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