merge
[cython.git] / runtests.py
1 #!/usr/bin/python
2
3 import os
4 import sys
5 import re
6 import codecs
7 import shutil
8 import unittest
9 import doctest
10 import operator
11
12 WITH_CYTHON = True
13
14 from distutils.dist import Distribution
15 from distutils.core import Extension
16 from distutils.command.build_ext import build_ext as _build_ext
17 distutils_distro = Distribution()
18
19 TEST_DIRS = ['compile', 'errors', 'run', 'pyregr']
20 TEST_RUN_DIRS = ['run', 'pyregr']
21
22 # Lists external modules, and a matcher matching tests
23 # which should be excluded if the module is not present.
24 EXT_DEP_MODULES = {
25     'numpy' : re.compile('.*\.numpy_.*').match
26 }
27
28 def get_numpy_include_dirs():
29     import numpy
30     return [numpy.get_include()]
31
32 EXT_DEP_INCLUDES = [
33     # test name matcher , callable returning list
34     (re.compile('numpy_.*').match, get_numpy_include_dirs),
35 ]
36
37 VER_DEP_MODULES = {
38 # such as:
39 #    (2,4) : (operator.le, lambda x: x in ['run.set']),
40     (3,): (operator.ge, lambda x: x in ['run.non_future_division',
41                                         'compile.extsetslice',
42                                         'compile.extdelslice']),
43 }
44
45 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
46 CFLAGS = os.getenv('CFLAGS', '').split()
47
48 class build_ext(_build_ext):
49     def build_extension(self, ext):
50         if ext.language == 'c++':
51             try:
52                 self.compiler.compiler_so.remove('-Wstrict-prototypes')
53             except Exception:
54                 pass
55         _build_ext.build_extension(self, ext)
56
57 class ErrorWriter(object):
58     match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
59     def __init__(self):
60         self.output = []
61         self.write = self.output.append
62
63     def _collect(self, collect_errors, collect_warnings):
64         s = ''.join(self.output)
65         result = []
66         for line in s.split('\n'):
67             match = self.match_error(line)
68             if match:
69                 is_warning, line, column, message = match.groups()
70                 if (is_warning and collect_warnings) or \
71                         (not is_warning and collect_errors):
72                     result.append( (int(line), int(column), message.strip()) )
73         result.sort()
74         return [ "%d:%d: %s" % values for values in result ]
75
76     def geterrors(self):
77         return self._collect(True, False)
78
79     def getwarnings(self):
80         return self._collect(False, True)
81
82     def getall(self):
83         return self._collect(True, True)
84
85 class TestBuilder(object):
86     def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
87                  cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
88                  languages, test_bugs):
89         self.rootdir = rootdir
90         self.workdir = workdir
91         self.selectors = selectors
92         self.exclude_selectors = exclude_selectors
93         self.annotate = annotate
94         self.cleanup_workdir = cleanup_workdir
95         self.cleanup_sharedlibs = cleanup_sharedlibs
96         self.with_pyregr = with_pyregr
97         self.cython_only = cython_only
98         self.languages = languages
99         self.test_bugs = test_bugs
100
101     def build_suite(self):
102         suite = unittest.TestSuite()
103         test_dirs = TEST_DIRS
104         filenames = os.listdir(self.rootdir)
105         filenames.sort()
106         for filename in filenames:
107             if not WITH_CYTHON and filename == "errors":
108                 # we won't get any errors without running Cython
109                 continue
110             path = os.path.join(self.rootdir, filename)
111             if os.path.isdir(path) and filename in test_dirs:
112                 if filename == 'pyregr' and not self.with_pyregr:
113                     continue
114                 suite.addTest(
115                     self.handle_directory(path, filename))
116         return suite
117
118     def handle_directory(self, path, context):
119         workdir = os.path.join(self.workdir, context)
120         if not os.path.exists(workdir):
121             os.makedirs(workdir)
122
123         expect_errors = (context == 'errors')
124         suite = unittest.TestSuite()
125         filenames = os.listdir(path)
126         filenames.sort()
127         for filename in filenames:
128             if not (filename.endswith(".pyx") or filename.endswith(".py")):
129                 continue
130             if filename.startswith('.'): continue # certain emacs backup files
131             if context == 'pyregr' and not filename.startswith('test_'):
132                 continue
133             module = os.path.splitext(filename)[0]
134             fqmodule = "%s.%s" % (context, module)
135             if not [ 1 for match in self.selectors
136                      if match(fqmodule) ]:
137                 continue
138             if self.exclude_selectors:
139                 if [1 for match in self.exclude_selectors if match(fqmodule)]:
140                     continue
141             if context in TEST_RUN_DIRS:
142                 if module.startswith("test_"):
143                     test_class = CythonUnitTestCase
144                 else:
145                     test_class = CythonRunTestCase
146             else:
147                 test_class = CythonCompileTestCase
148             for test in self.build_tests(test_class, path, workdir,
149                                          module, expect_errors):
150                 suite.addTest(test)
151         return suite
152
153     def build_tests(self, test_class, path, workdir, module, expect_errors):
154         if expect_errors:
155             languages = self.languages[:1]
156         else:
157             languages = self.languages
158         if 'cpp' in module and 'c' in languages:
159             languages = list(languages)
160             languages.remove('c')
161         tests = [ self.build_test(test_class, path, workdir, module,
162                                   language, expect_errors)
163                   for language in languages ]
164         return tests
165
166     def build_test(self, test_class, path, workdir, module,
167                    language, expect_errors):
168         workdir = os.path.join(workdir, language)
169         if not os.path.exists(workdir):
170             os.makedirs(workdir)
171         return test_class(path, workdir, module,
172                           language=language,
173                           expect_errors=expect_errors,
174                           annotate=self.annotate,
175                           cleanup_workdir=self.cleanup_workdir,
176                           cleanup_sharedlibs=self.cleanup_sharedlibs,
177                           cython_only=self.cython_only)
178
179 class CythonCompileTestCase(unittest.TestCase):
180     def __init__(self, directory, workdir, module, language='c',
181                  expect_errors=False, annotate=False, cleanup_workdir=True,
182                  cleanup_sharedlibs=True, cython_only=False):
183         self.directory = directory
184         self.workdir = workdir
185         self.module = module
186         self.language = language
187         self.expect_errors = expect_errors
188         self.annotate = annotate
189         self.cleanup_workdir = cleanup_workdir
190         self.cleanup_sharedlibs = cleanup_sharedlibs
191         self.cython_only = cython_only
192         unittest.TestCase.__init__(self)
193
194     def shortDescription(self):
195         return "compiling (%s) %s" % (self.language, self.module)
196
197     def setUp(self):
198         if self.workdir not in sys.path:
199             sys.path.insert(0, self.workdir)
200
201     def tearDown(self):
202         try:
203             sys.path.remove(self.workdir)
204         except ValueError:
205             pass
206         try:
207             del sys.modules[self.module]
208         except KeyError:
209             pass
210         cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
211         cleanup_lib_files = self.cleanup_sharedlibs
212         if os.path.exists(self.workdir):
213             for rmfile in os.listdir(self.workdir):
214                 if not cleanup_c_files:
215                     if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
216                         continue
217                 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
218                     continue
219                 if self.annotate and rmfile.endswith(".html"):
220                     continue
221                 try:
222                     rmfile = os.path.join(self.workdir, rmfile)
223                     if os.path.isdir(rmfile):
224                         shutil.rmtree(rmfile, ignore_errors=True)
225                     else:
226                         os.remove(rmfile)
227                 except IOError:
228                     pass
229         else:
230             os.makedirs(self.workdir)
231
232     def runTest(self):
233         self.runCompileTest()
234
235     def runCompileTest(self):
236         self.compile(self.directory, self.module, self.workdir,
237                      self.directory, self.expect_errors, self.annotate)
238
239     def find_module_source_file(self, source_file):
240         if not os.path.exists(source_file):
241             source_file = source_file[:-1]
242         return source_file
243
244     def build_target_filename(self, module_name):
245         target = '%s.%s' % (module_name, self.language)
246         return target
247
248     def split_source_and_output(self, directory, module, workdir):
249         source_file = os.path.join(directory, module) + '.pyx'
250         source_and_output = codecs.open(
251             self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
252         out = codecs.open(os.path.join(workdir, module + '.pyx'),
253                           'w', 'ISO-8859-1')
254         for line in source_and_output:
255             last_line = line
256             if line.startswith("_ERRORS"):
257                 out.close()
258                 out = ErrorWriter()
259             else:
260                 out.write(line)
261         try:
262             geterrors = out.geterrors
263         except AttributeError:
264             return []
265         else:
266             return geterrors()
267
268     def run_cython(self, directory, module, targetdir, incdir, annotate):
269         include_dirs = INCLUDE_DIRS[:]
270         if incdir:
271             include_dirs.append(incdir)
272         source = self.find_module_source_file(
273             os.path.join(directory, module + '.pyx'))
274         target = os.path.join(targetdir, self.build_target_filename(module))
275         options = CompilationOptions(
276             pyrex_default_options,
277             include_path = include_dirs,
278             output_file = target,
279             annotate = annotate,
280             use_listing_file = False,
281             cplus = self.language == 'cpp',
282             generate_pxi = False,
283             evaluate_tree_assertions = True,
284             )
285         cython_compile(source, options=options,
286                        full_module_name=module)
287
288     def run_distutils(self, module, workdir, incdir):
289         cwd = os.getcwd()
290         os.chdir(workdir)
291         try:
292             build_extension = build_ext(distutils_distro)
293             build_extension.include_dirs = INCLUDE_DIRS[:]
294             if incdir:
295                 build_extension.include_dirs.append(incdir)
296             build_extension.finalize_options()
297             ext_include_dirs = []
298             for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
299                 if match(module):
300                     ext_include_dirs += get_additional_include_dirs()
301             extension = Extension(
302                 module,
303                 sources = [self.build_target_filename(module)],
304                 include_dirs = ext_include_dirs,
305                 extra_compile_args = CFLAGS,
306                 )
307             if self.language == 'cpp':
308                 extension.language = 'c++'
309             build_extension.extensions = [extension]
310             build_extension.build_temp = workdir
311             build_extension.build_lib  = workdir
312             build_extension.run()
313         finally:
314             os.chdir(cwd)
315
316     def compile(self, directory, module, workdir, incdir,
317                 expect_errors, annotate):
318         expected_errors = errors = ()
319         if expect_errors:
320             expected_errors = self.split_source_and_output(
321                 directory, module, workdir)
322             directory = workdir
323
324         if WITH_CYTHON:
325             old_stderr = sys.stderr
326             try:
327                 sys.stderr = ErrorWriter()
328                 self.run_cython(directory, module, workdir, incdir, annotate)
329                 errors = sys.stderr.geterrors()
330             finally:
331                 sys.stderr = old_stderr
332
333         if errors or expected_errors:
334             try:
335                 for expected, error in zip(expected_errors, errors):
336                     self.assertEquals(expected, error)
337                 if len(errors) < len(expected_errors):
338                     expected_error = expected_errors[len(errors)]
339                     self.assertEquals(expected_error, None)
340                 elif len(errors) > len(expected_errors):
341                     unexpected_error = errors[len(expected_errors)]
342                     self.assertEquals(None, unexpected_error)
343             except AssertionError:
344                 print("\n=== Expected errors: ===")
345                 print('\n'.join(expected_errors))
346                 print("\n\n=== Got errors: ===")
347                 print('\n'.join(errors))
348                 print('\n')
349                 raise
350         else:
351             if not self.cython_only:
352                 self.run_distutils(module, workdir, incdir)
353
354 class CythonRunTestCase(CythonCompileTestCase):
355     def shortDescription(self):
356         return "compiling (%s) and running %s" % (self.language, self.module)
357
358     def run(self, result=None):
359         if result is None:
360             result = self.defaultTestResult()
361         result.startTest(self)
362         try:
363             self.setUp()
364             self.runCompileTest()
365             if not self.cython_only:
366                 doctest.DocTestSuite(self.module).run(result)
367         except Exception:
368             result.addError(self, sys.exc_info())
369             result.stopTest(self)
370         try:
371             self.tearDown()
372         except Exception:
373             pass
374
375 class CythonUnitTestCase(CythonCompileTestCase):
376     def shortDescription(self):
377         return "compiling (%s) tests in %s" % (self.language, self.module)
378
379     def run(self, result=None):
380         if result is None:
381             result = self.defaultTestResult()
382         result.startTest(self)
383         try:
384             self.setUp()
385             self.runCompileTest()
386             unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
387         except Exception:
388             result.addError(self, sys.exc_info())
389             result.stopTest(self)
390         try:
391             self.tearDown()
392         except Exception:
393             pass
394
395 def collect_unittests(path, module_prefix, suite, selectors):
396     def file_matches(filename):
397         return filename.startswith("Test") and filename.endswith(".py")
398
399     def package_matches(dirname):
400         return dirname == "Tests"
401
402     loader = unittest.TestLoader()
403
404     skipped_dirs = []
405
406     for dirpath, dirnames, filenames in os.walk(path):
407         if dirpath != path and "__init__.py" not in filenames:
408             skipped_dirs.append(dirpath + os.path.sep)
409             continue
410         skip = False
411         for dir in skipped_dirs:
412             if dirpath.startswith(dir):
413                 skip = True
414         if skip:
415             continue
416         parentname = os.path.split(dirpath)[-1]
417         if package_matches(parentname):
418             for f in filenames:
419                 if file_matches(f):
420                     filepath = os.path.join(dirpath, f)[:-len(".py")]
421                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
422                     if not [ 1 for match in selectors if match(modulename) ]:
423                         continue
424                     module = __import__(modulename)
425                     for x in modulename.split('.')[1:]:
426                         module = getattr(module, x)
427                     suite.addTests([loader.loadTestsFromModule(module)])
428
429 def collect_doctests(path, module_prefix, suite, selectors):
430     def package_matches(dirname):
431         return dirname not in ("Mac", "Distutils", "Plex")
432     def file_matches(filename):
433         return (filename.endswith(".py") and not ('~' in filename
434                 or '#' in filename or filename.startswith('.')))
435     import doctest, types
436     for dirpath, dirnames, filenames in os.walk(path):
437         parentname = os.path.split(dirpath)[-1]
438         if package_matches(parentname):
439             for f in filenames:
440                 if file_matches(f):
441                     if not f.endswith('.py'): continue
442                     filepath = os.path.join(dirpath, f)[:-len(".py")]
443                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
444                     if not [ 1 for match in selectors if match(modulename) ]:
445                         continue
446                     module = __import__(modulename)
447                     for x in modulename.split('.')[1:]:
448                         module = getattr(module, x)
449                     if hasattr(module, "__doc__") or hasattr(module, "__test__"):
450                         try:
451                             suite.addTest(doctest.DocTestSuite(module))
452                         except ValueError: # no tests
453                             pass
454
455 class MissingDependencyExcluder:
456     def __init__(self, deps):
457         # deps: { module name : matcher func }
458         self.exclude_matchers = []
459         for mod, matcher in deps.items():
460             try:
461                 __import__(mod)
462             except ImportError:
463                 self.exclude_matchers.append(matcher)
464         self.tests_missing_deps = []
465     def __call__(self, testname):
466         for matcher in self.exclude_matchers:
467             if matcher(testname):
468                 self.tests_missing_deps.append(testname)
469                 return True
470         return False
471
472 class VersionDependencyExcluder:
473     def __init__(self, deps):
474         # deps: { version : matcher func }
475         from sys import version_info
476         self.exclude_matchers = []
477         for ver, (compare, matcher) in deps.items():
478             if compare(version_info, ver):
479                 self.exclude_matchers.append(matcher)
480         self.tests_missing_deps = []
481     def __call__(self, testname):
482         for matcher in self.exclude_matchers:
483             if matcher(testname):
484                 self.tests_missing_deps.append(testname)
485                 return True
486         return False
487
488 class FileListExcluder:
489
490     def __init__(self, list_file):
491         self.excludes = {}
492         for line in open(list_file).readlines():
493             line = line.strip()
494             if line and line[0] != '#':
495                 self.excludes[line.split()[0]] = True
496                 
497     def __call__(self, testname):
498         return testname.split('.')[-1] in self.excludes
499
500 if __name__ == '__main__':
501     from optparse import OptionParser
502     parser = OptionParser()
503     parser.add_option("--no-cleanup", dest="cleanup_workdir",
504                       action="store_false", default=True,
505                       help="do not delete the generated C files (allows passing --no-cython on next run)")
506     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
507                       action="store_false", default=True,
508                       help="do not delete the generated shared libary files (allows manual module experimentation)")
509     parser.add_option("--no-cython", dest="with_cython",
510                       action="store_false", default=True,
511                       help="do not run the Cython compiler, only the C compiler")
512     parser.add_option("--no-c", dest="use_c",
513                       action="store_false", default=True,
514                       help="do not test C compilation")
515     parser.add_option("--no-cpp", dest="use_cpp",
516                       action="store_false", default=True,
517                       help="do not test C++ compilation")
518     parser.add_option("--no-unit", dest="unittests",
519                       action="store_false", default=True,
520                       help="do not run the unit tests")
521     parser.add_option("--no-doctest", dest="doctests",
522                       action="store_false", default=True,
523                       help="do not run the doctests")
524     parser.add_option("--no-file", dest="filetests",
525                       action="store_false", default=True,
526                       help="do not run the file based tests")
527     parser.add_option("--no-pyregr", dest="pyregr",
528                       action="store_false", default=True,
529                       help="do not run the regression tests of CPython in tests/pyregr/")    
530     parser.add_option("--cython-only", dest="cython_only",
531                       action="store_true", default=False,
532                       help="only compile pyx to c, do not run C compiler or run the tests")
533     parser.add_option("--no-refnanny", dest="with_refnanny",
534                       action="store_false", default=True,
535                       help="do not regression test reference counting")
536     parser.add_option("--sys-pyregr", dest="system_pyregr",
537                       action="store_true", default=False,
538                       help="run the regression tests of the CPython installation")
539     parser.add_option("-x", "--exclude", dest="exclude",
540                       action="append", metavar="PATTERN",
541                       help="exclude tests matching the PATTERN")
542     parser.add_option("-C", "--coverage", dest="coverage",
543                       action="store_true", default=False,
544                       help="collect source coverage data for the Compiler")
545     parser.add_option("-A", "--annotate", dest="annotate_source",
546                       action="store_true", default=True,
547                       help="generate annotated HTML versions of the test source files")
548     parser.add_option("--no-annotate", dest="annotate_source",
549                       action="store_false",
550                       help="do not generate annotated HTML versions of the test source files")
551     parser.add_option("-v", "--verbose", dest="verbosity",
552                       action="count", default=0,
553                       help="display test progress, pass twice to print test names")
554     parser.add_option("-T", "--ticket", dest="tickets",
555                       action="append",
556                       help="a bug ticket number to run the respective test in 'tests/bugs'")
557
558     options, cmd_args = parser.parse_args()
559
560     DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
561     ROOTDIR = os.path.join(DISTDIR, 'tests')
562     WORKDIR = os.path.join(os.getcwd(), 'BUILD')
563
564     if sys.version_info >= (3,1):
565         options.doctests    = False
566         options.unittests   = False
567         options.pyregr      = False
568         if options.with_cython:
569             # need to convert Cython sources first
570             import lib2to3.refactor
571             from distutils.util import copydir_run_2to3
572             fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
573                        if fix.split('fix_')[-1] not in ('next',)
574                        ]
575             cy3_dir = os.path.join(WORKDIR, 'Cy3')
576             if not os.path.exists(cy3_dir):
577                 os.makedirs(cy3_dir)
578             import distutils.log as dlog
579             dlog.set_threshold(dlog.DEBUG)
580             copydir_run_2to3(DISTDIR, cy3_dir, fixer_names=fixers,
581                              template = '''
582                              global-exclude *
583                              graft Cython
584                              recursive-exclude Cython *
585                              recursive-include Cython *.py *.pyx *.pxd
586                              ''')
587             sys.path.insert(0, cy3_dir)
588     elif sys.version_info[0] >= 3:
589         # make sure we do not import (or run) Cython itself
590         options.with_cython = False
591         options.doctests    = False
592         options.unittests   = False
593         options.pyregr      = False
594
595     if options.coverage:
596         import coverage
597         coverage.erase()
598         coverage.start()
599
600     WITH_CYTHON = options.with_cython
601
602     if WITH_CYTHON:
603         from Cython.Compiler.Main import \
604             CompilationOptions, \
605             default_options as pyrex_default_options, \
606             compile as cython_compile
607         from Cython.Compiler import Errors
608         Errors.LEVEL = 0 # show all warnings
609
610     # RUN ALL TESTS!
611     UNITTEST_MODULE = "Cython"
612     UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
613     if WITH_CYTHON:
614         if os.path.exists(WORKDIR):
615             for path in os.listdir(WORKDIR):
616                 if path in ("support", "Cy3"): continue
617                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
618     if not os.path.exists(WORKDIR):
619         os.makedirs(WORKDIR)
620
621     if WITH_CYTHON:
622         from Cython.Compiler.Version import version
623         sys.stderr.write("Running tests against Cython %s\n" % version)
624         from Cython.Compiler import DebugFlags
625         DebugFlags.debug_temp_code_comments = 1
626     else:
627         sys.stderr.write("Running tests without Cython.\n")
628     sys.stderr.write("Python %s\n" % sys.version)
629     sys.stderr.write("\n")
630
631     if options.with_refnanny:
632         from pyximport.pyxbuild import pyx_to_dll
633         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
634                              build_in_temp=True,
635                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
636         sys.path.insert(0, os.path.split(libpath)[0])
637         CFLAGS.append("-DCYTHON_REFNANNY")
638
639     test_bugs = False
640     if options.tickets:
641         for ticket_number in options.tickets:
642             test_bugs = True
643             cmd_args.append('.*T%s$' % ticket_number)
644     if not test_bugs:
645         for selector in cmd_args:
646             if selector.startswith('bugs'):
647                 test_bugs = True
648
649     import re
650     selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
651     if not selectors:
652         selectors = [ lambda x:True ]
653
654     # Chech which external modules are not present and exclude tests
655     # which depends on them (by prefix)
656
657     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES) 
658     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES) 
659     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
660
661     if options.exclude:
662         exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
663     
664     if not test_bugs:
665         exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
666
667     languages = []
668     if options.use_c:
669         languages.append('c')
670     if options.use_cpp:
671         languages.append('cpp')
672
673     test_suite = unittest.TestSuite()
674
675     if options.unittests:
676         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
677
678     if options.doctests:
679         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
680
681     if options.filetests and languages:
682         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
683                                 options.annotate_source, options.cleanup_workdir,
684                                 options.cleanup_sharedlibs, options.pyregr,
685                                 options.cython_only, languages, test_bugs)
686         test_suite.addTest(filetests.build_suite())
687
688     if options.system_pyregr and languages:
689         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
690                                 options.annotate_source, options.cleanup_workdir,
691                                 options.cleanup_sharedlibs, True,
692                                 options.cython_only, languages, test_bugs)
693         test_suite.addTest(
694             filetests.handle_directory(
695                 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
696                 'pyregr'))
697
698     unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
699
700     if options.coverage:
701         coverage.stop()
702         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
703         modules = [ module for name, module in sys.modules.items()
704                     if module is not None and
705                     name.startswith('Cython.Compiler.') and 
706                     name[len('Cython.Compiler.'):] not in ignored_modules ]
707         coverage.report(modules, show_missing=0)
708
709     if missing_dep_excluder.tests_missing_deps:
710         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
711         for test in missing_dep_excluder.tests_missing_deps:
712             sys.stderr.write("   %s\n" % test)
713
714     if options.with_refnanny:
715         import refnanny
716         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))