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