Cpp exception tests.
[cython.git] / runtests.py
1 #!/usr/bin/python
2
3 import os
4 import sys
5 import re
6 import codecs
7 import shutil
8 import unittest
9 import doctest
10 import operator
11 try:
12     from StringIO import StringIO
13 except ImportError:
14     from io import StringIO
15
16 try:
17     import cPickle as pickle
18 except ImportError:
19     import pickle
20
21
22 WITH_CYTHON = True
23
24 from distutils.dist import Distribution
25 from distutils.core import Extension
26 from distutils.command.build_ext import build_ext as _build_ext
27 distutils_distro = Distribution()
28
29 TEST_DIRS = ['compile', 'errors', 'run', 'pyregr']
30 TEST_RUN_DIRS = ['run', 'pyregr']
31
32 # Lists external modules, and a matcher matching tests
33 # which should be excluded if the module is not present.
34 EXT_DEP_MODULES = {
35     'numpy' : re.compile('.*\.numpy_.*').match
36 }
37
38 def get_numpy_include_dirs():
39     import numpy
40     return [numpy.get_include()]
41
42 EXT_DEP_INCLUDES = [
43     # test name matcher , callable returning list
44     (re.compile('numpy_.*').match, get_numpy_include_dirs),
45 ]
46
47 VER_DEP_MODULES = {
48 # such as:
49 #    (2,4) : (operator.le, lambda x: x in ['run.set']),
50     (3,): (operator.ge, lambda x: x in ['run.non_future_division',
51                                         'compile.extsetslice',
52                                         'compile.extdelslice']),
53 }
54
55 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
56 CFLAGS = os.getenv('CFLAGS', '').split()
57
58 class build_ext(_build_ext):
59     def build_extension(self, ext):
60         if ext.language == 'c++':
61             try:
62                 try: # Py2.7+ & Py3.2+ 
63                     compiler_obj = self.compiler_obj
64                 except AttributeError:
65                     compiler_obj = self.compiler
66                 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
67             except Exception:
68                 pass
69         _build_ext.build_extension(self, ext)
70
71 class ErrorWriter(object):
72     match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
73     def __init__(self):
74         self.output = []
75         self.write = self.output.append
76
77     def _collect(self, collect_errors, collect_warnings):
78         s = ''.join(self.output)
79         result = []
80         for line in s.split('\n'):
81             match = self.match_error(line)
82             if match:
83                 is_warning, line, column, message = match.groups()
84                 if (is_warning and collect_warnings) or \
85                         (not is_warning and collect_errors):
86                     result.append( (int(line), int(column), message.strip()) )
87         result.sort()
88         return [ "%d:%d: %s" % values for values in result ]
89
90     def geterrors(self):
91         return self._collect(True, False)
92
93     def getwarnings(self):
94         return self._collect(False, True)
95
96     def getall(self):
97         return self._collect(True, True)
98
99 class TestBuilder(object):
100     def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
101                  cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
102                  languages, test_bugs):
103         self.rootdir = rootdir
104         self.workdir = workdir
105         self.selectors = selectors
106         self.exclude_selectors = exclude_selectors
107         self.annotate = annotate
108         self.cleanup_workdir = cleanup_workdir
109         self.cleanup_sharedlibs = cleanup_sharedlibs
110         self.with_pyregr = with_pyregr
111         self.cython_only = cython_only
112         self.languages = languages
113         self.test_bugs = test_bugs
114
115     def build_suite(self):
116         suite = unittest.TestSuite()
117         test_dirs = TEST_DIRS
118         filenames = os.listdir(self.rootdir)
119         filenames.sort()
120         for filename in filenames:
121             if not WITH_CYTHON and filename == "errors":
122                 # we won't get any errors without running Cython
123                 continue
124             path = os.path.join(self.rootdir, filename)
125             if os.path.isdir(path) and filename in test_dirs:
126                 if filename == 'pyregr' and not self.with_pyregr:
127                     continue
128                 suite.addTest(
129                     self.handle_directory(path, filename))
130         return suite
131
132     def handle_directory(self, path, context):
133         workdir = os.path.join(self.workdir, context)
134         if not os.path.exists(workdir):
135             os.makedirs(workdir)
136
137         expect_errors = (context == 'errors')
138         suite = unittest.TestSuite()
139         filenames = os.listdir(path)
140         filenames.sort()
141         for filename in filenames:
142             if not (filename.endswith(".pyx") or filename.endswith(".py")):
143                 continue
144             if filename.startswith('.'): continue # certain emacs backup files
145             if context == 'pyregr' and not filename.startswith('test_'):
146                 continue
147             module = os.path.splitext(filename)[0]
148             fqmodule = "%s.%s" % (context, module)
149             if not [ 1 for match in self.selectors
150                      if match(fqmodule) ]:
151                 continue
152             if self.exclude_selectors:
153                 if [1 for match in self.exclude_selectors if match(fqmodule)]:
154                     continue
155             if context in TEST_RUN_DIRS:
156                 if module.startswith("test_"):
157                     test_class = CythonUnitTestCase
158                 else:
159                     test_class = CythonRunTestCase
160             else:
161                 test_class = CythonCompileTestCase
162             for test in self.build_tests(test_class, path, workdir,
163                                          module, expect_errors):
164                 suite.addTest(test)
165         return suite
166
167     def build_tests(self, test_class, path, workdir, module, expect_errors):
168         if expect_errors:
169             languages = self.languages[:1]
170         else:
171             languages = self.languages
172         if 'cpp' in module and 'c' in languages:
173             languages = list(languages)
174             languages.remove('c')
175         tests = [ self.build_test(test_class, path, workdir, module,
176                                   language, expect_errors)
177                   for language in languages ]
178         return tests
179
180     def build_test(self, test_class, path, workdir, module,
181                    language, expect_errors):
182         workdir = os.path.join(workdir, language)
183         if not os.path.exists(workdir):
184             os.makedirs(workdir)
185         return test_class(path, workdir, module,
186                           language=language,
187                           expect_errors=expect_errors,
188                           annotate=self.annotate,
189                           cleanup_workdir=self.cleanup_workdir,
190                           cleanup_sharedlibs=self.cleanup_sharedlibs,
191                           cython_only=self.cython_only)
192
193 class CythonCompileTestCase(unittest.TestCase):
194     def __init__(self, directory, workdir, module, language='c',
195                  expect_errors=False, annotate=False, cleanup_workdir=True,
196                  cleanup_sharedlibs=True, cython_only=False):
197         self.directory = directory
198         self.workdir = workdir
199         self.module = module
200         self.language = language
201         self.expect_errors = expect_errors
202         self.annotate = annotate
203         self.cleanup_workdir = cleanup_workdir
204         self.cleanup_sharedlibs = cleanup_sharedlibs
205         self.cython_only = cython_only
206         unittest.TestCase.__init__(self)
207
208     def shortDescription(self):
209         return "compiling (%s) %s" % (self.language, self.module)
210
211     def setUp(self):
212         if self.workdir not in sys.path:
213             sys.path.insert(0, self.workdir)
214
215     def tearDown(self):
216         try:
217             sys.path.remove(self.workdir)
218         except ValueError:
219             pass
220         try:
221             del sys.modules[self.module]
222         except KeyError:
223             pass
224         cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
225         cleanup_lib_files = self.cleanup_sharedlibs
226         if os.path.exists(self.workdir):
227             for rmfile in os.listdir(self.workdir):
228                 if not cleanup_c_files:
229                     if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
230                         continue
231                 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
232                     continue
233                 if self.annotate and rmfile.endswith(".html"):
234                     continue
235                 try:
236                     rmfile = os.path.join(self.workdir, rmfile)
237                     if os.path.isdir(rmfile):
238                         shutil.rmtree(rmfile, ignore_errors=True)
239                     else:
240                         os.remove(rmfile)
241                 except IOError:
242                     pass
243         else:
244             os.makedirs(self.workdir)
245
246     def runTest(self):
247         self.runCompileTest()
248
249     def runCompileTest(self):
250         self.compile(self.directory, self.module, self.workdir,
251                      self.directory, self.expect_errors, self.annotate)
252
253     def find_module_source_file(self, source_file):
254         if not os.path.exists(source_file):
255             source_file = source_file[:-1]
256         return source_file
257
258     def build_target_filename(self, module_name):
259         target = '%s.%s' % (module_name, self.language)
260         return target
261
262     def split_source_and_output(self, directory, module, workdir):
263         source_file = os.path.join(directory, module) + '.pyx'
264         source_and_output = codecs.open(
265             self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
266         out = codecs.open(os.path.join(workdir, module + '.pyx'),
267                           'w', 'ISO-8859-1')
268         for line in source_and_output:
269             last_line = line
270             if line.startswith("_ERRORS"):
271                 out.close()
272                 out = ErrorWriter()
273             else:
274                 out.write(line)
275         try:
276             geterrors = out.geterrors
277         except AttributeError:
278             return []
279         else:
280             return geterrors()
281
282     def run_cython(self, directory, module, targetdir, incdir, annotate):
283         include_dirs = INCLUDE_DIRS[:]
284         if incdir:
285             include_dirs.append(incdir)
286         source = self.find_module_source_file(
287             os.path.join(directory, module + '.pyx'))
288         target = os.path.join(targetdir, self.build_target_filename(module))
289         options = CompilationOptions(
290             pyrex_default_options,
291             include_path = include_dirs,
292             output_file = target,
293             annotate = annotate,
294             use_listing_file = False,
295             cplus = self.language == 'cpp',
296             generate_pxi = False,
297             evaluate_tree_assertions = True,
298             )
299         cython_compile(source, options=options,
300                        full_module_name=module)
301
302     def run_distutils(self, module, workdir, incdir):
303         cwd = os.getcwd()
304         os.chdir(workdir)
305         try:
306             build_extension = build_ext(distutils_distro)
307             build_extension.include_dirs = INCLUDE_DIRS[:]
308             if incdir:
309                 build_extension.include_dirs.append(incdir)
310             build_extension.finalize_options()
311             ext_include_dirs = []
312             for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
313                 if match(module):
314                     ext_include_dirs += get_additional_include_dirs()
315             extension = Extension(
316                 module,
317                 sources = [self.build_target_filename(module)],
318                 include_dirs = ext_include_dirs,
319                 extra_compile_args = CFLAGS,
320                 )
321             if self.language == 'cpp':
322                 extension.language = 'c++'
323             build_extension.extensions = [extension]
324             build_extension.build_temp = workdir
325             build_extension.build_lib  = workdir
326             build_extension.run()
327         finally:
328             os.chdir(cwd)
329
330     def compile(self, directory, module, workdir, incdir,
331                 expect_errors, annotate):
332         expected_errors = errors = ()
333         if expect_errors:
334             expected_errors = self.split_source_and_output(
335                 directory, module, workdir)
336             directory = workdir
337
338         if WITH_CYTHON:
339             old_stderr = sys.stderr
340             try:
341                 sys.stderr = ErrorWriter()
342                 self.run_cython(directory, module, workdir, incdir, annotate)
343                 errors = sys.stderr.geterrors()
344             finally:
345                 sys.stderr = old_stderr
346
347         if errors or expected_errors:
348             try:
349                 for expected, error in zip(expected_errors, errors):
350                     self.assertEquals(expected, error)
351                 if len(errors) < len(expected_errors):
352                     expected_error = expected_errors[len(errors)]
353                     self.assertEquals(expected_error, None)
354                 elif len(errors) > len(expected_errors):
355                     unexpected_error = errors[len(expected_errors)]
356                     self.assertEquals(None, unexpected_error)
357             except AssertionError:
358                 print("\n=== Expected errors: ===")
359                 print('\n'.join(expected_errors))
360                 print("\n\n=== Got errors: ===")
361                 print('\n'.join(errors))
362                 print('\n')
363                 raise
364         else:
365             if not self.cython_only:
366                 self.run_distutils(module, workdir, incdir)
367
368 class CythonRunTestCase(CythonCompileTestCase):
369     def shortDescription(self):
370         return "compiling (%s) and running %s" % (self.language, self.module)
371
372     def run(self, result=None):
373         if result is None:
374             result = self.defaultTestResult()
375         result.startTest(self)
376         try:
377             self.setUp()
378             self.runCompileTest()
379             if not self.cython_only:
380                 self.run_doctests(self.module, result)
381         except Exception:
382             result.addError(self, sys.exc_info())
383             result.stopTest(self)
384         try:
385             self.tearDown()
386         except Exception:
387             pass
388
389     def run_doctests(self, module_name, result):
390         if sys.version_info[0] >= 3 or not hasattr(os, 'fork'):
391             doctest.DocTestSuite(module_name).run(result)
392             return
393
394         # fork to make sure we do not keep the tested module loaded
395         input, output = os.pipe()
396         child_id = os.fork()
397         if not child_id:
398             result_code = 0
399             try:
400                 output = os.fdopen(output, 'wb')
401                 tests = None
402                 try:
403                     partial_result = PartialTestResult(result)
404                     tests = doctest.DocTestSuite(module_name)
405                     tests.run(partial_result)
406                 except Exception:
407                     if tests is None:
408                         # importing failed, try to fake a test class
409                         tests = _FakeClass(
410                             failureException=None,
411                             **{module_name: None})
412                     partial_result.addError(tests, sys.exc_info())
413                     result_code = 1
414                 pickle.dump(partial_result.data(), output)
415             finally:
416                 try: output.close()
417                 except: pass
418                 os._exit(result_code)
419
420         input = os.fdopen(input, 'rb')
421         PartialTestResult.join_results(result, pickle.load(input))
422         cid, result_code = os.waitpid(child_id, 0)
423         if result_code:
424             raise Exception("Tests in module '%s' exited with status %d" %
425                             (module_name, result_code >> 8))
426
427
428 is_private_field = re.compile('^_[^_]').match
429
430 class _FakeClass(object):
431     def __init__(self, **kwargs):
432         self.__dict__.update(kwargs)
433
434 try: # Py2.7+ and Py3.2+
435     from unittest.runner import _TextTestResult
436 except ImportError:
437     from unittest import _TextTestResult
438
439 class PartialTestResult(_TextTestResult):
440     def __init__(self, base_result):
441         _TextTestResult.__init__(
442             self, self._StringIO(), True,
443             base_result.dots + base_result.showAll*2)
444
445     def strip_error_results(self, results):
446         for test_case, error in results:
447             for attr_name in filter(is_private_field, dir(test_case)):
448                 if attr_name == '_dt_test':
449                     test_case._dt_test = _FakeClass(
450                         name=test_case._dt_test.name)
451                 else:
452                     setattr(test_case, attr_name, None)
453
454     def data(self):
455         self.strip_error_results(self.failures)
456         self.strip_error_results(self.errors)
457         return (self.failures, self.errors, self.testsRun,
458                 self.stream.getvalue())
459
460     def join_results(result, data):
461         """Static method for merging the result back into the main
462         result object.
463         """
464         errors, failures, tests_run, output = data
465         if output:
466             result.stream.write(output)
467         result.errors.extend(errors)
468         result.failures.extend(failures)
469         result.testsRun += tests_run
470
471     join_results = staticmethod(join_results)
472
473     class _StringIO(StringIO):
474         def writeln(self, line):
475             self.write("%s\n" % line)
476
477
478 class CythonUnitTestCase(CythonCompileTestCase):
479     def shortDescription(self):
480         return "compiling (%s) tests in %s" % (self.language, self.module)
481
482     def run(self, result=None):
483         if result is None:
484             result = self.defaultTestResult()
485         result.startTest(self)
486         try:
487             self.setUp()
488             self.runCompileTest()
489             unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
490         except Exception:
491             result.addError(self, sys.exc_info())
492             result.stopTest(self)
493         try:
494             self.tearDown()
495         except Exception:
496             pass
497
498 def collect_unittests(path, module_prefix, suite, selectors):
499     def file_matches(filename):
500         return filename.startswith("Test") and filename.endswith(".py")
501
502     def package_matches(dirname):
503         return dirname == "Tests"
504
505     loader = unittest.TestLoader()
506
507     skipped_dirs = []
508
509     for dirpath, dirnames, filenames in os.walk(path):
510         if dirpath != path and "__init__.py" not in filenames:
511             skipped_dirs.append(dirpath + os.path.sep)
512             continue
513         skip = False
514         for dir in skipped_dirs:
515             if dirpath.startswith(dir):
516                 skip = True
517         if skip:
518             continue
519         parentname = os.path.split(dirpath)[-1]
520         if package_matches(parentname):
521             for f in filenames:
522                 if file_matches(f):
523                     filepath = os.path.join(dirpath, f)[:-len(".py")]
524                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
525                     if not [ 1 for match in selectors if match(modulename) ]:
526                         continue
527                     module = __import__(modulename)
528                     for x in modulename.split('.')[1:]:
529                         module = getattr(module, x)
530                     suite.addTests([loader.loadTestsFromModule(module)])
531
532 def collect_doctests(path, module_prefix, suite, selectors):
533     def package_matches(dirname):
534         return dirname not in ("Mac", "Distutils", "Plex")
535     def file_matches(filename):
536         return (filename.endswith(".py") and not ('~' in filename
537                 or '#' in filename or filename.startswith('.')))
538     import doctest, types
539     for dirpath, dirnames, filenames in os.walk(path):
540         parentname = os.path.split(dirpath)[-1]
541         if package_matches(parentname):
542             for f in filenames:
543                 if file_matches(f):
544                     if not f.endswith('.py'): continue
545                     filepath = os.path.join(dirpath, f)[:-len(".py")]
546                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
547                     if not [ 1 for match in selectors if match(modulename) ]:
548                         continue
549                     module = __import__(modulename)
550                     for x in modulename.split('.')[1:]:
551                         module = getattr(module, x)
552                     if hasattr(module, "__doc__") or hasattr(module, "__test__"):
553                         try:
554                             suite.addTest(doctest.DocTestSuite(module))
555                         except ValueError: # no tests
556                             pass
557
558 class MissingDependencyExcluder:
559     def __init__(self, deps):
560         # deps: { module name : matcher func }
561         self.exclude_matchers = []
562         for mod, matcher in deps.items():
563             try:
564                 __import__(mod)
565             except ImportError:
566                 self.exclude_matchers.append(matcher)
567         self.tests_missing_deps = []
568     def __call__(self, testname):
569         for matcher in self.exclude_matchers:
570             if matcher(testname):
571                 self.tests_missing_deps.append(testname)
572                 return True
573         return False
574
575 class VersionDependencyExcluder:
576     def __init__(self, deps):
577         # deps: { version : matcher func }
578         from sys import version_info
579         self.exclude_matchers = []
580         for ver, (compare, matcher) in deps.items():
581             if compare(version_info, ver):
582                 self.exclude_matchers.append(matcher)
583         self.tests_missing_deps = []
584     def __call__(self, testname):
585         for matcher in self.exclude_matchers:
586             if matcher(testname):
587                 self.tests_missing_deps.append(testname)
588                 return True
589         return False
590
591 class FileListExcluder:
592
593     def __init__(self, list_file):
594         self.excludes = {}
595         for line in open(list_file).readlines():
596             line = line.strip()
597             if line and line[0] != '#':
598                 self.excludes[line.split()[0]] = True
599                 
600     def __call__(self, testname):
601         return testname.split('.')[-1] in self.excludes
602
603 if __name__ == '__main__':
604     from optparse import OptionParser
605     parser = OptionParser()
606     parser.add_option("--no-cleanup", dest="cleanup_workdir",
607                       action="store_false", default=True,
608                       help="do not delete the generated C files (allows passing --no-cython on next run)")
609     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
610                       action="store_false", default=True,
611                       help="do not delete the generated shared libary files (allows manual module experimentation)")
612     parser.add_option("--no-cython", dest="with_cython",
613                       action="store_false", default=True,
614                       help="do not run the Cython compiler, only the C compiler")
615     parser.add_option("--no-c", dest="use_c",
616                       action="store_false", default=True,
617                       help="do not test C compilation")
618     parser.add_option("--no-cpp", dest="use_cpp",
619                       action="store_false", default=True,
620                       help="do not test C++ compilation")
621     parser.add_option("--no-unit", dest="unittests",
622                       action="store_false", default=True,
623                       help="do not run the unit tests")
624     parser.add_option("--no-doctest", dest="doctests",
625                       action="store_false", default=True,
626                       help="do not run the doctests")
627     parser.add_option("--no-file", dest="filetests",
628                       action="store_false", default=True,
629                       help="do not run the file based tests")
630     parser.add_option("--no-pyregr", dest="pyregr",
631                       action="store_false", default=True,
632                       help="do not run the regression tests of CPython in tests/pyregr/")    
633     parser.add_option("--cython-only", dest="cython_only",
634                       action="store_true", default=False,
635                       help="only compile pyx to c, do not run C compiler or run the tests")
636     parser.add_option("--no-refnanny", dest="with_refnanny",
637                       action="store_false", default=True,
638                       help="do not regression test reference counting")
639     parser.add_option("--sys-pyregr", dest="system_pyregr",
640                       action="store_true", default=False,
641                       help="run the regression tests of the CPython installation")
642     parser.add_option("-x", "--exclude", dest="exclude",
643                       action="append", metavar="PATTERN",
644                       help="exclude tests matching the PATTERN")
645     parser.add_option("-C", "--coverage", dest="coverage",
646                       action="store_true", default=False,
647                       help="collect source coverage data for the Compiler")
648     parser.add_option("-A", "--annotate", dest="annotate_source",
649                       action="store_true", default=True,
650                       help="generate annotated HTML versions of the test source files")
651     parser.add_option("--no-annotate", dest="annotate_source",
652                       action="store_false",
653                       help="do not generate annotated HTML versions of the test source files")
654     parser.add_option("-v", "--verbose", dest="verbosity",
655                       action="count", default=0,
656                       help="display test progress, pass twice to print test names")
657     parser.add_option("-T", "--ticket", dest="tickets",
658                       action="append",
659                       help="a bug ticket number to run the respective test in 'tests/bugs'")
660
661     options, cmd_args = parser.parse_args()
662
663     DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
664     ROOTDIR = os.path.join(DISTDIR, 'tests')
665     WORKDIR = os.path.join(os.getcwd(), 'BUILD')
666
667     if sys.version_info >= (3,1):
668         options.doctests    = False
669         options.unittests   = False
670         options.pyregr      = False
671         if options.with_cython:
672             # need to convert Cython sources first
673             import lib2to3.refactor
674             from distutils.util import copydir_run_2to3
675             fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
676                        if fix.split('fix_')[-1] not in ('next',)
677                        ]
678             cy3_dir = os.path.join(WORKDIR, 'Cy3')
679             if not os.path.exists(cy3_dir):
680                 os.makedirs(cy3_dir)
681             import distutils.log as dlog
682             dlog.set_threshold(dlog.DEBUG)
683             copydir_run_2to3(DISTDIR, cy3_dir, fixer_names=fixers,
684                              template = '''
685                              global-exclude *
686                              graft Cython
687                              recursive-exclude Cython *
688                              recursive-include Cython *.py *.pyx *.pxd
689                              ''')
690             sys.path.insert(0, cy3_dir)
691     elif sys.version_info[0] >= 3:
692         # make sure we do not import (or run) Cython itself
693         options.with_cython = False
694         options.doctests    = False
695         options.unittests   = False
696         options.pyregr      = False
697
698     if options.coverage:
699         import coverage
700         coverage.erase()
701         coverage.start()
702
703     WITH_CYTHON = options.with_cython
704
705     if WITH_CYTHON:
706         from Cython.Compiler.Main import \
707             CompilationOptions, \
708             default_options as pyrex_default_options, \
709             compile as cython_compile
710         from Cython.Compiler import Errors
711         Errors.LEVEL = 0 # show all warnings
712         from Cython.Compiler import Options
713         Options.generate_cleanup_code = 3   # complete cleanup code
714         from Cython.Compiler import DebugFlags
715         DebugFlags.debug_temp_code_comments = 1
716
717     # RUN ALL TESTS!
718     UNITTEST_MODULE = "Cython"
719     UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
720     if WITH_CYTHON:
721         if os.path.exists(WORKDIR):
722             for path in os.listdir(WORKDIR):
723                 if path in ("support", "Cy3"): continue
724                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
725     if not os.path.exists(WORKDIR):
726         os.makedirs(WORKDIR)
727
728     if WITH_CYTHON:
729         from Cython.Compiler.Version import version
730         sys.stderr.write("Running tests against Cython %s\n" % version)
731     else:
732         sys.stderr.write("Running tests without Cython.\n")
733     sys.stderr.write("Python %s\n" % sys.version)
734     sys.stderr.write("\n")
735
736     if options.with_refnanny:
737         from pyximport.pyxbuild import pyx_to_dll
738         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
739                              build_in_temp=True,
740                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
741         sys.path.insert(0, os.path.split(libpath)[0])
742         CFLAGS.append("-DCYTHON_REFNANNY=1")
743
744     test_bugs = False
745     if options.tickets:
746         for ticket_number in options.tickets:
747             test_bugs = True
748             cmd_args.append('.*T%s$' % ticket_number)
749     if not test_bugs:
750         for selector in cmd_args:
751             if selector.startswith('bugs'):
752                 test_bugs = True
753
754     import re
755     selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
756     if not selectors:
757         selectors = [ lambda x:True ]
758
759     # Chech which external modules are not present and exclude tests
760     # which depends on them (by prefix)
761
762     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES) 
763     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES) 
764     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
765
766     if options.exclude:
767         exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
768     
769     if not test_bugs:
770         exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
771
772     languages = []
773     if options.use_c:
774         languages.append('c')
775     if options.use_cpp:
776         languages.append('cpp')
777
778     test_suite = unittest.TestSuite()
779
780     if options.unittests:
781         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
782
783     if options.doctests:
784         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
785
786     if options.filetests and languages:
787         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
788                                 options.annotate_source, options.cleanup_workdir,
789                                 options.cleanup_sharedlibs, options.pyregr,
790                                 options.cython_only, languages, test_bugs)
791         test_suite.addTest(filetests.build_suite())
792
793     if options.system_pyregr and languages:
794         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
795                                 options.annotate_source, options.cleanup_workdir,
796                                 options.cleanup_sharedlibs, True,
797                                 options.cython_only, languages, test_bugs)
798         test_suite.addTest(
799             filetests.handle_directory(
800                 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
801                 'pyregr'))
802
803     unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
804
805     if options.coverage:
806         coverage.stop()
807         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
808         modules = [ module for name, module in sys.modules.items()
809                     if module is not None and
810                     name.startswith('Cython.Compiler.') and 
811                     name[len('Cython.Compiler.'):] not in ignored_modules ]
812         coverage.report(modules, show_missing=0)
813
814     if missing_dep_excluder.tests_missing_deps:
815         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
816         for test in missing_dep_excluder.tests_missing_deps:
817             sys.stderr.write("   %s\n" % test)
818
819     if options.with_refnanny:
820         import refnanny
821         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))