merged in latest cython-devel
[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         try:
637             os.remove('make.output')
638         except OSError:
639             pass
640
641 class MissingDependencyExcluder:
642     def __init__(self, deps):
643         # deps: { module name : matcher func }
644         self.exclude_matchers = []
645         for mod, matcher in deps.items():
646             try:
647                 __import__(mod)
648             except ImportError:
649                 self.exclude_matchers.append(matcher)
650         self.tests_missing_deps = []
651     def __call__(self, testname):
652         for matcher in self.exclude_matchers:
653             if matcher(testname):
654                 self.tests_missing_deps.append(testname)
655                 return True
656         return False
657
658 class VersionDependencyExcluder:
659     def __init__(self, deps):
660         # deps: { version : matcher func }
661         from sys import version_info
662         self.exclude_matchers = []
663         for ver, (compare, matcher) in deps.items():
664             if compare(version_info, ver):
665                 self.exclude_matchers.append(matcher)
666         self.tests_missing_deps = []
667     def __call__(self, testname):
668         for matcher in self.exclude_matchers:
669             if matcher(testname):
670                 self.tests_missing_deps.append(testname)
671                 return True
672         return False
673
674 class FileListExcluder:
675
676     def __init__(self, list_file):
677         self.excludes = {}
678         for line in open(list_file).readlines():
679             line = line.strip()
680             if line and line[0] != '#':
681                 self.excludes[line.split()[0]] = True
682                 
683     def __call__(self, testname):
684         return testname in self.excludes or testname.split('.')[-1] in self.excludes
685
686 def refactor_for_py3(distdir, cy3_dir):
687     # need to convert Cython sources first
688     import lib2to3.refactor
689     from distutils.util import copydir_run_2to3
690     fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
691                if fix.split('fix_')[-1] not in ('next',)
692                ]
693     if not os.path.exists(cy3_dir):
694         os.makedirs(cy3_dir)
695     import distutils.log as dlog
696     dlog.set_threshold(dlog.DEBUG)
697     copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
698                      template = '''
699                      global-exclude *
700                      graft Cython
701                      recursive-exclude Cython *
702                      recursive-include Cython *.py *.pyx *.pxd
703                      ''')
704     sys.path.insert(0, cy3_dir)
705
706
707 if __name__ == '__main__':
708     from optparse import OptionParser
709     parser = OptionParser()
710     parser.add_option("--no-cleanup", dest="cleanup_workdir",
711                       action="store_false", default=True,
712                       help="do not delete the generated C files (allows passing --no-cython on next run)")
713     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
714                       action="store_false", default=True,
715                       help="do not delete the generated shared libary files (allows manual module experimentation)")
716     parser.add_option("--no-cython", dest="with_cython",
717                       action="store_false", default=True,
718                       help="do not run the Cython compiler, only the C compiler")
719     parser.add_option("--no-c", dest="use_c",
720                       action="store_false", default=True,
721                       help="do not test C compilation")
722     parser.add_option("--no-cpp", dest="use_cpp",
723                       action="store_false", default=True,
724                       help="do not test C++ compilation")
725     parser.add_option("--no-unit", dest="unittests",
726                       action="store_false", default=True,
727                       help="do not run the unit tests")
728     parser.add_option("--no-doctest", dest="doctests",
729                       action="store_false", default=True,
730                       help="do not run the doctests")
731     parser.add_option("--no-file", dest="filetests",
732                       action="store_false", default=True,
733                       help="do not run the file based tests")
734     parser.add_option("--no-pyregr", dest="pyregr",
735                       action="store_false", default=True,
736                       help="do not run the regression tests of CPython in tests/pyregr/")    
737     parser.add_option("--cython-only", dest="cython_only",
738                       action="store_true", default=False,
739                       help="only compile pyx to c, do not run C compiler or run the tests")
740     parser.add_option("--no-refnanny", dest="with_refnanny",
741                       action="store_false", default=True,
742                       help="do not regression test reference counting")
743     parser.add_option("--no-fork", dest="fork",
744                       action="store_false", default=True,
745                       help="do not fork to run tests")
746     parser.add_option("--sys-pyregr", dest="system_pyregr",
747                       action="store_true", default=False,
748                       help="run the regression tests of the CPython installation")
749     parser.add_option("-x", "--exclude", dest="exclude",
750                       action="append", metavar="PATTERN",
751                       help="exclude tests matching the PATTERN")
752     parser.add_option("-C", "--coverage", dest="coverage",
753                       action="store_true", default=False,
754                       help="collect source coverage data for the Compiler")
755     parser.add_option("-A", "--annotate", dest="annotate_source",
756                       action="store_true", default=True,
757                       help="generate annotated HTML versions of the test source files")
758     parser.add_option("--no-annotate", dest="annotate_source",
759                       action="store_false",
760                       help="do not generate annotated HTML versions of the test source files")
761     parser.add_option("-v", "--verbose", dest="verbosity",
762                       action="count", default=0,
763                       help="display test progress, pass twice to print test names")
764     parser.add_option("-T", "--ticket", dest="tickets",
765                       action="append",
766                       help="a bug ticket number to run the respective test in 'tests/*'")
767     parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
768                       help="write test results in XML to directory DIR")
769     parser.add_option("--exit-ok", dest="exit_ok", default=False,
770                       action="store_true",
771                       help="exit without error code even on test failures")
772
773     options, cmd_args = parser.parse_args()
774
775     DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
776     ROOTDIR = os.path.join(DISTDIR, 'tests')
777     WORKDIR = os.path.join(os.getcwd(), 'BUILD')
778
779     if sys.version_info[0] >= 3:
780         options.doctests = False
781         options.pyregr   = False
782         if options.with_cython:
783             try:
784                 # try if Cython is installed in a Py3 version
785                 import Cython.Compiler.Main
786             except Exception:
787                 cy_modules = [ name for name in sys.modules
788                                if name == 'Cython' or name.startswith('Cython.') ]
789                 for name in cy_modules:
790                     del sys.modules[name]
791                 # hasn't been refactored yet - do it now
792                 cy3_dir = os.path.join(WORKDIR, 'Cy3')
793                 if sys.version_info >= (3,1):
794                     refactor_for_py3(DISTDIR, cy3_dir)
795                 elif os.path.isdir(cy3_dir):
796                     sys.path.insert(0, cy3_dir)
797                 else:
798                     options.with_cython = False
799
800     WITH_CYTHON = options.with_cython
801
802     if options.coverage:
803         if not WITH_CYTHON:
804             options.coverage = False
805         else:
806             import coverage
807             coverage.erase()
808             coverage.start()
809
810     if WITH_CYTHON:
811         from Cython.Compiler.Main import \
812             CompilationOptions, \
813             default_options as pyrex_default_options, \
814             compile as cython_compile
815         from Cython.Compiler import Errors
816         Errors.LEVEL = 0 # show all warnings
817         from Cython.Compiler import Options
818         Options.generate_cleanup_code = 3   # complete cleanup code
819         from Cython.Compiler import DebugFlags
820         DebugFlags.debug_temp_code_comments = 1
821
822     # RUN ALL TESTS!
823     UNITTEST_MODULE = "Cython"
824     UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
825     if WITH_CYTHON:
826         if os.path.exists(WORKDIR):
827             for path in os.listdir(WORKDIR):
828                 if path in ("support", "Cy3"): continue
829                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
830     if not os.path.exists(WORKDIR):
831         os.makedirs(WORKDIR)
832
833     if WITH_CYTHON:
834         from Cython.Compiler.Version import version
835         sys.stderr.write("Running tests against Cython %s\n" % version)
836     else:
837         sys.stderr.write("Running tests without Cython.\n")
838     sys.stderr.write("Python %s\n" % sys.version)
839     sys.stderr.write("\n")
840
841     if options.with_refnanny:
842         from pyximport.pyxbuild import pyx_to_dll
843         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
844                              build_in_temp=True,
845                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
846         sys.path.insert(0, os.path.split(libpath)[0])
847         CFLAGS.append("-DCYTHON_REFNANNY=1")
848
849     if options.xml_output_dir and options.fork:
850         # doesn't currently work together
851         sys.stderr.write("Disabling forked testing to support XML test output\n")
852         options.fork = False
853
854     test_bugs = False
855     if options.tickets:
856         for ticket_number in options.tickets:
857             test_bugs = True
858             cmd_args.append('.*T%s$' % ticket_number)
859     if not test_bugs:
860         for selector in cmd_args:
861             if selector.startswith('bugs'):
862                 test_bugs = True
863
864     import re
865     selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
866     if not selectors:
867         selectors = [ lambda x:True ]
868
869     # Chech which external modules are not present and exclude tests
870     # which depends on them (by prefix)
871
872     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES) 
873     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES) 
874     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
875
876     if options.exclude:
877         exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
878     
879     if not test_bugs:
880         exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
881     
882     if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
883         exclude_selectors += [ lambda x: x == "run.specialfloat" ]
884
885     languages = []
886     if options.use_c:
887         languages.append('c')
888     if options.use_cpp:
889         languages.append('cpp')
890
891     test_suite = unittest.TestSuite()
892
893     if options.unittests:
894         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
895
896     if options.doctests:
897         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
898
899     if options.filetests and languages:
900         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
901                                 options.annotate_source, options.cleanup_workdir,
902                                 options.cleanup_sharedlibs, options.pyregr,
903                                 options.cython_only, languages, test_bugs,
904                                 options.fork)
905         test_suite.addTest(filetests.build_suite())
906
907     if options.system_pyregr and languages:
908         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
909                                 options.annotate_source, options.cleanup_workdir,
910                                 options.cleanup_sharedlibs, True,
911                                 options.cython_only, languages, test_bugs,
912                                 options.fork)
913         test_suite.addTest(
914             filetests.handle_directory(
915                 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
916                 'pyregr'))
917
918     if options.xml_output_dir:
919         from Cython.Tests.xmlrunner import XMLTestRunner
920         test_runner = XMLTestRunner(output=options.xml_output_dir,
921                                     verbose=options.verbosity > 0)
922     else:
923         test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
924
925     result = test_runner.run(test_suite)
926
927     if options.coverage:
928         coverage.stop()
929         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
930         modules = [ module for name, module in sys.modules.items()
931                     if module is not None and
932                     name.startswith('Cython.Compiler.') and 
933                     name[len('Cython.Compiler.'):] not in ignored_modules ]
934         coverage.report(modules, show_missing=0)
935
936     if missing_dep_excluder.tests_missing_deps:
937         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
938         for test in missing_dep_excluder.tests_missing_deps:
939             sys.stderr.write("   %s\n" % test)
940
941     if options.with_refnanny:
942         import refnanny
943         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
944
945     if options.exit_ok:
946         sys.exit(0)
947     else:
948         sys.exit(not result.wasSuccessful())