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