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