merged in Vitja's tab removals
[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 time
10 import unittest
11 import doctest
12 import operator
13 import tempfile
14 import traceback
15 try:
16     from StringIO import StringIO
17 except ImportError:
18     from io import StringIO
19
20 try:
21     import cPickle as pickle
22 except ImportError:
23     import pickle
24
25 try:
26     from io import open as io_open
27 except ImportError:
28     from codecs import open as io_open
29
30 try:
31     import threading
32 except ImportError: # No threads, no problems
33     threading = None
34
35 try:
36     from collections import defaultdict
37 except ImportError:
38     class defaultdict(object):
39         def __init__(self, default_factory=lambda : None):
40             self._dict = {}
41             self.default_factory = default_factory
42         def __getitem__(self, key):
43             if key not in self._dict:
44                 self._dict[key] = self.default_factory()
45             return self._dict[key]
46         def __setitem__(self, key, value):
47             self._dict[key] = value
48         def __repr__(self):
49             return repr(self._dict)
50
51 WITH_CYTHON = True
52 CY3_DIR = None
53
54 from distutils.dist import Distribution
55 from distutils.core import Extension
56 from distutils.command.build_ext import build_ext as _build_ext
57 distutils_distro = Distribution()
58
59 if sys.platform == 'win32':
60     # TODO: Figure out why this hackery (see http://thread.gmane.org/gmane.comp.python.cython.devel/8280/).
61     config_files = distutils_distro.find_config_files()
62     try: config_files.remove('setup.cfg')
63     except ValueError: pass
64     distutils_distro.parse_config_files(config_files)
65
66     cfgfiles = distutils_distro.find_config_files()
67     try: cfgfiles.remove('setup.cfg')
68     except ValueError: pass
69     distutils_distro.parse_config_files(cfgfiles)
70
71 EXT_DEP_MODULES = {
72     'tag:numpy' : 'numpy',
73     'tag:pstats': 'pstats',
74     'tag:posix' : 'posix',
75 }
76
77 def update_numpy_extension(ext):
78     import numpy
79     ext.include_dirs.append(numpy.get_include())
80
81 EXT_EXTRAS = {
82     'tag:numpy' : update_numpy_extension,
83 }
84
85 # TODO: use tags
86 VER_DEP_MODULES = {
87     # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
88     # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
89     (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
90                                           'run.builtin_sorted'
91                                           ]),
92     (2,5) : (operator.lt, lambda x: x in ['run.any',
93                                           'run.all',
94                                           'run.relativeimport_T542',
95                                           'run.relativeimport_star_T542',
96                                           ]),
97     (2,6) : (operator.lt, lambda x: x in ['run.print_function',
98                                           'run.cython3',
99                                           'run.generators_py', # generators, with statement
100                                           'run.pure_py', # decorators, with statement
101                                           ]),
102     (2,7) : (operator.lt, lambda x: x in ['run.withstat_py', # multi context with statement
103                                           ]),
104     # The next line should start (3,); but this is a dictionary, so
105     # we can only have one (3,) key.  Since 2.7 is supposed to be the
106     # last 2.x release, things would have to change drastically for this
107     # to be unsafe...
108     (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3',
109                                            'run.test_raisefrom',
110                                            ]),
111     (3,): (operator.ge, lambda x: x in ['run.non_future_division',
112                                         'compile.extsetslice',
113                                         'compile.extdelslice',
114                                         'run.special_methods_T561_py2']),
115 }
116
117 # files that should not be converted to Python 3 code with 2to3
118 KEEP_2X_FILES = [
119     os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
120     os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
121     os.path.join('Cython', 'Debugger', 'libcython.py'),
122     os.path.join('Cython', 'Debugger', 'libpython.py'),
123 ]
124
125 COMPILER = None
126 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
127 CFLAGS = os.getenv('CFLAGS', '').split()
128
129 def memoize(f):
130     uncomputed = object()
131     f._cache = {}
132     def func(*args):
133         res = f._cache.get(args, uncomputed)
134         if res is uncomputed:
135             res = f._cache[args] = f(*args)
136         return res
137     return func
138
139 def parse_tags(filepath):
140     tags = defaultdict(list)
141     f = io_open(filepath, encoding='ISO-8859-1', errors='replace')
142     try:
143         for line in f:
144             line = line.strip()
145             if not line:
146                 continue
147             if line[0] != '#':
148                 break
149             ix = line.find(':')
150             if ix != -1:
151                 tag = line[1:ix].strip()
152                 values = line[ix+1:].split(',')
153                 tags[tag].extend([value.strip() for value in values])
154     finally:
155         f.close()
156     return tags
157
158 parse_tags = memoize(parse_tags)
159
160 list_unchanging_dir = memoize(lambda x: os.listdir(x))
161
162
163 class build_ext(_build_ext):
164     def build_extension(self, ext):
165         if ext.language == 'c++':
166             try:
167                 try: # Py2.7+ & Py3.2+
168                     compiler_obj = self.compiler_obj
169                 except AttributeError:
170                     compiler_obj = self.compiler
171                 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
172             except Exception:
173                 pass
174         _build_ext.build_extension(self, ext)
175
176 class ErrorWriter(object):
177     match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
178     def __init__(self):
179         self.output = []
180         self.write = self.output.append
181
182     def _collect(self, collect_errors, collect_warnings):
183         s = ''.join(self.output)
184         result = []
185         for line in s.split('\n'):
186             match = self.match_error(line)
187             if match:
188                 is_warning, line, column, message = match.groups()
189                 if (is_warning and collect_warnings) or \
190                         (not is_warning and collect_errors):
191                     result.append( (int(line), int(column), message.strip()) )
192         result.sort()
193         return [ "%d:%d: %s" % values for values in result ]
194
195     def geterrors(self):
196         return self._collect(True, False)
197
198     def getwarnings(self):
199         return self._collect(False, True)
200
201     def getall(self):
202         return self._collect(True, True)
203
204 class TestBuilder(object):
205     def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
206                  cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
207                  languages, test_bugs, fork, language_level):
208         self.rootdir = rootdir
209         self.workdir = workdir
210         self.selectors = selectors
211         self.exclude_selectors = exclude_selectors
212         self.annotate = annotate
213         self.cleanup_workdir = cleanup_workdir
214         self.cleanup_sharedlibs = cleanup_sharedlibs
215         self.with_pyregr = with_pyregr
216         self.cython_only = cython_only
217         self.languages = languages
218         self.test_bugs = test_bugs
219         self.fork = fork
220         self.language_level = language_level
221
222     def build_suite(self):
223         suite = unittest.TestSuite()
224         filenames = os.listdir(self.rootdir)
225         filenames.sort()
226         for filename in filenames:
227             path = os.path.join(self.rootdir, filename)
228             if os.path.isdir(path):
229                 if filename == 'pyregr' and not self.with_pyregr:
230                     continue
231                 if filename == 'broken' and not self.test_bugs:
232                     continue
233                 suite.addTest(
234                     self.handle_directory(path, filename))
235         if sys.platform not in ['win32']:
236             # Non-Windows makefile.
237             if [1 for selector in self.selectors if selector("embedded")] \
238                 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
239                 suite.addTest(unittest.makeSuite(EmbedTest))
240         return suite
241
242     def handle_directory(self, path, context):
243         workdir = os.path.join(self.workdir, context)
244         if not os.path.exists(workdir):
245             os.makedirs(workdir)
246
247         suite = unittest.TestSuite()
248         filenames = list_unchanging_dir(path)
249         filenames.sort()
250         for filename in filenames:
251             filepath = os.path.join(path, filename)
252             module, ext = os.path.splitext(filename)
253             if ext not in ('.py', '.pyx', '.srctree'):
254                 continue
255             if filename.startswith('.'):
256                 continue # certain emacs backup files
257             tags = parse_tags(filepath)
258             fqmodule = "%s.%s" % (context, module)
259             if not [ 1 for match in self.selectors
260                      if match(fqmodule, tags) ]:
261                 continue
262             if self.exclude_selectors:
263                 if [1 for match in self.exclude_selectors 
264                         if match(fqmodule, tags)]:
265                     continue
266
267             mode = 'run' # default
268             if tags['mode']:
269                 mode = tags['mode'][0]
270             elif context == 'pyregr':
271                 mode = 'pyregr'
272
273             if ext == '.srctree':
274                 suite.addTest(EndToEndTest(filepath, workdir, self.cleanup_workdir))
275                 continue
276
277             # Choose the test suite.
278             if mode == 'pyregr':
279                 if not filename.startswith('test_'):
280                     continue
281                 test_class = CythonPyregrTestCase
282             elif mode == 'run':
283                 if module.startswith("test_"):
284                     test_class = CythonUnitTestCase
285                 else:
286                     test_class = CythonRunTestCase
287             else:
288                 test_class = CythonCompileTestCase
289
290             for test in self.build_tests(test_class, path, workdir,
291                                          module, mode == 'error', tags):
292                 suite.addTest(test)
293             if mode == 'run' and ext == '.py':
294                 # additionally test file in real Python
295                 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
296                 
297         return suite
298
299     def build_tests(self, test_class, path, workdir, module, expect_errors, tags):
300         if 'werror' in tags['tag']:
301             warning_errors = True
302         else:
303             warning_errors = False
304
305         if expect_errors:
306             if 'cpp' in tags['tag'] and 'cpp' in self.languages:
307                 languages = ['cpp']
308             else:
309                 languages = self.languages[:1]
310         else:
311             languages = self.languages
312         if 'cpp' in tags['tag'] and 'c' in languages:
313             languages = list(languages)
314             languages.remove('c')
315         tests = [ self.build_test(test_class, path, workdir, module,
316                                   language, expect_errors, warning_errors)
317                   for language in languages ]
318         return tests
319
320     def build_test(self, test_class, path, workdir, module,
321                    language, expect_errors, warning_errors):
322         workdir = os.path.join(workdir, language)
323         if not os.path.exists(workdir):
324             os.makedirs(workdir)
325         return test_class(path, workdir, module,
326                           language=language,
327                           expect_errors=expect_errors,
328                           annotate=self.annotate,
329                           cleanup_workdir=self.cleanup_workdir,
330                           cleanup_sharedlibs=self.cleanup_sharedlibs,
331                           cython_only=self.cython_only,
332                           fork=self.fork,
333                           language_level=self.language_level,
334                           warning_errors=warning_errors)
335
336 class CythonCompileTestCase(unittest.TestCase):
337     def __init__(self, test_directory, workdir, module, language='c',
338                  expect_errors=False, annotate=False, cleanup_workdir=True,
339                  cleanup_sharedlibs=True, cython_only=False, fork=True,
340                  language_level=2, warning_errors=False):
341         self.test_directory = test_directory
342         self.workdir = workdir
343         self.module = module
344         self.language = language
345         self.expect_errors = expect_errors
346         self.annotate = annotate
347         self.cleanup_workdir = cleanup_workdir
348         self.cleanup_sharedlibs = cleanup_sharedlibs
349         self.cython_only = cython_only
350         self.fork = fork
351         self.language_level = language_level
352         self.warning_errors = warning_errors
353         unittest.TestCase.__init__(self)
354
355     def shortDescription(self):
356         return "compiling (%s) %s" % (self.language, self.module)
357
358     def setUp(self):
359         from Cython.Compiler import Options
360         self._saved_options = [ (name, getattr(Options, name))
361                                 for name in ('warning_errors', 'error_on_unknown_names') ]
362         Options.warning_errors = self.warning_errors
363
364         if self.workdir not in sys.path:
365             sys.path.insert(0, self.workdir)
366
367     def tearDown(self):
368         from Cython.Compiler import Options
369         for name, value in self._saved_options:
370             setattr(Options, name, value)
371
372         try:
373             sys.path.remove(self.workdir)
374         except ValueError:
375             pass
376         try:
377             del sys.modules[self.module]
378         except KeyError:
379             pass
380         cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
381         cleanup_lib_files = self.cleanup_sharedlibs
382         if os.path.exists(self.workdir):
383             for rmfile in os.listdir(self.workdir):
384                 if not cleanup_c_files:
385                     if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
386                         continue
387                 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
388                     continue
389                 if self.annotate and rmfile.endswith(".html"):
390                     continue
391                 try:
392                     rmfile = os.path.join(self.workdir, rmfile)
393                     if os.path.isdir(rmfile):
394                         shutil.rmtree(rmfile, ignore_errors=True)
395                     else:
396                         os.remove(rmfile)
397                 except IOError:
398                     pass
399         else:
400             os.makedirs(self.workdir)
401
402     def runTest(self):
403         self.runCompileTest()
404
405     def runCompileTest(self):
406         self.compile(self.test_directory, self.module, self.workdir,
407                      self.test_directory, self.expect_errors, self.annotate)
408
409     def find_module_source_file(self, source_file):
410         if not os.path.exists(source_file):
411             source_file = source_file[:-1]
412         return source_file
413
414     def build_target_filename(self, module_name):
415         target = '%s.%s' % (module_name, self.language)
416         return target
417     
418     def related_files(self, test_directory, module_name):
419         is_related = re.compile('%s_.*[.].*' % module_name).match
420         return [filename for filename in list_unchanging_dir(test_directory)
421             if is_related(filename)]
422
423     def copy_files(self, test_directory, target_directory, file_list):
424         for filename in file_list:
425             shutil.copy(os.path.join(test_directory, filename),
426                         target_directory)
427
428     def source_files(self, workdir, module_name, file_list):
429         return ([self.build_target_filename(module_name)] +
430             [filename for filename in file_list
431                 if not os.path.isfile(os.path.join(workdir, filename))])
432
433     def split_source_and_output(self, test_directory, module, workdir):
434         source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
435         source_and_output = io_open(source_file, 'rU', encoding='ISO-8859-1')
436         try:
437             out = io_open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
438                               'w', encoding='ISO-8859-1')
439             for line in source_and_output:
440                 last_line = line
441                 if line.startswith("_ERRORS"):
442                     out.close()
443                     out = ErrorWriter()
444                 else:
445                     out.write(line)
446         finally:
447             source_and_output.close()
448         try:
449             geterrors = out.geterrors
450         except AttributeError:
451             out.close()
452             return []
453         else:
454             return geterrors()
455
456     def run_cython(self, test_directory, module, targetdir, incdir, annotate,
457                    extra_compile_options=None):
458         include_dirs = INCLUDE_DIRS[:]
459         if incdir:
460             include_dirs.append(incdir)
461         source = self.find_module_source_file(
462             os.path.join(test_directory, module + '.pyx'))
463         target = os.path.join(targetdir, self.build_target_filename(module))
464
465         if extra_compile_options is None:
466             extra_compile_options = {}
467
468         try:
469             CompilationOptions
470         except NameError:
471             from Cython.Compiler.Main import CompilationOptions
472             from Cython.Compiler.Main import compile as cython_compile
473             from Cython.Compiler.Main import default_options
474
475         options = CompilationOptions(
476             default_options,
477             include_path = include_dirs,
478             output_file = target,
479             annotate = annotate,
480             use_listing_file = False,
481             cplus = self.language == 'cpp',
482             language_level = self.language_level,
483             generate_pxi = False,
484             evaluate_tree_assertions = True,
485             **extra_compile_options
486             )
487         cython_compile(source, options=options,
488                        full_module_name=module)
489
490     def run_distutils(self, test_directory, module, workdir, incdir,
491                       extra_extension_args=None):
492         original_source = self.find_module_source_file(
493             os.path.join(test_directory, module + '.pyx'))
494         try:
495             tags = parse_tags(original_source)
496         except IOError:
497             tags = {}
498         cwd = os.getcwd()
499         os.chdir(workdir)
500         try:
501             build_extension = build_ext(distutils_distro)
502             build_extension.include_dirs = INCLUDE_DIRS[:]
503             if incdir:
504                 build_extension.include_dirs.append(incdir)
505             build_extension.finalize_options()
506             if COMPILER:
507                 build_extension.compiler = COMPILER
508             ext_compile_flags = CFLAGS[:]
509             if  build_extension.compiler == 'mingw32':
510                 ext_compile_flags.append('-Wno-format')
511             if extra_extension_args is None:
512                 extra_extension_args = {}
513
514             related_files = self.related_files(test_directory, module)
515             self.copy_files(test_directory, workdir, related_files)
516             extension = Extension(
517                 module,
518                 sources = self.source_files(workdir, module, related_files),
519                 extra_compile_args = ext_compile_flags,
520                 **extra_extension_args
521                 )
522             for matcher, fixer in EXT_EXTRAS.items():
523                 if isinstance(matcher, str):
524                     del EXT_EXTRAS[matcher]
525                     matcher = string_selector(matcher)
526                     EXT_EXTRAS[matcher] = fixer
527                 if matcher(module, tags):
528                     extension = fixer(extension) or extension
529             if self.language == 'cpp':
530                 extension.language = 'c++'
531             build_extension.extensions = [extension]
532             build_extension.build_temp = workdir
533             build_extension.build_lib  = workdir
534             build_extension.run()
535         finally:
536             os.chdir(cwd)
537
538     def compile(self, test_directory, module, workdir, incdir,
539                 expect_errors, annotate):
540         expected_errors = errors = ()
541         if expect_errors:
542             expected_errors = self.split_source_and_output(
543                 test_directory, module, workdir)
544             test_directory = workdir
545
546         if WITH_CYTHON:
547             old_stderr = sys.stderr
548             try:
549                 sys.stderr = ErrorWriter()
550                 self.run_cython(test_directory, module, workdir, incdir, annotate)
551                 errors = sys.stderr.geterrors()
552             finally:
553                 sys.stderr = old_stderr
554
555         if errors or expected_errors:
556             try:
557                 for expected, error in zip(expected_errors, errors):
558                     self.assertEquals(expected, error)
559                 if len(errors) < len(expected_errors):
560                     expected_error = expected_errors[len(errors)]
561                     self.assertEquals(expected_error, None)
562                 elif len(errors) > len(expected_errors):
563                     unexpected_error = errors[len(expected_errors)]
564                     self.assertEquals(None, unexpected_error)
565             except AssertionError:
566                 print("\n=== Expected errors: ===")
567                 print('\n'.join(expected_errors))
568                 print("\n\n=== Got errors: ===")
569                 print('\n'.join(errors))
570                 print('\n')
571                 raise
572         else:
573             if not self.cython_only:
574                 self.run_distutils(test_directory, module, workdir, incdir)
575
576 class CythonRunTestCase(CythonCompileTestCase):
577     def shortDescription(self):
578         return "compiling (%s) and running %s" % (self.language, self.module)
579
580     def run(self, result=None):
581         if result is None:
582             result = self.defaultTestResult()
583         result.startTest(self)
584         try:
585             self.setUp()
586             try:
587                 self.runCompileTest()
588                 self.run_tests(result)
589             finally:
590                 check_thread_termination()
591         except Exception:
592             result.addError(self, sys.exc_info())
593             result.stopTest(self)
594         try:
595             self.tearDown()
596         except Exception:
597             pass
598
599     def run_tests(self, result):
600         if not self.cython_only:
601             self.run_doctests(self.module, result)
602
603     def run_doctests(self, module_name, result):
604         def run_test(result):
605             tests = doctest.DocTestSuite(module_name)
606             tests.run(result)
607         run_forked_test(result, run_test, self.shortDescription(), self.fork)
608
609
610 def run_forked_test(result, run_func, test_name, fork=True):
611     if not fork or sys.version_info[0] >= 3 or not hasattr(os, 'fork'):
612         run_func(result)
613         gc.collect()
614         return
615
616     # fork to make sure we do not keep the tested module loaded
617     result_handle, result_file = tempfile.mkstemp()
618     os.close(result_handle)
619     child_id = os.fork()
620     if not child_id:
621         result_code = 0
622         try:
623             try:
624                 tests = None
625                 try:
626                     partial_result = PartialTestResult(result)
627                     run_func(partial_result)
628                     gc.collect()
629                 except Exception:
630                     if tests is None:
631                         # importing failed, try to fake a test class
632                         tests = _FakeClass(
633                             failureException=sys.exc_info()[1],
634                             _shortDescription=test_name,
635                             module_name=None)
636                     partial_result.addError(tests, sys.exc_info())
637                     result_code = 1
638                 output = open(result_file, 'wb')
639                 pickle.dump(partial_result.data(), output)
640             except:
641                 traceback.print_exc()
642         finally:
643             try: output.close()
644             except: pass
645             os._exit(result_code)
646
647     try:
648         cid, result_code = os.waitpid(child_id, 0)
649         # os.waitpid returns the child's result code in the
650         # upper byte of result_code, and the signal it was
651         # killed by in the lower byte
652         if result_code & 255:
653             raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
654                             (module_name, result_code & 255))
655         result_code = result_code >> 8
656         if result_code in (0,1):
657             input = open(result_file, 'rb')
658             try:
659                 PartialTestResult.join_results(result, pickle.load(input))
660             finally:
661                 input.close()
662         if result_code:
663             raise Exception("Tests in module '%s' exited with status %d" %
664                             (module_name, result_code))
665     finally:
666         try: os.unlink(result_file)
667         except: pass
668
669 class PureDoctestTestCase(unittest.TestCase):
670     def __init__(self, module_name, module_path):
671         self.module_name = module_name
672         self.module_path = module_path
673         unittest.TestCase.__init__(self, 'run')
674
675     def shortDescription(self):
676         return "running pure doctests in %s" % self.module_name
677
678     def run(self, result=None):
679         if result is None:
680             result = self.defaultTestResult()
681         loaded_module_name = 'pure_doctest__' + self.module_name
682         result.startTest(self)
683         try:
684             self.setUp()
685
686             import imp
687             m = imp.load_source(loaded_module_name, self.module_path)
688             try:
689                 doctest.DocTestSuite(m).run(result)
690             finally:
691                 del m
692                 if loaded_module_name in sys.modules:
693                     del sys.modules[loaded_module_name]
694                 check_thread_termination()
695         except Exception:
696             result.addError(self, sys.exc_info())
697             result.stopTest(self)
698         try:
699             self.tearDown()
700         except Exception:
701             pass
702
703 is_private_field = re.compile('^_[^_]').match
704
705 class _FakeClass(object):
706     def __init__(self, **kwargs):
707         self._shortDescription = kwargs.get('module_name')
708         self.__dict__.update(kwargs)
709     def shortDescription(self):
710         return self._shortDescription
711
712 try: # Py2.7+ and Py3.2+
713     from unittest.runner import _TextTestResult
714 except ImportError:
715     from unittest import _TextTestResult
716
717 class PartialTestResult(_TextTestResult):
718     def __init__(self, base_result):
719         _TextTestResult.__init__(
720             self, self._StringIO(), True,
721             base_result.dots + base_result.showAll*2)
722
723     def strip_error_results(self, results):
724         for test_case, error in results:
725             for attr_name in filter(is_private_field, dir(test_case)):
726                 if attr_name == '_dt_test':
727                     test_case._dt_test = _FakeClass(
728                         name=test_case._dt_test.name)
729                 elif attr_name != '_shortDescription':
730                     setattr(test_case, attr_name, None)
731
732     def data(self):
733         self.strip_error_results(self.failures)
734         self.strip_error_results(self.errors)
735         return (self.failures, self.errors, self.testsRun,
736                 self.stream.getvalue())
737
738     def join_results(result, data):
739         """Static method for merging the result back into the main
740         result object.
741         """
742         failures, errors, tests_run, output = data
743         if output:
744             result.stream.write(output)
745         result.errors.extend(errors)
746         result.failures.extend(failures)
747         result.testsRun += tests_run
748
749     join_results = staticmethod(join_results)
750
751     class _StringIO(StringIO):
752         def writeln(self, line):
753             self.write("%s\n" % line)
754
755
756 class CythonUnitTestCase(CythonRunTestCase):
757     def shortDescription(self):
758         return "compiling (%s) tests in %s" % (self.language, self.module)
759
760     def run_tests(self, result):
761         unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
762
763
764 class CythonPyregrTestCase(CythonRunTestCase):
765     def setUp(self):
766         CythonRunTestCase.setUp(self)
767         from Cython.Compiler import Options
768         Options.error_on_unknown_names = False
769
770     def _run_unittest(self, result, *classes):
771         """Run tests from unittest.TestCase-derived classes."""
772         valid_types = (unittest.TestSuite, unittest.TestCase)
773         suite = unittest.TestSuite()
774         for cls in classes:
775             if isinstance(cls, str):
776                 if cls in sys.modules:
777                     suite.addTest(unittest.findTestCases(sys.modules[cls]))
778                 else:
779                     raise ValueError("str arguments must be keys in sys.modules")
780             elif isinstance(cls, valid_types):
781                 suite.addTest(cls)
782             else:
783                 suite.addTest(unittest.makeSuite(cls))
784         suite.run(result)
785
786     def _run_doctest(self, result, module):
787         self.run_doctests(module, result)
788
789     def run_tests(self, result):
790         try:
791             from test import test_support as support
792         except ImportError: # Py3k
793             from test import support
794
795         def run_test(result):
796             def run_unittest(*classes):
797                 return self._run_unittest(result, *classes)
798             def run_doctest(module, verbosity=None):
799                 return self._run_doctest(result, module)
800
801             support.run_unittest = run_unittest
802             support.run_doctest = run_doctest
803
804             try:
805                 module = __import__(self.module)
806                 if hasattr(module, 'test_main'):
807                     module.test_main()
808             except (unittest.SkipTest, support.ResourceDenied):
809                 result.addSkip(self, 'ok')
810
811         run_forked_test(result, run_test, self.shortDescription(), self.fork)
812
813 include_debugger = sys.version_info[:2] > (2, 5)
814
815 def collect_unittests(path, module_prefix, suite, selectors):
816     def file_matches(filename):
817         return filename.startswith("Test") and filename.endswith(".py")
818
819     def package_matches(dirname):
820         return dirname == "Tests"
821
822     loader = unittest.TestLoader()
823
824     if include_debugger:
825         skipped_dirs = []
826     else:
827         skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
828
829     for dirpath, dirnames, filenames in os.walk(path):
830         if dirpath != path and "__init__.py" not in filenames:
831             skipped_dirs.append(dirpath + os.path.sep)
832             continue
833         skip = False
834         for dir in skipped_dirs:
835             if dirpath.startswith(dir):
836                 skip = True
837         if skip:
838             continue
839         parentname = os.path.split(dirpath)[-1]
840         if package_matches(parentname):
841             for f in filenames:
842                 if file_matches(f):
843                     filepath = os.path.join(dirpath, f)[:-len(".py")]
844                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
845                     if not [ 1 for match in selectors if match(modulename) ]:
846                         continue
847                     module = __import__(modulename)
848                     for x in modulename.split('.')[1:]:
849                         module = getattr(module, x)
850                     suite.addTests([loader.loadTestsFromModule(module)])
851
852
853
854 def collect_doctests(path, module_prefix, suite, selectors):
855     def package_matches(dirname):
856         if dirname == 'Debugger' and not include_debugger:
857             return False
858         return dirname not in ("Mac", "Distutils", "Plex")
859     def file_matches(filename):
860         filename, ext = os.path.splitext(filename)
861         blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
862                      'TestLibCython']
863         return (ext == '.py' and not
864                 '~' in filename and not
865                 '#' in filename and not
866                 filename.startswith('.') and not
867                 filename in blacklist)
868     import doctest, types
869     for dirpath, dirnames, filenames in os.walk(path):
870         for dir in list(dirnames):
871             if not package_matches(dir):
872                 dirnames.remove(dir)
873         for f in filenames:
874             if file_matches(f):
875                 if not f.endswith('.py'): continue
876                 filepath = os.path.join(dirpath, f)
877                 if os.path.getsize(filepath) == 0: continue
878                 filepath = filepath[:-len(".py")]
879                 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
880                 if not [ 1 for match in selectors if match(modulename) ]:
881                     continue
882                 if 'in_gdb' in modulename:
883                     # These should only be imported from gdb.
884                     continue
885                 module = __import__(modulename)
886                 for x in modulename.split('.')[1:]:
887                     module = getattr(module, x)
888                 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
889                     try:
890                         suite.addTest(doctest.DocTestSuite(module))
891                     except ValueError: # no tests
892                         pass
893
894
895 class EndToEndTest(unittest.TestCase):
896     """
897     This is a test of build/*.srctree files, where srctree defines a full
898     directory structure and its header gives a list of commands to run.
899     """
900     cython_root = os.path.dirname(os.path.abspath(__file__))
901
902     def __init__(self, treefile, workdir, cleanup_workdir=True):
903         self.name = os.path.splitext(os.path.basename(treefile))[0]
904         self.treefile = treefile
905         self.workdir = os.path.join(workdir, self.name)
906         self.cleanup_workdir = cleanup_workdir
907         cython_syspath = self.cython_root
908         for path in sys.path[::-1]:
909             if path.startswith(self.cython_root):
910                 # Py3 installation and refnanny build prepend their
911                 # fixed paths to sys.path => prefer that over the
912                 # generic one
913                 cython_syspath = path + os.pathsep + cython_syspath
914         self.cython_syspath = cython_syspath
915         unittest.TestCase.__init__(self)
916
917     def shortDescription(self):
918         return "End-to-end %s" % self.name
919
920     def setUp(self):
921         from Cython.TestUtils import unpack_source_tree
922         _, self.commands = unpack_source_tree(self.treefile, self.workdir)
923         self.old_dir = os.getcwd()
924         os.chdir(self.workdir)
925         if self.workdir not in sys.path:
926             sys.path.insert(0, self.workdir)
927
928     def tearDown(self):
929         if self.cleanup_workdir:
930             for trial in range(5):
931                 try:
932                     shutil.rmtree(self.workdir)
933                 except OSError:
934                     time.sleep(0.1)
935                 else:
936                     break
937         os.chdir(self.old_dir)
938
939     def runTest(self):
940         commands = (self.commands
941             .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
942             .replace("PYTHON", sys.executable))
943         try:
944             old_path = os.environ.get('PYTHONPATH')
945             os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
946             for command in commands.split('\n'):
947                 if sys.version_info[:2] >= (2,4):
948                     import subprocess
949                     p = subprocess.Popen(commands,
950                                          stderr=subprocess.PIPE,
951                                          stdout=subprocess.PIPE,
952                                          shell=True)
953                     out, err = p.communicate()
954                     res = p.returncode
955                     if res != 0:
956                         print(command)
957                         print(out)
958                         print(err)
959                 else:
960                     res = os.system(command)
961                 self.assertEqual(0, res, "non-zero exit status")
962         finally:
963             if old_path:
964                 os.environ['PYTHONPATH'] = old_path
965             else:
966                 del os.environ['PYTHONPATH']
967
968
969 # TODO: Support cython_freeze needed here as well.
970 # TODO: Windows support.
971
972 class EmbedTest(unittest.TestCase):
973
974     working_dir = "Demos/embed"
975
976     def setUp(self):
977         self.old_dir = os.getcwd()
978         os.chdir(self.working_dir)
979         os.system(
980             "make PYTHON='%s' clean > /dev/null" % sys.executable)
981
982     def tearDown(self):
983         try:
984             os.system(
985                 "make PYTHON='%s' clean > /dev/null" % sys.executable)
986         except:
987             pass
988         os.chdir(self.old_dir)
989
990     def test_embed(self):
991         from distutils import sysconfig
992         libname = sysconfig.get_config_var('LIBRARY')
993         libdir = sysconfig.get_config_var('LIBDIR')
994         if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
995             libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
996             if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
997                 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
998                 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
999                     # report the error for the original directory
1000                     libdir = sysconfig.get_config_var('LIBDIR')
1001         cython = 'cython.py'
1002         if sys.version_info[0] >=3 and CY3_DIR:
1003             cython = os.path.join(CY3_DIR, cython)
1004         cython = os.path.abspath(os.path.join('..', '..', cython))
1005         self.assert_(os.system(
1006             "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
1007         try:
1008             os.remove('make.output')
1009         except OSError:
1010             pass
1011
1012 class MissingDependencyExcluder:
1013     def __init__(self, deps):
1014         # deps: { matcher func : module name }
1015         self.exclude_matchers = []
1016         for matcher, mod in deps.items():
1017             try:
1018                 __import__(mod)
1019             except ImportError:
1020                 self.exclude_matchers.append(string_selector(matcher))
1021         self.tests_missing_deps = []
1022     def __call__(self, testname, tags=None):
1023         for matcher in self.exclude_matchers:
1024             if matcher(testname, tags):
1025                 self.tests_missing_deps.append(testname)
1026                 return True
1027         return False
1028
1029 class VersionDependencyExcluder:
1030     def __init__(self, deps):
1031         # deps: { version : matcher func }
1032         from sys import version_info
1033         self.exclude_matchers = []
1034         for ver, (compare, matcher) in deps.items():
1035             if compare(version_info, ver):
1036                 self.exclude_matchers.append(matcher)
1037         self.tests_missing_deps = []
1038     def __call__(self, testname, tags=None):
1039         for matcher in self.exclude_matchers:
1040             if matcher(testname):
1041                 self.tests_missing_deps.append(testname)
1042                 return True
1043         return False
1044
1045 class FileListExcluder:
1046
1047     def __init__(self, list_file):
1048         self.excludes = {}
1049         f = open(list_file)
1050         try:
1051             for line in f.readlines():
1052                 line = line.strip()
1053                 if line and line[0] != '#':
1054                     self.excludes[line.split()[0]] = True
1055         finally:
1056             f.close()
1057
1058     def __call__(self, testname, tags=None):
1059         return testname in self.excludes or testname.split('.')[-1] in self.excludes
1060
1061 class TagsSelector:
1062
1063     def __init__(self, tag, value):
1064         self.tag = tag
1065         self.value = value
1066     
1067     def __call__(self, testname, tags=None):
1068         if tags is None:
1069             return False
1070         else:
1071             return self.value in tags[self.tag]
1072
1073 class RegExSelector:
1074     
1075     def __init__(self, pattern_string):
1076         self.pattern = re.compile(pattern_string, re.I|re.U)
1077
1078     def __call__(self, testname, tags=None):
1079         return self.pattern.search(testname)
1080
1081 def string_selector(s):
1082     ix = s.find(':')
1083     if ix == -1:
1084         return RegExSelector(s)
1085     else:
1086         return TagsSelector(s[:ix], s[ix+1:])
1087         
1088
1089 def refactor_for_py3(distdir, cy3_dir):
1090     # need to convert Cython sources first
1091     import lib2to3.refactor
1092     from distutils.util import copydir_run_2to3
1093     fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
1094                if fix.split('fix_')[-1] not in ('next',)
1095                ]
1096     if not os.path.exists(cy3_dir):
1097         os.makedirs(cy3_dir)
1098     import distutils.log as dlog
1099     dlog.set_threshold(dlog.INFO)
1100     copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1101                      template = '''
1102                      global-exclude *
1103                      graft Cython
1104                      recursive-exclude Cython *
1105                      recursive-include Cython *.py *.pyx *.pxd
1106                      recursive-include Cython/Debugger/Tests *
1107                      include runtests.py
1108                      include cython.py
1109                      ''')
1110     sys.path.insert(0, cy3_dir)
1111
1112     for keep_2x_file in KEEP_2X_FILES:
1113         destfile = os.path.join(cy3_dir, keep_2x_file)
1114         shutil.copy(keep_2x_file, destfile)
1115
1116 class PendingThreadsError(RuntimeError):
1117     pass
1118
1119 threads_seen = []
1120
1121 def check_thread_termination(ignore_seen=True):
1122     if threading is None: # no threading enabled in CPython
1123         return
1124     current = threading.currentThread()
1125     blocking_threads = []
1126     for t in threading.enumerate():
1127         if not t.isAlive() or t == current:
1128             continue
1129         t.join(timeout=2)
1130         if t.isAlive():
1131             if not ignore_seen:
1132                 blocking_threads.append(t)
1133                 continue
1134             for seen in threads_seen:
1135                 if t is seen:
1136                     break
1137             else:
1138                 threads_seen.append(t)
1139                 blocking_threads.append(t)
1140     if not blocking_threads:
1141         return
1142     sys.stderr.write("warning: left-over threads found after running test:\n")
1143     for t in blocking_threads:
1144         sys.stderr.write('...%s\n'  % repr(t))
1145     raise PendingThreadsError("left-over threads found after running test")
1146
1147 def main():
1148
1149     DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1150
1151     from optparse import OptionParser
1152     parser = OptionParser()
1153     parser.add_option("--no-cleanup", dest="cleanup_workdir",
1154                       action="store_false", default=True,
1155                       help="do not delete the generated C files (allows passing --no-cython on next run)")
1156     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1157                       action="store_false", default=True,
1158                       help="do not delete the generated shared libary files (allows manual module experimentation)")
1159     parser.add_option("--no-cython", dest="with_cython",
1160                       action="store_false", default=True,
1161                       help="do not run the Cython compiler, only the C compiler")
1162     parser.add_option("--compiler", dest="compiler", default=None,
1163                       help="C compiler type")
1164     parser.add_option("--no-c", dest="use_c",
1165                       action="store_false", default=True,
1166                       help="do not test C compilation")
1167     parser.add_option("--no-cpp", dest="use_cpp",
1168                       action="store_false", default=True,
1169                       help="do not test C++ compilation")
1170     parser.add_option("--no-unit", dest="unittests",
1171                       action="store_false", default=True,
1172                       help="do not run the unit tests")
1173     parser.add_option("--no-doctest", dest="doctests",
1174                       action="store_false", default=True,
1175                       help="do not run the doctests")
1176     parser.add_option("--no-file", dest="filetests",
1177                       action="store_false", default=True,
1178                       help="do not run the file based tests")
1179     parser.add_option("--no-pyregr", dest="pyregr",
1180                       action="store_false", default=True,
1181                       help="do not run the regression tests of CPython in tests/pyregr/")
1182     parser.add_option("--cython-only", dest="cython_only",
1183                       action="store_true", default=False,
1184                       help="only compile pyx to c, do not run C compiler or run the tests")
1185     parser.add_option("--no-refnanny", dest="with_refnanny",
1186                       action="store_false", default=True,
1187                       help="do not regression test reference counting")
1188     parser.add_option("--no-fork", dest="fork",
1189                       action="store_false", default=True,
1190                       help="do not fork to run tests")
1191     parser.add_option("--sys-pyregr", dest="system_pyregr",
1192                       action="store_true", default=False,
1193                       help="run the regression tests of the CPython installation")
1194     parser.add_option("-x", "--exclude", dest="exclude",
1195                       action="append", metavar="PATTERN",
1196                       help="exclude tests matching the PATTERN")
1197     parser.add_option("-C", "--coverage", dest="coverage",
1198                       action="store_true", default=False,
1199                       help="collect source coverage data for the Compiler")
1200     parser.add_option("--coverage-xml", dest="coverage_xml",
1201                       action="store_true", default=False,
1202                       help="collect source coverage data for the Compiler in XML format")
1203     parser.add_option("--coverage-html", dest="coverage_html",
1204                       action="store_true", default=False,
1205                       help="collect source coverage data for the Compiler in HTML format")
1206     parser.add_option("-A", "--annotate", dest="annotate_source",
1207                       action="store_true", default=True,
1208                       help="generate annotated HTML versions of the test source files")
1209     parser.add_option("--no-annotate", dest="annotate_source",
1210                       action="store_false",
1211                       help="do not generate annotated HTML versions of the test source files")
1212     parser.add_option("-v", "--verbose", dest="verbosity",
1213                       action="count", default=0,
1214                       help="display test progress, pass twice to print test names")
1215     parser.add_option("-T", "--ticket", dest="tickets",
1216                       action="append",
1217                       help="a bug ticket number to run the respective test in 'tests/*'")
1218     parser.add_option("-3", dest="language_level",
1219                       action="store_const", const=3, default=2,
1220                       help="set language level to Python 3 (useful for running the CPython regression tests)'")
1221     parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1222                       help="write test results in XML to directory DIR")
1223     parser.add_option("--exit-ok", dest="exit_ok", default=False,
1224                       action="store_true",
1225                       help="exit without error code even on test failures")
1226     parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1227                       help="working directory")
1228     parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1229                       help="working directory")
1230
1231     options, cmd_args = parser.parse_args()
1232
1233     ROOTDIR = os.path.abspath(options.root_dir)
1234     WORKDIR = os.path.abspath(options.work_dir)
1235
1236     if sys.version_info[0] >= 3:
1237         options.doctests = False
1238         if options.with_cython:
1239             try:
1240                 # try if Cython is installed in a Py3 version
1241                 import Cython.Compiler.Main
1242             except Exception:
1243                 # back out anything the import process loaded, then
1244                 # 2to3 the Cython sources to make them re-importable
1245                 cy_modules = [ name for name in sys.modules
1246                                if name == 'Cython' or name.startswith('Cython.') ]
1247                 for name in cy_modules:
1248                     del sys.modules[name]
1249                 # hasn't been refactored yet - do it now
1250                 global CY3_DIR
1251                 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1252                 if sys.version_info >= (3,1):
1253                     refactor_for_py3(DISTDIR, cy3_dir)
1254                 elif os.path.isdir(cy3_dir):
1255                     sys.path.insert(0, cy3_dir)
1256                 else:
1257                     options.with_cython = False
1258
1259     WITH_CYTHON = options.with_cython
1260
1261     if options.coverage or options.coverage_xml or options.coverage_html:
1262         if not WITH_CYTHON:
1263             options.coverage = options.coverage_xml = options.coverage_html = False
1264         else:
1265             from coverage import coverage as _coverage
1266             coverage = _coverage(branch=True)
1267             coverage.erase()
1268             coverage.start()
1269
1270     if WITH_CYTHON:
1271         global CompilationOptions, pyrex_default_options, cython_compile
1272         from Cython.Compiler.Main import \
1273             CompilationOptions, \
1274             default_options as pyrex_default_options, \
1275             compile as cython_compile
1276         from Cython.Compiler import Errors
1277         Errors.LEVEL = 0 # show all warnings
1278         from Cython.Compiler import Options
1279         Options.generate_cleanup_code = 3   # complete cleanup code
1280         from Cython.Compiler import DebugFlags
1281         DebugFlags.debug_temp_code_comments = 1
1282
1283     # RUN ALL TESTS!
1284     UNITTEST_MODULE = "Cython"
1285     UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1286     if WITH_CYTHON:
1287         if os.path.exists(WORKDIR):
1288             for path in os.listdir(WORKDIR):
1289                 if path in ("support", "Cy3"): continue
1290                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1291     if not os.path.exists(WORKDIR):
1292         os.makedirs(WORKDIR)
1293
1294     sys.stderr.write("Python %s\n" % sys.version)
1295     sys.stderr.write("\n")
1296     if WITH_CYTHON:
1297         from Cython.Compiler.Version import version
1298         sys.stderr.write("Running tests against Cython %s\n" % version)
1299     else:
1300         sys.stderr.write("Running tests without Cython.\n")
1301
1302     if options.with_refnanny:
1303         from pyximport.pyxbuild import pyx_to_dll
1304         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1305                              build_in_temp=True,
1306                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
1307         sys.path.insert(0, os.path.split(libpath)[0])
1308         CFLAGS.append("-DCYTHON_REFNANNY=1")
1309
1310     if options.xml_output_dir and options.fork:
1311         # doesn't currently work together
1312         sys.stderr.write("Disabling forked testing to support XML test output\n")
1313         options.fork = False
1314
1315     if WITH_CYTHON and options.language_level == 3:
1316         sys.stderr.write("Using Cython language level 3.\n")
1317
1318     sys.stderr.write("\n")
1319
1320     test_bugs = False
1321     if options.tickets:
1322         for ticket_number in options.tickets:
1323             test_bugs = True
1324             cmd_args.append('ticket:%s' % ticket_number)
1325     if not test_bugs:
1326         for selector in cmd_args:
1327             if selector.startswith('bugs'):
1328                 test_bugs = True
1329
1330     import re
1331     selectors = [ string_selector(r) for r in cmd_args ]
1332     if not selectors:
1333         selectors = [ lambda x, tags=None: True ]
1334
1335     # Chech which external modules are not present and exclude tests
1336     # which depends on them (by prefix)
1337
1338     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1339     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1340     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1341
1342     if options.exclude:
1343         exclude_selectors += [ string_selector(r) for r in options.exclude ]
1344
1345     if not test_bugs:
1346         exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1347
1348     if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1349         exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1350
1351     global COMPILER
1352     if options.compiler:
1353         COMPILER = options.compiler
1354     languages = []
1355     if options.use_c:
1356         languages.append('c')
1357     if options.use_cpp:
1358         languages.append('cpp')
1359
1360     test_suite = unittest.TestSuite()
1361
1362     if options.unittests:
1363         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1364
1365     if options.doctests:
1366         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1367
1368     if options.filetests and languages:
1369         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1370                                 options.annotate_source, options.cleanup_workdir,
1371                                 options.cleanup_sharedlibs, options.pyregr,
1372                                 options.cython_only, languages, test_bugs,
1373                                 options.fork, options.language_level)
1374         test_suite.addTest(filetests.build_suite())
1375
1376     if options.system_pyregr and languages:
1377         sys_pyregr_dir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test')
1378         if os.path.isdir(sys_pyregr_dir):
1379             filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1380                                     options.annotate_source, options.cleanup_workdir,
1381                                     options.cleanup_sharedlibs, True,
1382                                     options.cython_only, languages, test_bugs,
1383                                     options.fork, sys.version_info[0])
1384             sys.stderr.write("Including CPython regression tests in %s\n" % sys_pyregr_dir)
1385             test_suite.addTest(filetests.handle_directory(sys_pyregr_dir, 'pyregr'))
1386
1387     if options.xml_output_dir:
1388         from Cython.Tests.xmlrunner import XMLTestRunner
1389         test_runner = XMLTestRunner(output=options.xml_output_dir,
1390                                     verbose=options.verbosity > 0)
1391     else:
1392         test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1393
1394     result = test_runner.run(test_suite)
1395
1396     if options.coverage or options.coverage_xml or options.coverage_html:
1397         coverage.stop()
1398         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1399         modules = [ module for name, module in sys.modules.items()
1400                     if module is not None and
1401                     name.startswith('Cython.Compiler.') and
1402                     name[len('Cython.Compiler.'):] not in ignored_modules ]
1403         if options.coverage:
1404             coverage.report(modules, show_missing=0)
1405         if options.coverage_xml:
1406             coverage.xml_report(modules, outfile="coverage-report.xml")
1407         if options.coverage_html:
1408             coverage.html_report(modules, directory="coverage-report-html")
1409
1410     if missing_dep_excluder.tests_missing_deps:
1411         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1412         for test in missing_dep_excluder.tests_missing_deps:
1413             sys.stderr.write("   %s\n" % test)
1414
1415     if options.with_refnanny:
1416         import refnanny
1417         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1418
1419     print("ALL DONE")
1420
1421     if options.exit_ok:
1422         return_code = 0
1423     else:
1424         return_code = not result.wasSuccessful()
1425
1426     try:
1427         check_thread_termination(ignore_seen=False)
1428         sys.exit(return_code)
1429     except PendingThreadsError:
1430         # normal program exit won't kill the threads, do it the hard way here
1431         os._exit(return_code)
1432
1433 if __name__ == '__main__':
1434     try:
1435         main()
1436     except SystemExit: # <= Py2.4 ...
1437         raise
1438     except Exception:
1439         traceback.print_exc()
1440         try:
1441             check_thread_termination(ignore_seen=False)
1442         except PendingThreadsError:
1443             # normal program exit won't kill the threads, do it the hard way here
1444             os._exit(1)