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