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