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