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