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