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