use 'hg identify' to generate .hgrev file
[cython.git] / runtests.py
1 #!/usr/bin/python
2
3 import os
4 import sys
5 import re
6 import gc
7 import codecs
8 import shutil
9 import unittest
10 import doctest
11 import operator
12 import tempfile
13 try:
14     from StringIO import StringIO
15 except ImportError:
16     from io import StringIO
17
18 try:
19     import cPickle as pickle
20 except ImportError:
21     import pickle
22
23
24 WITH_CYTHON = True
25
26 from distutils.dist import Distribution
27 from distutils.core import Extension
28 from distutils.command.build_ext import build_ext as _build_ext
29 distutils_distro = Distribution()
30
31 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr']
32 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
33
34 # Lists external modules, and a matcher matching tests
35 # which should be excluded if the module is not present.
36 EXT_DEP_MODULES = {
37     'numpy' : re.compile('.*\.numpy_.*').match,
38     'pstats' : re.compile('.*\.pstats_.*').match,
39     'posix' : re.compile('.*\.posix_.*').match,
40 }
41
42 def get_numpy_include_dirs():
43     import numpy
44     return [numpy.get_include()]
45
46 EXT_DEP_INCLUDES = [
47     # test name matcher , callable returning list
48     (re.compile('numpy_.*').match, get_numpy_include_dirs),
49 ]
50
51 VER_DEP_MODULES = {
52     # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
53     # (2,4) : (operator.le, ...) excludes ... when PyVer <= 2.4.x
54     (2,5) : (operator.lt, lambda x: x in ['run.any',
55                                           'run.all',
56                                           ]),
57     (2,4) : (operator.le, lambda x: x in ['run.extern_builtins_T258'
58                                           ]),
59     (2,6) : (operator.lt, lambda x: x in ['run.print_function',
60                                           'run.cython3',
61                                           ]),
62     (3,): (operator.ge, lambda x: x in ['run.non_future_division',
63                                         'compile.extsetslice',
64                                         'compile.extdelslice']),
65 }
66
67 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
68 CFLAGS = os.getenv('CFLAGS', '').split()
69
70 class build_ext(_build_ext):
71     def build_extension(self, ext):
72         if ext.language == 'c++':
73             try:
74                 try: # Py2.7+ & Py3.2+ 
75                     compiler_obj = self.compiler_obj
76                 except AttributeError:
77                     compiler_obj = self.compiler
78                 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
79             except Exception:
80                 pass
81         _build_ext.build_extension(self, ext)
82
83 class ErrorWriter(object):
84     match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
85     def __init__(self):
86         self.output = []
87         self.write = self.output.append
88
89     def _collect(self, collect_errors, collect_warnings):
90         s = ''.join(self.output)
91         result = []
92         for line in s.split('\n'):
93             match = self.match_error(line)
94             if match:
95                 is_warning, line, column, message = match.groups()
96                 if (is_warning and collect_warnings) or \
97                         (not is_warning and collect_errors):
98                     result.append( (int(line), int(column), message.strip()) )
99         result.sort()
100         return [ "%d:%d: %s" % values for values in result ]
101
102     def geterrors(self):
103         return self._collect(True, False)
104
105     def getwarnings(self):
106         return self._collect(False, True)
107
108     def getall(self):
109         return self._collect(True, True)
110
111 class TestBuilder(object):
112     def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
113                  cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
114                  languages, test_bugs, fork):
115         self.rootdir = rootdir
116         self.workdir = workdir
117         self.selectors = selectors
118         self.exclude_selectors = exclude_selectors
119         self.annotate = annotate
120         self.cleanup_workdir = cleanup_workdir
121         self.cleanup_sharedlibs = cleanup_sharedlibs
122         self.with_pyregr = with_pyregr
123         self.cython_only = cython_only
124         self.languages = languages
125         self.test_bugs = test_bugs
126         self.fork = fork
127
128     def build_suite(self):
129         suite = unittest.TestSuite()
130         test_dirs = TEST_DIRS
131         filenames = os.listdir(self.rootdir)
132         filenames.sort()
133         for filename in filenames:
134             if not WITH_CYTHON and filename == "errors":
135                 # we won't get any errors without running Cython
136                 continue
137             path = os.path.join(self.rootdir, filename)
138             if os.path.isdir(path) and filename in test_dirs:
139                 if filename == 'pyregr' and not self.with_pyregr:
140                     continue
141                 suite.addTest(
142                     self.handle_directory(path, filename))
143         if sys.platform not in ['win32'] and sys.version_info[0] < 3:
144             # Non-Windows makefile, can't run Cython under Py3.
145             if [1 for selector in self.selectors if selector("embedded")]:
146                 suite.addTest(unittest.makeSuite(EmbedTest))
147         return suite
148
149     def handle_directory(self, path, context):
150         workdir = os.path.join(self.workdir, context)
151         if not os.path.exists(workdir):
152             os.makedirs(workdir)
153
154         expect_errors = (context == 'errors')
155         suite = unittest.TestSuite()
156         filenames = os.listdir(path)
157         filenames.sort()
158         for filename in filenames:
159             if not (filename.endswith(".pyx") or filename.endswith(".py")):
160                 continue
161             if filename.startswith('.'): continue # certain emacs backup files
162             if context == 'pyregr' and not filename.startswith('test_'):
163                 continue
164             module = os.path.splitext(filename)[0]
165             fqmodule = "%s.%s" % (context, module)
166             if not [ 1 for match in self.selectors
167                      if match(fqmodule) ]:
168                 continue
169             if self.exclude_selectors:
170                 if [1 for match in self.exclude_selectors if match(fqmodule)]:
171                     continue
172             if context in TEST_RUN_DIRS:
173                 if module.startswith("test_"):
174                     test_class = CythonUnitTestCase
175                 else:
176                     test_class = CythonRunTestCase
177             else:
178                 test_class = CythonCompileTestCase
179             for test in self.build_tests(test_class, path, workdir,
180                                          module, expect_errors):
181                 suite.addTest(test)
182         return suite
183
184     def build_tests(self, test_class, path, workdir, module, expect_errors):
185         if expect_errors:
186             if 'cpp' in module and 'cpp' in self.languages:
187                 languages = ['cpp']
188             else:
189                 languages = self.languages[:1]
190         else:
191             languages = self.languages
192         if 'cpp' in module and 'c' in languages:
193             languages = list(languages)
194             languages.remove('c')
195         tests = [ self.build_test(test_class, path, workdir, module,
196                                   language, expect_errors)
197                   for language in languages ]
198         return tests
199
200     def build_test(self, test_class, path, workdir, module,
201                    language, expect_errors):
202         workdir = os.path.join(workdir, language)
203         if not os.path.exists(workdir):
204             os.makedirs(workdir)
205         return test_class(path, workdir, module,
206                           language=language,
207                           expect_errors=expect_errors,
208                           annotate=self.annotate,
209                           cleanup_workdir=self.cleanup_workdir,
210                           cleanup_sharedlibs=self.cleanup_sharedlibs,
211                           cython_only=self.cython_only,
212                           fork=self.fork)
213
214 class CythonCompileTestCase(unittest.TestCase):
215     def __init__(self, test_directory, workdir, module, language='c',
216                  expect_errors=False, annotate=False, cleanup_workdir=True,
217                  cleanup_sharedlibs=True, cython_only=False, fork=True):
218         self.test_directory = test_directory
219         self.workdir = workdir
220         self.module = module
221         self.language = language
222         self.expect_errors = expect_errors
223         self.annotate = annotate
224         self.cleanup_workdir = cleanup_workdir
225         self.cleanup_sharedlibs = cleanup_sharedlibs
226         self.cython_only = cython_only
227         self.fork = fork
228         unittest.TestCase.__init__(self)
229
230     def shortDescription(self):
231         return "compiling (%s) %s" % (self.language, self.module)
232
233     def setUp(self):
234         if self.workdir not in sys.path:
235             sys.path.insert(0, self.workdir)
236
237     def tearDown(self):
238         try:
239             sys.path.remove(self.workdir)
240         except ValueError:
241             pass
242         try:
243             del sys.modules[self.module]
244         except KeyError:
245             pass
246         cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
247         cleanup_lib_files = self.cleanup_sharedlibs
248         if os.path.exists(self.workdir):
249             for rmfile in os.listdir(self.workdir):
250                 if not cleanup_c_files:
251                     if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
252                         continue
253                 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
254                     continue
255                 if self.annotate and rmfile.endswith(".html"):
256                     continue
257                 try:
258                     rmfile = os.path.join(self.workdir, rmfile)
259                     if os.path.isdir(rmfile):
260                         shutil.rmtree(rmfile, ignore_errors=True)
261                     else:
262                         os.remove(rmfile)
263                 except IOError:
264                     pass
265         else:
266             os.makedirs(self.workdir)
267
268     def runTest(self):
269         self.runCompileTest()
270
271     def runCompileTest(self):
272         self.compile(self.test_directory, self.module, self.workdir,
273                      self.test_directory, self.expect_errors, self.annotate)
274
275     def find_module_source_file(self, source_file):
276         if not os.path.exists(source_file):
277             source_file = source_file[:-1]
278         return source_file
279
280     def build_target_filename(self, module_name):
281         target = '%s.%s' % (module_name, self.language)
282         return target
283
284     def copy_related_files(self, test_directory, target_directory, module_name):
285         is_related = re.compile('%s_.*[.].*' % module_name).match
286         for filename in os.listdir(test_directory):
287             if is_related(filename):
288                 shutil.copy(os.path.join(test_directory, filename),
289                             target_directory)
290
291     def find_source_files(self, workdir, module_name):
292         is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
293         return [self.build_target_filename(module_name)] + [
294             filename for filename in os.listdir(workdir)
295             if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
296
297     def split_source_and_output(self, test_directory, module, workdir):
298         source_file = os.path.join(test_directory, module) + '.pyx'
299         source_and_output = codecs.open(
300             self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
301         out = codecs.open(os.path.join(workdir, module + '.pyx'),
302                           'w', 'ISO-8859-1')
303         for line in source_and_output:
304             last_line = line
305             if line.startswith("_ERRORS"):
306                 out.close()
307                 out = ErrorWriter()
308             else:
309                 out.write(line)
310         try:
311             geterrors = out.geterrors
312         except AttributeError:
313             return []
314         else:
315             return geterrors()
316
317     def run_cython(self, test_directory, module, targetdir, incdir, annotate):
318         include_dirs = INCLUDE_DIRS[:]
319         if incdir:
320             include_dirs.append(incdir)
321         source = self.find_module_source_file(
322             os.path.join(test_directory, module + '.pyx'))
323         target = os.path.join(targetdir, self.build_target_filename(module))
324         options = CompilationOptions(
325             pyrex_default_options,
326             include_path = include_dirs,
327             output_file = target,
328             annotate = annotate,
329             use_listing_file = False,
330             cplus = self.language == 'cpp',
331             generate_pxi = False,
332             evaluate_tree_assertions = True,
333             )
334         cython_compile(source, options=options,
335                        full_module_name=module)
336
337     def run_distutils(self, test_directory, module, workdir, incdir):
338         cwd = os.getcwd()
339         os.chdir(workdir)
340         try:
341             build_extension = build_ext(distutils_distro)
342             build_extension.include_dirs = INCLUDE_DIRS[:]
343             if incdir:
344                 build_extension.include_dirs.append(incdir)
345             build_extension.finalize_options()
346             ext_include_dirs = []
347             for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
348                 if match(module):
349                     ext_include_dirs += get_additional_include_dirs()
350             self.copy_related_files(test_directory, workdir, module)
351             extension = Extension(
352                 module,
353                 sources = self.find_source_files(workdir, module),
354                 include_dirs = ext_include_dirs,
355                 extra_compile_args = CFLAGS,
356                 )
357             if self.language == 'cpp':
358                 extension.language = 'c++'
359             build_extension.extensions = [extension]
360             build_extension.build_temp = workdir
361             build_extension.build_lib  = workdir
362             build_extension.run()
363         finally:
364             os.chdir(cwd)
365
366     def compile(self, test_directory, module, workdir, incdir,
367                 expect_errors, annotate):
368         expected_errors = errors = ()
369         if expect_errors:
370             expected_errors = self.split_source_and_output(
371                 test_directory, module, workdir)
372             test_directory = workdir
373
374         if WITH_CYTHON:
375             old_stderr = sys.stderr
376             try:
377                 sys.stderr = ErrorWriter()
378                 self.run_cython(test_directory, module, workdir, incdir, annotate)
379                 errors = sys.stderr.geterrors()
380             finally:
381                 sys.stderr = old_stderr
382
383         if errors or expected_errors:
384             try:
385                 for expected, error in zip(expected_errors, errors):
386                     self.assertEquals(expected, error)
387                 if len(errors) < len(expected_errors):
388                     expected_error = expected_errors[len(errors)]
389                     self.assertEquals(expected_error, None)
390                 elif len(errors) > len(expected_errors):
391                     unexpected_error = errors[len(expected_errors)]
392                     self.assertEquals(None, unexpected_error)
393             except AssertionError:
394                 print("\n=== Expected errors: ===")
395                 print('\n'.join(expected_errors))
396                 print("\n\n=== Got errors: ===")
397                 print('\n'.join(errors))
398                 print('\n')
399                 raise
400         else:
401             if not self.cython_only:
402                 self.run_distutils(test_directory, module, workdir, incdir)
403
404 class CythonRunTestCase(CythonCompileTestCase):
405     def shortDescription(self):
406         return "compiling (%s) and running %s" % (self.language, self.module)
407
408     def run(self, result=None):
409         if result is None:
410             result = self.defaultTestResult()
411         result.startTest(self)
412         try:
413             self.setUp()
414             self.runCompileTest()
415             if not self.cython_only:
416                 self.run_doctests(self.module, result)
417         except Exception:
418             result.addError(self, sys.exc_info())
419             result.stopTest(self)
420         try:
421             self.tearDown()
422         except Exception:
423             pass
424
425     def run_doctests(self, module_name, result):
426         if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
427             doctest.DocTestSuite(module_name).run(result)
428             gc.collect()
429             return
430
431         # fork to make sure we do not keep the tested module loaded
432         result_handle, result_file = tempfile.mkstemp()
433         os.close(result_handle)
434         child_id = os.fork()
435         if not child_id:
436             result_code = 0
437             try:
438                 try:
439                     tests = None
440                     try:
441                         partial_result = PartialTestResult(result)
442                         tests = doctest.DocTestSuite(module_name)
443                         tests.run(partial_result)
444                         gc.collect()
445                     except Exception:
446                         if tests is None:
447                             # importing failed, try to fake a test class
448                             tests = _FakeClass(
449                                 failureException=sys.exc_info()[1],
450                                 _shortDescription=self.shortDescription(),
451                                 module_name=None)
452                         partial_result.addError(tests, sys.exc_info())
453                         result_code = 1
454                     output = open(result_file, 'wb')
455                     pickle.dump(partial_result.data(), output)
456                 except:
457                     import traceback
458                     traceback.print_exc()
459             finally:
460                 try: output.close()
461                 except: pass
462                 os._exit(result_code)
463
464         try:
465             cid, result_code = os.waitpid(child_id, 0)
466             # os.waitpid returns the child's result code in the
467             # upper byte of result_code, and the signal it was
468             # killed by in the lower byte
469             if result_code & 255:
470                 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
471                                 (module_name, result_code & 255))
472             result_code = result_code >> 8
473             if result_code in (0,1):
474                 input = open(result_file, 'rb')
475                 try:
476                     PartialTestResult.join_results(result, pickle.load(input))
477                 finally:
478                     input.close()
479             if result_code:
480                 raise Exception("Tests in module '%s' exited with status %d" %
481                                 (module_name, result_code))
482         finally:
483             try: os.unlink(result_file)
484             except: pass
485
486
487 is_private_field = re.compile('^_[^_]').match
488
489 class _FakeClass(object):
490     def __init__(self, **kwargs):
491         self._shortDescription = kwargs.get('module_name')
492         self.__dict__.update(kwargs)
493     def shortDescription(self):
494         return self._shortDescription
495
496 try: # Py2.7+ and Py3.2+
497     from unittest.runner import _TextTestResult
498 except ImportError:
499     from unittest import _TextTestResult
500
501 class PartialTestResult(_TextTestResult):
502     def __init__(self, base_result):
503         _TextTestResult.__init__(
504             self, self._StringIO(), True,
505             base_result.dots + base_result.showAll*2)
506
507     def strip_error_results(self, results):
508         for test_case, error in results:
509             for attr_name in filter(is_private_field, dir(test_case)):
510                 if attr_name == '_dt_test':
511                     test_case._dt_test = _FakeClass(
512                         name=test_case._dt_test.name)
513                 elif attr_name != '_shortDescription':
514                     setattr(test_case, attr_name, None)
515
516     def data(self):
517         self.strip_error_results(self.failures)
518         self.strip_error_results(self.errors)
519         return (self.failures, self.errors, self.testsRun,
520                 self.stream.getvalue())
521
522     def join_results(result, data):
523         """Static method for merging the result back into the main
524         result object.
525         """
526         failures, errors, tests_run, output = data
527         if output:
528             result.stream.write(output)
529         result.errors.extend(errors)
530         result.failures.extend(failures)
531         result.testsRun += tests_run
532
533     join_results = staticmethod(join_results)
534
535     class _StringIO(StringIO):
536         def writeln(self, line):
537             self.write("%s\n" % line)
538
539
540 class CythonUnitTestCase(CythonCompileTestCase):
541     def shortDescription(self):
542         return "compiling (%s) tests in %s" % (self.language, self.module)
543
544     def run(self, result=None):
545         if result is None:
546             result = self.defaultTestResult()
547         result.startTest(self)
548         try:
549             self.setUp()
550             self.runCompileTest()
551             unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
552         except Exception:
553             result.addError(self, sys.exc_info())
554             result.stopTest(self)
555         try:
556             self.tearDown()
557         except Exception:
558             pass
559
560 def collect_unittests(path, module_prefix, suite, selectors):
561     def file_matches(filename):
562         return filename.startswith("Test") and filename.endswith(".py")
563
564     def package_matches(dirname):
565         return dirname == "Tests"
566
567     loader = unittest.TestLoader()
568
569     skipped_dirs = []
570
571     for dirpath, dirnames, filenames in os.walk(path):
572         if dirpath != path and "__init__.py" not in filenames:
573             skipped_dirs.append(dirpath + os.path.sep)
574             continue
575         skip = False
576         for dir in skipped_dirs:
577             if dirpath.startswith(dir):
578                 skip = True
579         if skip:
580             continue
581         parentname = os.path.split(dirpath)[-1]
582         if package_matches(parentname):
583             for f in filenames:
584                 if file_matches(f):
585                     filepath = os.path.join(dirpath, f)[:-len(".py")]
586                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
587                     if not [ 1 for match in selectors if match(modulename) ]:
588                         continue
589                     module = __import__(modulename)
590                     for x in modulename.split('.')[1:]:
591                         module = getattr(module, x)
592                     suite.addTests([loader.loadTestsFromModule(module)])
593
594 def collect_doctests(path, module_prefix, suite, selectors):
595     def package_matches(dirname):
596         return dirname not in ("Mac", "Distutils", "Plex")
597     def file_matches(filename):
598         return (filename.endswith(".py") and not ('~' in filename
599                 or '#' in filename or filename.startswith('.')))
600     import doctest, types
601     for dirpath, dirnames, filenames in os.walk(path):
602         parentname = os.path.split(dirpath)[-1]
603         if package_matches(parentname):
604             for f in filenames:
605                 if file_matches(f):
606                     if not f.endswith('.py'): continue
607                     filepath = os.path.join(dirpath, f)[:-len(".py")]
608                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
609                     if not [ 1 for match in selectors if match(modulename) ]:
610                         continue
611                     module = __import__(modulename)
612                     for x in modulename.split('.')[1:]:
613                         module = getattr(module, x)
614                     if hasattr(module, "__doc__") or hasattr(module, "__test__"):
615                         try:
616                             suite.addTest(doctest.DocTestSuite(module))
617                         except ValueError: # no tests
618                             pass
619
620 # TODO: Support cython_freeze needed here as well.
621 # TODO: Windows support.
622
623 class EmbedTest(unittest.TestCase):
624     
625     working_dir = "Demos/embed"
626     
627     def setUp(self):
628         self.old_dir = os.getcwd()
629         os.chdir(self.working_dir)
630         os.system(
631             "make PYTHON='%s' clean > /dev/null" % sys.executable)
632     
633     def tearDown(self):
634         try:
635             os.system(
636                 "make PYTHON='%s' clean > /dev/null" % sys.executable)
637         except:
638             pass
639         os.chdir(self.old_dir)
640         
641     def test_embed(self):
642         self.assert_(os.system(
643             "make PYTHON='%s' test > make.output" % sys.executable) == 0)
644         try:
645             os.remove('make.output')
646         except OSError:
647             pass
648
649 class MissingDependencyExcluder:
650     def __init__(self, deps):
651         # deps: { module name : matcher func }
652         self.exclude_matchers = []
653         for mod, matcher in deps.items():
654             try:
655                 __import__(mod)
656             except ImportError:
657                 self.exclude_matchers.append(matcher)
658         self.tests_missing_deps = []
659     def __call__(self, testname):
660         for matcher in self.exclude_matchers:
661             if matcher(testname):
662                 self.tests_missing_deps.append(testname)
663                 return True
664         return False
665
666 class VersionDependencyExcluder:
667     def __init__(self, deps):
668         # deps: { version : matcher func }
669         from sys import version_info
670         self.exclude_matchers = []
671         for ver, (compare, matcher) in deps.items():
672             if compare(version_info, ver):
673                 self.exclude_matchers.append(matcher)
674         self.tests_missing_deps = []
675     def __call__(self, testname):
676         for matcher in self.exclude_matchers:
677             if matcher(testname):
678                 self.tests_missing_deps.append(testname)
679                 return True
680         return False
681
682 class FileListExcluder:
683
684     def __init__(self, list_file):
685         self.excludes = {}
686         for line in open(list_file).readlines():
687             line = line.strip()
688             if line and line[0] != '#':
689                 self.excludes[line.split()[0]] = True
690                 
691     def __call__(self, testname):
692         return testname in self.excludes or testname.split('.')[-1] in self.excludes
693
694 def refactor_for_py3(distdir, cy3_dir):
695     # need to convert Cython sources first
696     import lib2to3.refactor
697     from distutils.util import copydir_run_2to3
698     fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
699                if fix.split('fix_')[-1] not in ('next',)
700                ]
701     if not os.path.exists(cy3_dir):
702         os.makedirs(cy3_dir)
703     import distutils.log as dlog
704     dlog.set_threshold(dlog.DEBUG)
705     copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
706                      template = '''
707                      global-exclude *
708                      graft Cython
709                      recursive-exclude Cython *
710                      recursive-include Cython *.py *.pyx *.pxd
711                      ''')
712     sys.path.insert(0, cy3_dir)
713
714
715 if __name__ == '__main__':
716     from optparse import OptionParser
717     parser = OptionParser()
718     parser.add_option("--no-cleanup", dest="cleanup_workdir",
719                       action="store_false", default=True,
720                       help="do not delete the generated C files (allows passing --no-cython on next run)")
721     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
722                       action="store_false", default=True,
723                       help="do not delete the generated shared libary files (allows manual module experimentation)")
724     parser.add_option("--no-cython", dest="with_cython",
725                       action="store_false", default=True,
726                       help="do not run the Cython compiler, only the C compiler")
727     parser.add_option("--no-c", dest="use_c",
728                       action="store_false", default=True,
729                       help="do not test C compilation")
730     parser.add_option("--no-cpp", dest="use_cpp",
731                       action="store_false", default=True,
732                       help="do not test C++ compilation")
733     parser.add_option("--no-unit", dest="unittests",
734                       action="store_false", default=True,
735                       help="do not run the unit tests")
736     parser.add_option("--no-doctest", dest="doctests",
737                       action="store_false", default=True,
738                       help="do not run the doctests")
739     parser.add_option("--no-file", dest="filetests",
740                       action="store_false", default=True,
741                       help="do not run the file based tests")
742     parser.add_option("--no-pyregr", dest="pyregr",
743                       action="store_false", default=True,
744                       help="do not run the regression tests of CPython in tests/pyregr/")    
745     parser.add_option("--cython-only", dest="cython_only",
746                       action="store_true", default=False,
747                       help="only compile pyx to c, do not run C compiler or run the tests")
748     parser.add_option("--no-refnanny", dest="with_refnanny",
749                       action="store_false", default=True,
750                       help="do not regression test reference counting")
751     parser.add_option("--no-fork", dest="fork",
752                       action="store_false", default=True,
753                       help="do not fork to run tests")
754     parser.add_option("--sys-pyregr", dest="system_pyregr",
755                       action="store_true", default=False,
756                       help="run the regression tests of the CPython installation")
757     parser.add_option("-x", "--exclude", dest="exclude",
758                       action="append", metavar="PATTERN",
759                       help="exclude tests matching the PATTERN")
760     parser.add_option("-C", "--coverage", dest="coverage",
761                       action="store_true", default=False,
762                       help="collect source coverage data for the Compiler")
763     parser.add_option("--coverage-xml", dest="coverage_xml",
764                       action="store_true", default=False,
765                       help="collect source coverage data for the Compiler in XML format")
766     parser.add_option("-A", "--annotate", dest="annotate_source",
767                       action="store_true", default=True,
768                       help="generate annotated HTML versions of the test source files")
769     parser.add_option("--no-annotate", dest="annotate_source",
770                       action="store_false",
771                       help="do not generate annotated HTML versions of the test source files")
772     parser.add_option("-v", "--verbose", dest="verbosity",
773                       action="count", default=0,
774                       help="display test progress, pass twice to print test names")
775     parser.add_option("-T", "--ticket", dest="tickets",
776                       action="append",
777                       help="a bug ticket number to run the respective test in 'tests/*'")
778     parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
779                       help="write test results in XML to directory DIR")
780     parser.add_option("--exit-ok", dest="exit_ok", default=False,
781                       action="store_true",
782                       help="exit without error code even on test failures")
783
784     options, cmd_args = parser.parse_args()
785
786     DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
787     ROOTDIR = os.path.join(DISTDIR, 'tests')
788     WORKDIR = os.path.join(os.getcwd(), 'BUILD')
789
790     if sys.version_info[0] >= 3:
791         options.doctests = False
792         if options.with_cython:
793             try:
794                 # try if Cython is installed in a Py3 version
795                 import Cython.Compiler.Main
796             except Exception:
797                 cy_modules = [ name for name in sys.modules
798                                if name == 'Cython' or name.startswith('Cython.') ]
799                 for name in cy_modules:
800                     del sys.modules[name]
801                 # hasn't been refactored yet - do it now
802                 cy3_dir = os.path.join(WORKDIR, 'Cy3')
803                 if sys.version_info >= (3,1):
804                     refactor_for_py3(DISTDIR, cy3_dir)
805                 elif os.path.isdir(cy3_dir):
806                     sys.path.insert(0, cy3_dir)
807                 else:
808                     options.with_cython = False
809
810     WITH_CYTHON = options.with_cython
811
812     if options.coverage or options.coverage_xml:
813         if not WITH_CYTHON:
814             options.coverage = options.coverage_xml = False
815         else:
816             from coverage import coverage as _coverage
817             coverage = _coverage(branch=True)
818             coverage.erase()
819             coverage.start()
820
821     if WITH_CYTHON:
822         from Cython.Compiler.Main import \
823             CompilationOptions, \
824             default_options as pyrex_default_options, \
825             compile as cython_compile
826         from Cython.Compiler import Errors
827         Errors.LEVEL = 0 # show all warnings
828         from Cython.Compiler import Options
829         Options.generate_cleanup_code = 3   # complete cleanup code
830         from Cython.Compiler import DebugFlags
831         DebugFlags.debug_temp_code_comments = 1
832
833     # RUN ALL TESTS!
834     UNITTEST_MODULE = "Cython"
835     UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
836     if WITH_CYTHON:
837         if os.path.exists(WORKDIR):
838             for path in os.listdir(WORKDIR):
839                 if path in ("support", "Cy3"): continue
840                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
841     if not os.path.exists(WORKDIR):
842         os.makedirs(WORKDIR)
843
844     if WITH_CYTHON:
845         from Cython.Compiler.Version import version
846         sys.stderr.write("Running tests against Cython %s\n" % version)
847     else:
848         sys.stderr.write("Running tests without Cython.\n")
849     sys.stderr.write("Python %s\n" % sys.version)
850     sys.stderr.write("\n")
851
852     if options.with_refnanny:
853         from pyximport.pyxbuild import pyx_to_dll
854         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
855                              build_in_temp=True,
856                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
857         sys.path.insert(0, os.path.split(libpath)[0])
858         CFLAGS.append("-DCYTHON_REFNANNY=1")
859
860     if options.xml_output_dir and options.fork:
861         # doesn't currently work together
862         sys.stderr.write("Disabling forked testing to support XML test output\n")
863         options.fork = False
864
865     test_bugs = False
866     if options.tickets:
867         for ticket_number in options.tickets:
868             test_bugs = True
869             cmd_args.append('.*T%s$' % ticket_number)
870     if not test_bugs:
871         for selector in cmd_args:
872             if selector.startswith('bugs'):
873                 test_bugs = True
874
875     import re
876     selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
877     if not selectors:
878         selectors = [ lambda x:True ]
879
880     # Chech which external modules are not present and exclude tests
881     # which depends on them (by prefix)
882
883     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES) 
884     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES) 
885     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
886
887     if options.exclude:
888         exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
889     
890     if not test_bugs:
891         exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
892     
893     if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
894         exclude_selectors += [ lambda x: x == "run.specialfloat" ]
895
896     languages = []
897     if options.use_c:
898         languages.append('c')
899     if options.use_cpp:
900         languages.append('cpp')
901
902     test_suite = unittest.TestSuite()
903
904     if options.unittests:
905         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
906
907     if options.doctests:
908         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
909
910     if options.filetests and languages:
911         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
912                                 options.annotate_source, options.cleanup_workdir,
913                                 options.cleanup_sharedlibs, options.pyregr,
914                                 options.cython_only, languages, test_bugs,
915                                 options.fork)
916         test_suite.addTest(filetests.build_suite())
917
918     if options.system_pyregr and languages:
919         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
920                                 options.annotate_source, options.cleanup_workdir,
921                                 options.cleanup_sharedlibs, True,
922                                 options.cython_only, languages, test_bugs,
923                                 options.fork)
924         test_suite.addTest(
925             filetests.handle_directory(
926                 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
927                 'pyregr'))
928
929     if options.xml_output_dir:
930         from Cython.Tests.xmlrunner import XMLTestRunner
931         test_runner = XMLTestRunner(output=options.xml_output_dir,
932                                     verbose=options.verbosity > 0)
933     else:
934         test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
935
936     result = test_runner.run(test_suite)
937
938     if options.coverage or options.coverage_xml:
939         coverage.stop()
940         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
941         modules = [ module for name, module in sys.modules.items()
942                     if module is not None and
943                     name.startswith('Cython.Compiler.') and 
944                     name[len('Cython.Compiler.'):] not in ignored_modules ]
945         if options.coverage:
946             coverage.report(modules, show_missing=0)
947         if options.coverage_xml:
948             coverage.xml_report(modules, outfile="coverage-report.xml")
949
950     if missing_dep_excluder.tests_missing_deps:
951         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
952         for test in missing_dep_excluder.tests_missing_deps:
953             sys.stderr.write("   %s\n" % test)
954
955     if options.with_refnanny:
956         import refnanny
957         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
958
959     if options.exit_ok:
960         sys.exit(0)
961     else:
962         sys.exit(not result.wasSuccessful())