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