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