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