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