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