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