fix non-forked testing
[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         def run_test(result):
592             tests = doctest.DocTestSuite(module_name)
593             tests.run(result)
594         run_forked_test(result, run_test, self.shortDescription(), self.fork)
595
596
597 def run_forked_test(result, run_func, test_name, fork=True):
598     if not fork or sys.version_info[0] >= 3 or not hasattr(os, 'fork'):
599         run_func(result)
600         gc.collect()
601         return
602
603     # fork to make sure we do not keep the tested module loaded
604     result_handle, result_file = tempfile.mkstemp()
605     os.close(result_handle)
606     child_id = os.fork()
607     if not child_id:
608         result_code = 0
609         try:
610             try:
611                 tests = None
612                 try:
613                     partial_result = PartialTestResult(result)
614                     run_func(partial_result)
615                     gc.collect()
616                 except Exception:
617                     if tests is None:
618                         # importing failed, try to fake a test class
619                         tests = _FakeClass(
620                             failureException=sys.exc_info()[1],
621                             _shortDescription=test_name,
622                             module_name=None)
623                     partial_result.addError(tests, sys.exc_info())
624                     result_code = 1
625                 output = open(result_file, 'wb')
626                 pickle.dump(partial_result.data(), output)
627             except:
628                 traceback.print_exc()
629         finally:
630             try: output.close()
631             except: pass
632             os._exit(result_code)
633
634     try:
635         cid, result_code = os.waitpid(child_id, 0)
636         # os.waitpid returns the child's result code in the
637         # upper byte of result_code, and the signal it was
638         # killed by in the lower byte
639         if result_code & 255:
640             raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
641                             (module_name, result_code & 255))
642         result_code = result_code >> 8
643         if result_code in (0,1):
644             input = open(result_file, 'rb')
645             try:
646                 PartialTestResult.join_results(result, pickle.load(input))
647             finally:
648                 input.close()
649         if result_code:
650             raise Exception("Tests in module '%s' exited with status %d" %
651                             (module_name, result_code))
652     finally:
653         try: os.unlink(result_file)
654         except: pass
655
656 class PureDoctestTestCase(unittest.TestCase):
657     def __init__(self, module_name, module_path):
658         self.module_name = module_name
659         self.module_path = module_path
660         unittest.TestCase.__init__(self, 'run')
661
662     def shortDescription(self):
663         return "running pure doctests in %s" % self.module_name
664
665     def run(self, result=None):
666         if result is None:
667             result = self.defaultTestResult()
668         loaded_module_name = 'pure_doctest__' + self.module_name
669         result.startTest(self)
670         try:
671             self.setUp()
672
673             import imp
674             m = imp.load_source(loaded_module_name, self.module_path)
675             try:
676                 doctest.DocTestSuite(m).run(result)
677             finally:
678                 del m
679                 if loaded_module_name in sys.modules:
680                     del sys.modules[loaded_module_name]
681                 check_thread_termination()
682         except Exception:
683             result.addError(self, sys.exc_info())
684             result.stopTest(self)
685         try:
686             self.tearDown()
687         except Exception:
688             pass
689
690 is_private_field = re.compile('^_[^_]').match
691
692 class _FakeClass(object):
693     def __init__(self, **kwargs):
694         self._shortDescription = kwargs.get('module_name')
695         self.__dict__.update(kwargs)
696     def shortDescription(self):
697         return self._shortDescription
698
699 try: # Py2.7+ and Py3.2+
700     from unittest.runner import _TextTestResult
701 except ImportError:
702     from unittest import _TextTestResult
703
704 class PartialTestResult(_TextTestResult):
705     def __init__(self, base_result):
706         _TextTestResult.__init__(
707             self, self._StringIO(), True,
708             base_result.dots + base_result.showAll*2)
709
710     def strip_error_results(self, results):
711         for test_case, error in results:
712             for attr_name in filter(is_private_field, dir(test_case)):
713                 if attr_name == '_dt_test':
714                     test_case._dt_test = _FakeClass(
715                         name=test_case._dt_test.name)
716                 elif attr_name != '_shortDescription':
717                     setattr(test_case, attr_name, None)
718
719     def data(self):
720         self.strip_error_results(self.failures)
721         self.strip_error_results(self.errors)
722         return (self.failures, self.errors, self.testsRun,
723                 self.stream.getvalue())
724
725     def join_results(result, data):
726         """Static method for merging the result back into the main
727         result object.
728         """
729         failures, errors, tests_run, output = data
730         if output:
731             result.stream.write(output)
732         result.errors.extend(errors)
733         result.failures.extend(failures)
734         result.testsRun += tests_run
735
736     join_results = staticmethod(join_results)
737
738     class _StringIO(StringIO):
739         def writeln(self, line):
740             self.write("%s\n" % line)
741
742
743 class CythonUnitTestCase(CythonRunTestCase):
744     def shortDescription(self):
745         return "compiling (%s) tests in %s" % (self.language, self.module)
746
747     def run_tests(self, result):
748         unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
749
750
751 class CythonPyregrTestCase(CythonRunTestCase):
752     def setUp(self):
753         CythonRunTestCase.setUp(self)
754         from Cython.Compiler import Options
755         Options.error_on_unknown_names = False
756
757     def _run_unittest(self, result, *classes):
758         """Run tests from unittest.TestCase-derived classes."""
759         valid_types = (unittest.TestSuite, unittest.TestCase)
760         suite = unittest.TestSuite()
761         for cls in classes:
762             if isinstance(cls, str):
763                 if cls in sys.modules:
764                     suite.addTest(unittest.findTestCases(sys.modules[cls]))
765                 else:
766                     raise ValueError("str arguments must be keys in sys.modules")
767             elif isinstance(cls, valid_types):
768                 suite.addTest(cls)
769             else:
770                 suite.addTest(unittest.makeSuite(cls))
771         suite.run(result)
772
773     def _run_doctest(self, result, module):
774         self.run_doctests(module, result)
775
776     def run_tests(self, result):
777         try:
778             from test import test_support as support
779         except ImportError: # Py3k
780             from test import support
781
782         def run_test(result):
783             def run_unittest(*classes):
784                 return self._run_unittest(result, *classes)
785             def run_doctest(module, verbosity=None):
786                 return self._run_doctest(result, module)
787
788             support.run_unittest = run_unittest
789             support.run_doctest = run_doctest
790
791             try:
792                 module = __import__(self.module)
793                 if hasattr(module, 'test_main'):
794                     module.test_main()
795             except (unittest.SkipTest, support.ResourceDenied):
796                 result.addSkip(self, 'ok')
797
798         run_forked_test(result, run_test, self.shortDescription(), self.fork)
799
800 include_debugger = sys.version_info[:2] > (2, 5)
801
802 def collect_unittests(path, module_prefix, suite, selectors):
803     def file_matches(filename):
804         return filename.startswith("Test") and filename.endswith(".py")
805
806     def package_matches(dirname):
807         return dirname == "Tests"
808
809     loader = unittest.TestLoader()
810
811     if include_debugger:
812         skipped_dirs = []
813     else:
814         skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
815
816     for dirpath, dirnames, filenames in os.walk(path):
817         if dirpath != path and "__init__.py" not in filenames:
818             skipped_dirs.append(dirpath + os.path.sep)
819             continue
820         skip = False
821         for dir in skipped_dirs:
822             if dirpath.startswith(dir):
823                 skip = True
824         if skip:
825             continue
826         parentname = os.path.split(dirpath)[-1]
827         if package_matches(parentname):
828             for f in filenames:
829                 if file_matches(f):
830                     filepath = os.path.join(dirpath, f)[:-len(".py")]
831                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
832                     if not [ 1 for match in selectors if match(modulename) ]:
833                         continue
834                     module = __import__(modulename)
835                     for x in modulename.split('.')[1:]:
836                         module = getattr(module, x)
837                     suite.addTests([loader.loadTestsFromModule(module)])
838
839
840
841 def collect_doctests(path, module_prefix, suite, selectors):
842     def package_matches(dirname):
843         if dirname == 'Debugger' and not include_debugger:
844             return False
845         return dirname not in ("Mac", "Distutils", "Plex")
846     def file_matches(filename):
847         filename, ext = os.path.splitext(filename)
848         blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
849                      'TestLibCython']
850         return (ext == '.py' and not
851                 '~' in filename and not
852                 '#' in filename and not
853                 filename.startswith('.') and not
854                 filename in blacklist)
855     import doctest, types
856     for dirpath, dirnames, filenames in os.walk(path):
857         for dir in list(dirnames):
858             if not package_matches(dir):
859                 dirnames.remove(dir)
860         for f in filenames:
861             if file_matches(f):
862                 if not f.endswith('.py'): continue
863                 filepath = os.path.join(dirpath, f)
864                 if os.path.getsize(filepath) == 0: continue
865                 filepath = filepath[:-len(".py")]
866                 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
867                 if not [ 1 for match in selectors if match(modulename) ]:
868                     continue
869                 if 'in_gdb' in modulename:
870                     # These should only be imported from gdb.
871                     continue
872                 module = __import__(modulename)
873                 for x in modulename.split('.')[1:]:
874                     module = getattr(module, x)
875                 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
876                     try:
877                         suite.addTest(doctest.DocTestSuite(module))
878                     except ValueError: # no tests
879                         pass
880
881
882 class EndToEndTest(unittest.TestCase):
883     """
884     This is a test of build/*.srctree files, where srctree defines a full
885     directory structure and its header gives a list of commands to run.
886     """
887     cython_root = os.path.dirname(os.path.abspath(__file__))
888
889     def __init__(self, treefile, workdir, cleanup_workdir=True):
890         self.name = os.path.splitext(os.path.basename(treefile))[0]
891         self.treefile = treefile
892         self.workdir = os.path.join(workdir, self.name)
893         self.cleanup_workdir = cleanup_workdir
894         cython_syspath = self.cython_root
895         for path in sys.path[::-1]:
896             if path.startswith(self.cython_root):
897                 # Py3 installation and refnanny build prepend their
898                 # fixed paths to sys.path => prefer that over the
899                 # generic one
900                 cython_syspath = path + os.pathsep + cython_syspath
901         self.cython_syspath = cython_syspath
902         unittest.TestCase.__init__(self)
903
904     def shortDescription(self):
905         return "End-to-end %s" % self.name
906
907     def setUp(self):
908         from Cython.TestUtils import unpack_source_tree
909         _, self.commands = unpack_source_tree(self.treefile, self.workdir)
910         self.old_dir = os.getcwd()
911         os.chdir(self.workdir)
912         if self.workdir not in sys.path:
913             sys.path.insert(0, self.workdir)
914
915     def tearDown(self):
916         if self.cleanup_workdir:
917             for trial in range(5):
918                 try:
919                     shutil.rmtree(self.workdir)
920                 except OSError:
921                     time.sleep(0.1)
922                 else:
923                     break
924         os.chdir(self.old_dir)
925
926     def runTest(self):
927         commands = (self.commands
928             .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
929             .replace("PYTHON", sys.executable))
930         try:
931             old_path = os.environ.get('PYTHONPATH')
932             os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
933             for command in commands.split('\n'):
934                 if sys.version_info[:2] >= (2,4):
935                     import subprocess
936                     p = subprocess.Popen(commands,
937                                          stderr=subprocess.PIPE,
938                                          stdout=subprocess.PIPE,
939                                          shell=True)
940                     out, err = p.communicate()
941                     res = p.returncode
942                     if res != 0:
943                         print(command)
944                         print(out)
945                         print(err)
946                 else:
947                     res = os.system(command)
948                 self.assertEqual(0, res, "non-zero exit status")
949         finally:
950             if old_path:
951                 os.environ['PYTHONPATH'] = old_path
952             else:
953                 del os.environ['PYTHONPATH']
954
955
956 # TODO: Support cython_freeze needed here as well.
957 # TODO: Windows support.
958
959 class EmbedTest(unittest.TestCase):
960
961     working_dir = "Demos/embed"
962
963     def setUp(self):
964         self.old_dir = os.getcwd()
965         os.chdir(self.working_dir)
966         os.system(
967             "make PYTHON='%s' clean > /dev/null" % sys.executable)
968
969     def tearDown(self):
970         try:
971             os.system(
972                 "make PYTHON='%s' clean > /dev/null" % sys.executable)
973         except:
974             pass
975         os.chdir(self.old_dir)
976
977     def test_embed(self):
978         from distutils import sysconfig
979         libname = sysconfig.get_config_var('LIBRARY')
980         libdir = sysconfig.get_config_var('LIBDIR')
981         if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
982             libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
983             if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
984                 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
985                 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
986                     # report the error for the original directory
987                     libdir = sysconfig.get_config_var('LIBDIR')
988         cython = 'cython.py'
989         if sys.version_info[0] >=3 and CY3_DIR:
990             cython = os.path.join(CY3_DIR, cython)
991         cython = os.path.abspath(os.path.join('..', '..', cython))
992         self.assert_(os.system(
993             "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
994         try:
995             os.remove('make.output')
996         except OSError:
997             pass
998
999 class MissingDependencyExcluder:
1000     def __init__(self, deps):
1001         # deps: { module name : matcher func }
1002         self.exclude_matchers = []
1003         for mod, matcher in deps.items():
1004             try:
1005                 __import__(mod)
1006             except ImportError:
1007                 self.exclude_matchers.append(string_selector(matcher))
1008         self.tests_missing_deps = []
1009     def __call__(self, testname, tags=None):
1010         for matcher in self.exclude_matchers:
1011             if matcher(testname, tags):
1012                 self.tests_missing_deps.append(testname)
1013                 return True
1014         return False
1015
1016 class VersionDependencyExcluder:
1017     def __init__(self, deps):
1018         # deps: { version : matcher func }
1019         from sys import version_info
1020         self.exclude_matchers = []
1021         for ver, (compare, matcher) in deps.items():
1022             if compare(version_info, ver):
1023                 self.exclude_matchers.append(matcher)
1024         self.tests_missing_deps = []
1025     def __call__(self, testname, tags=None):
1026         for matcher in self.exclude_matchers:
1027             if matcher(testname):
1028                 self.tests_missing_deps.append(testname)
1029                 return True
1030         return False
1031
1032 class FileListExcluder:
1033
1034     def __init__(self, list_file):
1035         self.excludes = {}
1036         f = open(list_file)
1037         try:
1038             for line in f.readlines():
1039                 line = line.strip()
1040                 if line and line[0] != '#':
1041                     self.excludes[line.split()[0]] = True
1042         finally:
1043             f.close()
1044
1045     def __call__(self, testname, tags=None):
1046         return testname in self.excludes or testname.split('.')[-1] in self.excludes
1047
1048 class TagsSelector:
1049
1050     def __init__(self, tag, value):
1051         self.tag = tag
1052         self.value = value
1053     
1054     def __call__(self, testname, tags=None):
1055         if tags is None:
1056             return False
1057         else:
1058             return self.value in tags[self.tag]
1059
1060 class RegExSelector:
1061     
1062     def __init__(self, pattern_string):
1063         self.pattern = re.compile(pattern_string, re.I|re.U)
1064
1065     def __call__(self, testname, tags=None):
1066         return self.pattern.search(testname)
1067
1068 def string_selector(s):
1069     ix = s.find(':')
1070     if ix == -1:
1071         return RegExSelector(s)
1072     else:
1073         return TagsSelector(s[:ix], s[ix+1:])
1074         
1075
1076 def refactor_for_py3(distdir, cy3_dir):
1077     # need to convert Cython sources first
1078     import lib2to3.refactor
1079     from distutils.util import copydir_run_2to3
1080     fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
1081                if fix.split('fix_')[-1] not in ('next',)
1082                ]
1083     if not os.path.exists(cy3_dir):
1084         os.makedirs(cy3_dir)
1085     import distutils.log as dlog
1086     dlog.set_threshold(dlog.INFO)
1087     copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1088                      template = '''
1089                      global-exclude *
1090                      graft Cython
1091                      recursive-exclude Cython *
1092                      recursive-include Cython *.py *.pyx *.pxd
1093                      recursive-include Cython/Debugger/Tests *
1094                      include runtests.py
1095                      include cython.py
1096                      ''')
1097     sys.path.insert(0, cy3_dir)
1098
1099     for keep_2x_file in KEEP_2X_FILES:
1100         destfile = os.path.join(cy3_dir, keep_2x_file)
1101         shutil.copy(keep_2x_file, destfile)
1102
1103 class PendingThreadsError(RuntimeError):
1104     pass
1105
1106 threads_seen = []
1107
1108 def check_thread_termination(ignore_seen=True):
1109     if threading is None: # no threading enabled in CPython
1110         return
1111     current = threading.currentThread()
1112     blocking_threads = []
1113     for t in threading.enumerate():
1114         if not t.isAlive() or t == current:
1115             continue
1116         t.join(timeout=2)
1117         if t.isAlive():
1118             if not ignore_seen:
1119                 blocking_threads.append(t)
1120                 continue
1121             for seen in threads_seen:
1122                 if t is seen:
1123                     break
1124             else:
1125                 threads_seen.append(t)
1126                 blocking_threads.append(t)
1127     if not blocking_threads:
1128         return
1129     sys.stderr.write("warning: left-over threads found after running test:\n")
1130     for t in blocking_threads:
1131         sys.stderr.write('...%s\n'  % repr(t))
1132     raise PendingThreadsError("left-over threads found after running test")
1133
1134 def main():
1135
1136     DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1137
1138     from optparse import OptionParser
1139     parser = OptionParser()
1140     parser.add_option("--no-cleanup", dest="cleanup_workdir",
1141                       action="store_false", default=True,
1142                       help="do not delete the generated C files (allows passing --no-cython on next run)")
1143     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1144                       action="store_false", default=True,
1145                       help="do not delete the generated shared libary files (allows manual module experimentation)")
1146     parser.add_option("--no-cython", dest="with_cython",
1147                       action="store_false", default=True,
1148                       help="do not run the Cython compiler, only the C compiler")
1149     parser.add_option("--compiler", dest="compiler", default=None,
1150                       help="C compiler type")
1151     parser.add_option("--no-c", dest="use_c",
1152                       action="store_false", default=True,
1153                       help="do not test C compilation")
1154     parser.add_option("--no-cpp", dest="use_cpp",
1155                       action="store_false", default=True,
1156                       help="do not test C++ compilation")
1157     parser.add_option("--no-unit", dest="unittests",
1158                       action="store_false", default=True,
1159                       help="do not run the unit tests")
1160     parser.add_option("--no-doctest", dest="doctests",
1161                       action="store_false", default=True,
1162                       help="do not run the doctests")
1163     parser.add_option("--no-file", dest="filetests",
1164                       action="store_false", default=True,
1165                       help="do not run the file based tests")
1166     parser.add_option("--no-pyregr", dest="pyregr",
1167                       action="store_false", default=True,
1168                       help="do not run the regression tests of CPython in tests/pyregr/")
1169     parser.add_option("--cython-only", dest="cython_only",
1170                       action="store_true", default=False,
1171                       help="only compile pyx to c, do not run C compiler or run the tests")
1172     parser.add_option("--no-refnanny", dest="with_refnanny",
1173                       action="store_false", default=True,
1174                       help="do not regression test reference counting")
1175     parser.add_option("--no-fork", dest="fork",
1176                       action="store_false", default=True,
1177                       help="do not fork to run tests")
1178     parser.add_option("--sys-pyregr", dest="system_pyregr",
1179                       action="store_true", default=False,
1180                       help="run the regression tests of the CPython installation")
1181     parser.add_option("-x", "--exclude", dest="exclude",
1182                       action="append", metavar="PATTERN",
1183                       help="exclude tests matching the PATTERN")
1184     parser.add_option("-C", "--coverage", dest="coverage",
1185                       action="store_true", default=False,
1186                       help="collect source coverage data for the Compiler")
1187     parser.add_option("--coverage-xml", dest="coverage_xml",
1188                       action="store_true", default=False,
1189                       help="collect source coverage data for the Compiler in XML format")
1190     parser.add_option("-A", "--annotate", dest="annotate_source",
1191                       action="store_true", default=True,
1192                       help="generate annotated HTML versions of the test source files")
1193     parser.add_option("--no-annotate", dest="annotate_source",
1194                       action="store_false",
1195                       help="do not generate annotated HTML versions of the test source files")
1196     parser.add_option("-v", "--verbose", dest="verbosity",
1197                       action="count", default=0,
1198                       help="display test progress, pass twice to print test names")
1199     parser.add_option("-T", "--ticket", dest="tickets",
1200                       action="append",
1201                       help="a bug ticket number to run the respective test in 'tests/*'")
1202     parser.add_option("-3", dest="language_level",
1203                       action="store_const", const=3, default=2,
1204                       help="set language level to Python 3 (useful for running the CPython regression tests)'")
1205     parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1206                       help="write test results in XML to directory DIR")
1207     parser.add_option("--exit-ok", dest="exit_ok", default=False,
1208                       action="store_true",
1209                       help="exit without error code even on test failures")
1210     parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1211                       help="working directory")
1212     parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1213                       help="working directory")
1214
1215     options, cmd_args = parser.parse_args()
1216
1217     ROOTDIR = os.path.abspath(options.root_dir)
1218     WORKDIR = os.path.abspath(options.work_dir)
1219
1220     if sys.version_info[0] >= 3:
1221         options.doctests = False
1222         if options.with_cython:
1223             try:
1224                 # try if Cython is installed in a Py3 version
1225                 import Cython.Compiler.Main
1226             except Exception:
1227                 # back out anything the import process loaded, then
1228                 # 2to3 the Cython sources to make them re-importable
1229                 cy_modules = [ name for name in sys.modules
1230                                if name == 'Cython' or name.startswith('Cython.') ]
1231                 for name in cy_modules:
1232                     del sys.modules[name]
1233                 # hasn't been refactored yet - do it now
1234                 global CY3_DIR
1235                 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1236                 if sys.version_info >= (3,1):
1237                     refactor_for_py3(DISTDIR, cy3_dir)
1238                 elif os.path.isdir(cy3_dir):
1239                     sys.path.insert(0, cy3_dir)
1240                 else:
1241                     options.with_cython = False
1242
1243     WITH_CYTHON = options.with_cython
1244
1245     if options.coverage or options.coverage_xml:
1246         if not WITH_CYTHON:
1247             options.coverage = options.coverage_xml = False
1248         else:
1249             from coverage import coverage as _coverage
1250             coverage = _coverage(branch=True)
1251             coverage.erase()
1252             coverage.start()
1253
1254     if WITH_CYTHON:
1255         global CompilationOptions, pyrex_default_options, cython_compile
1256         from Cython.Compiler.Main import \
1257             CompilationOptions, \
1258             default_options as pyrex_default_options, \
1259             compile as cython_compile
1260         from Cython.Compiler import Errors
1261         Errors.LEVEL = 0 # show all warnings
1262         from Cython.Compiler import Options
1263         Options.generate_cleanup_code = 3   # complete cleanup code
1264         from Cython.Compiler import DebugFlags
1265         DebugFlags.debug_temp_code_comments = 1
1266
1267     # RUN ALL TESTS!
1268     UNITTEST_MODULE = "Cython"
1269     UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1270     if WITH_CYTHON:
1271         if os.path.exists(WORKDIR):
1272             for path in os.listdir(WORKDIR):
1273                 if path in ("support", "Cy3"): continue
1274                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1275     if not os.path.exists(WORKDIR):
1276         os.makedirs(WORKDIR)
1277
1278     sys.stderr.write("Python %s\n" % sys.version)
1279     sys.stderr.write("\n")
1280     if WITH_CYTHON:
1281         from Cython.Compiler.Version import version
1282         sys.stderr.write("Running tests against Cython %s\n" % version)
1283     else:
1284         sys.stderr.write("Running tests without Cython.\n")
1285
1286     if options.with_refnanny:
1287         from pyximport.pyxbuild import pyx_to_dll
1288         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1289                              build_in_temp=True,
1290                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
1291         sys.path.insert(0, os.path.split(libpath)[0])
1292         CFLAGS.append("-DCYTHON_REFNANNY=1")
1293
1294     if options.xml_output_dir and options.fork:
1295         # doesn't currently work together
1296         sys.stderr.write("Disabling forked testing to support XML test output\n")
1297         options.fork = False
1298
1299     if WITH_CYTHON and options.language_level == 3:
1300         sys.stderr.write("Using Cython language level 3.\n")
1301
1302     sys.stderr.write("\n")
1303
1304     test_bugs = False
1305     if options.tickets:
1306         for ticket_number in options.tickets:
1307             test_bugs = True
1308             cmd_args.append('ticket:%s' % ticket_number)
1309     if not test_bugs:
1310         for selector in cmd_args:
1311             if selector.startswith('bugs'):
1312                 test_bugs = True
1313
1314     import re
1315     selectors = [ string_selector(r) for r in cmd_args ]
1316     if not selectors:
1317         selectors = [ lambda x, tags=None: True ]
1318
1319     # Chech which external modules are not present and exclude tests
1320     # which depends on them (by prefix)
1321
1322     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1323     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1324     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1325
1326     if options.exclude:
1327         exclude_selectors += [ string_selector(r) for r in options.exclude ]
1328
1329     if not test_bugs:
1330         exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1331
1332     if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1333         exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1334
1335     global COMPILER
1336     if options.compiler:
1337         COMPILER = options.compiler
1338     languages = []
1339     if options.use_c:
1340         languages.append('c')
1341     if options.use_cpp:
1342         languages.append('cpp')
1343
1344     test_suite = unittest.TestSuite()
1345
1346     if options.unittests:
1347         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1348
1349     if options.doctests:
1350         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1351
1352     if options.filetests and languages:
1353         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1354                                 options.annotate_source, options.cleanup_workdir,
1355                                 options.cleanup_sharedlibs, options.pyregr,
1356                                 options.cython_only, languages, test_bugs,
1357                                 options.fork, options.language_level)
1358         test_suite.addTest(filetests.build_suite())
1359
1360     if options.system_pyregr and languages:
1361         sys_pyregr_dir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test')
1362         if os.path.isdir(sys_pyregr_dir):
1363             filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1364                                     options.annotate_source, options.cleanup_workdir,
1365                                     options.cleanup_sharedlibs, True,
1366                                     options.cython_only, languages, test_bugs,
1367                                     options.fork, sys.version_info[0])
1368             sys.stderr.write("Including CPython regression tests in %s\n" % sys_pyregr_dir)
1369             test_suite.addTest(filetests.handle_directory(sys_pyregr_dir, 'pyregr'))
1370
1371     if options.xml_output_dir:
1372         from Cython.Tests.xmlrunner import XMLTestRunner
1373         test_runner = XMLTestRunner(output=options.xml_output_dir,
1374                                     verbose=options.verbosity > 0)
1375     else:
1376         test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1377
1378     result = test_runner.run(test_suite)
1379
1380     if options.coverage or options.coverage_xml:
1381         coverage.stop()
1382         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1383         modules = [ module for name, module in sys.modules.items()
1384                     if module is not None and
1385                     name.startswith('Cython.Compiler.') and
1386                     name[len('Cython.Compiler.'):] not in ignored_modules ]
1387         if options.coverage:
1388             coverage.report(modules, show_missing=0)
1389         if options.coverage_xml:
1390             coverage.xml_report(modules, outfile="coverage-report.xml")
1391
1392     if missing_dep_excluder.tests_missing_deps:
1393         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1394         for test in missing_dep_excluder.tests_missing_deps:
1395             sys.stderr.write("   %s\n" % test)
1396
1397     if options.with_refnanny:
1398         import refnanny
1399         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1400
1401     print("ALL DONE")
1402
1403     if options.exit_ok:
1404         return_code = 0
1405     else:
1406         return_code = not result.wasSuccessful()
1407
1408     try:
1409         check_thread_termination(ignore_seen=False)
1410         sys.exit(return_code)
1411     except PendingThreadsError:
1412         # normal program exit won't kill the threads, do it the hard way here
1413         os._exit(return_code)
1414
1415 if __name__ == '__main__':
1416     try:
1417         main()
1418     except SystemExit: # <= Py2.4 ...
1419         raise
1420     except Exception:
1421         traceback.print_exc()
1422         try:
1423             check_thread_termination(ignore_seen=False)
1424         except PendingThreadsError:
1425             # normal program exit won't kill the threads, do it the hard way here
1426             os._exit(1)