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