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