12 from StringIO import StringIO
14 from io import StringIO
17 import cPickle as pickle
24 from distutils.dist import Distribution
25 from distutils.core import Extension
26 from distutils.command.build_ext import build_ext as _build_ext
27 distutils_distro = Distribution()
29 TEST_DIRS = ['compile', 'errors', 'run', 'pyregr']
30 TEST_RUN_DIRS = ['run', 'pyregr']
32 # Lists external modules, and a matcher matching tests
33 # which should be excluded if the module is not present.
35 'numpy' : re.compile('.*\.numpy_.*').match
38 def get_numpy_include_dirs():
40 return [numpy.get_include()]
43 # test name matcher , callable returning list
44 (re.compile('numpy_.*').match, get_numpy_include_dirs),
49 # (2,4) : (operator.le, lambda x: x in ['run.set']),
50 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
51 'compile.extsetslice',
52 'compile.extdelslice']),
55 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
56 CFLAGS = os.getenv('CFLAGS', '').split()
58 class build_ext(_build_ext):
59 def build_extension(self, ext):
60 if ext.language == 'c++':
62 self.compiler.compiler_so.remove('-Wstrict-prototypes')
65 _build_ext.build_extension(self, ext)
67 class ErrorWriter(object):
68 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
71 self.write = self.output.append
73 def _collect(self, collect_errors, collect_warnings):
74 s = ''.join(self.output)
76 for line in s.split('\n'):
77 match = self.match_error(line)
79 is_warning, line, column, message = match.groups()
80 if (is_warning and collect_warnings) or \
81 (not is_warning and collect_errors):
82 result.append( (int(line), int(column), message.strip()) )
84 return [ "%d:%d: %s" % values for values in result ]
87 return self._collect(True, False)
89 def getwarnings(self):
90 return self._collect(False, True)
93 return self._collect(True, True)
95 class TestBuilder(object):
96 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
97 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
98 languages, test_bugs):
99 self.rootdir = rootdir
100 self.workdir = workdir
101 self.selectors = selectors
102 self.exclude_selectors = exclude_selectors
103 self.annotate = annotate
104 self.cleanup_workdir = cleanup_workdir
105 self.cleanup_sharedlibs = cleanup_sharedlibs
106 self.with_pyregr = with_pyregr
107 self.cython_only = cython_only
108 self.languages = languages
109 self.test_bugs = test_bugs
111 def build_suite(self):
112 suite = unittest.TestSuite()
113 test_dirs = TEST_DIRS
114 filenames = os.listdir(self.rootdir)
116 for filename in filenames:
117 if not WITH_CYTHON and filename == "errors":
118 # we won't get any errors without running Cython
120 path = os.path.join(self.rootdir, filename)
121 if os.path.isdir(path) and filename in test_dirs:
122 if filename == 'pyregr' and not self.with_pyregr:
125 self.handle_directory(path, filename))
128 def handle_directory(self, path, context):
129 workdir = os.path.join(self.workdir, context)
130 if not os.path.exists(workdir):
133 expect_errors = (context == 'errors')
134 suite = unittest.TestSuite()
135 filenames = os.listdir(path)
137 for filename in filenames:
138 if not (filename.endswith(".pyx") or filename.endswith(".py")):
140 if filename.startswith('.'): continue # certain emacs backup files
141 if context == 'pyregr' and not filename.startswith('test_'):
143 module = os.path.splitext(filename)[0]
144 fqmodule = "%s.%s" % (context, module)
145 if not [ 1 for match in self.selectors
146 if match(fqmodule) ]:
148 if self.exclude_selectors:
149 if [1 for match in self.exclude_selectors if match(fqmodule)]:
151 if context in TEST_RUN_DIRS:
152 if module.startswith("test_"):
153 test_class = CythonUnitTestCase
155 test_class = CythonRunTestCase
157 test_class = CythonCompileTestCase
158 for test in self.build_tests(test_class, path, workdir,
159 module, expect_errors):
163 def build_tests(self, test_class, path, workdir, module, expect_errors):
165 languages = self.languages[:1]
167 languages = self.languages
168 if 'cpp' in module and 'c' in languages:
169 languages = list(languages)
170 languages.remove('c')
171 tests = [ self.build_test(test_class, path, workdir, module,
172 language, expect_errors)
173 for language in languages ]
176 def build_test(self, test_class, path, workdir, module,
177 language, expect_errors):
178 workdir = os.path.join(workdir, language)
179 if not os.path.exists(workdir):
181 return test_class(path, workdir, module,
183 expect_errors=expect_errors,
184 annotate=self.annotate,
185 cleanup_workdir=self.cleanup_workdir,
186 cleanup_sharedlibs=self.cleanup_sharedlibs,
187 cython_only=self.cython_only)
189 class CythonCompileTestCase(unittest.TestCase):
190 def __init__(self, directory, workdir, module, language='c',
191 expect_errors=False, annotate=False, cleanup_workdir=True,
192 cleanup_sharedlibs=True, cython_only=False):
193 self.directory = directory
194 self.workdir = workdir
196 self.language = language
197 self.expect_errors = expect_errors
198 self.annotate = annotate
199 self.cleanup_workdir = cleanup_workdir
200 self.cleanup_sharedlibs = cleanup_sharedlibs
201 self.cython_only = cython_only
202 unittest.TestCase.__init__(self)
204 def shortDescription(self):
205 return "compiling (%s) %s" % (self.language, self.module)
208 if self.workdir not in sys.path:
209 sys.path.insert(0, self.workdir)
213 sys.path.remove(self.workdir)
217 del sys.modules[self.module]
220 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
221 cleanup_lib_files = self.cleanup_sharedlibs
222 if os.path.exists(self.workdir):
223 for rmfile in os.listdir(self.workdir):
224 if not cleanup_c_files:
225 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
227 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
229 if self.annotate and rmfile.endswith(".html"):
232 rmfile = os.path.join(self.workdir, rmfile)
233 if os.path.isdir(rmfile):
234 shutil.rmtree(rmfile, ignore_errors=True)
240 os.makedirs(self.workdir)
243 self.runCompileTest()
245 def runCompileTest(self):
246 self.compile(self.directory, self.module, self.workdir,
247 self.directory, self.expect_errors, self.annotate)
249 def find_module_source_file(self, source_file):
250 if not os.path.exists(source_file):
251 source_file = source_file[:-1]
254 def build_target_filename(self, module_name):
255 target = '%s.%s' % (module_name, self.language)
258 def split_source_and_output(self, directory, module, workdir):
259 source_file = os.path.join(directory, module) + '.pyx'
260 source_and_output = codecs.open(
261 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
262 out = codecs.open(os.path.join(workdir, module + '.pyx'),
264 for line in source_and_output:
266 if line.startswith("_ERRORS"):
272 geterrors = out.geterrors
273 except AttributeError:
278 def run_cython(self, directory, module, targetdir, incdir, annotate):
279 include_dirs = INCLUDE_DIRS[:]
281 include_dirs.append(incdir)
282 source = self.find_module_source_file(
283 os.path.join(directory, module + '.pyx'))
284 target = os.path.join(targetdir, self.build_target_filename(module))
285 options = CompilationOptions(
286 pyrex_default_options,
287 include_path = include_dirs,
288 output_file = target,
290 use_listing_file = False,
291 cplus = self.language == 'cpp',
292 generate_pxi = False,
293 evaluate_tree_assertions = True,
295 cython_compile(source, options=options,
296 full_module_name=module)
298 def run_distutils(self, module, workdir, incdir):
302 build_extension = build_ext(distutils_distro)
303 build_extension.include_dirs = INCLUDE_DIRS[:]
305 build_extension.include_dirs.append(incdir)
306 build_extension.finalize_options()
307 ext_include_dirs = []
308 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
310 ext_include_dirs += get_additional_include_dirs()
311 extension = Extension(
313 sources = [self.build_target_filename(module)],
314 include_dirs = ext_include_dirs,
315 extra_compile_args = CFLAGS,
317 if self.language == 'cpp':
318 extension.language = 'c++'
319 build_extension.extensions = [extension]
320 build_extension.build_temp = workdir
321 build_extension.build_lib = workdir
322 build_extension.run()
326 def compile(self, directory, module, workdir, incdir,
327 expect_errors, annotate):
328 expected_errors = errors = ()
330 expected_errors = self.split_source_and_output(
331 directory, module, workdir)
335 old_stderr = sys.stderr
337 sys.stderr = ErrorWriter()
338 self.run_cython(directory, module, workdir, incdir, annotate)
339 errors = sys.stderr.geterrors()
341 sys.stderr = old_stderr
343 if errors or expected_errors:
345 for expected, error in zip(expected_errors, errors):
346 self.assertEquals(expected, error)
347 if len(errors) < len(expected_errors):
348 expected_error = expected_errors[len(errors)]
349 self.assertEquals(expected_error, None)
350 elif len(errors) > len(expected_errors):
351 unexpected_error = errors[len(expected_errors)]
352 self.assertEquals(None, unexpected_error)
353 except AssertionError:
354 print("\n=== Expected errors: ===")
355 print('\n'.join(expected_errors))
356 print("\n\n=== Got errors: ===")
357 print('\n'.join(errors))
361 if not self.cython_only:
362 self.run_distutils(module, workdir, incdir)
364 class CythonRunTestCase(CythonCompileTestCase):
365 def shortDescription(self):
366 return "compiling (%s) and running %s" % (self.language, self.module)
368 def run(self, result=None):
370 result = self.defaultTestResult()
371 result.startTest(self)
374 self.runCompileTest()
375 if not self.cython_only:
376 self.run_doctests(self.module, result)
378 result.addError(self, sys.exc_info())
379 result.stopTest(self)
385 def run_doctests(self, module_name, result):
386 if sys.version_info[0] >= 3 or not hasattr(os, 'fork'):
387 doctest.DocTestSuite(module_name).run(result)
390 # fork to make sure we do not keep the tested module loaded
391 input, output = os.pipe()
396 output = os.fdopen(output, 'wb')
399 partial_result = PartialTestResult(result)
400 tests = doctest.DocTestSuite(module_name)
401 tests.run(partial_result)
404 # importing failed, try to fake a test class
406 failureException=None,
407 **{module_name: None})
408 partial_result.addError(tests, sys.exc_info())
410 pickle.dump(partial_result.data(), output)
414 os._exit(result_code)
416 input = os.fdopen(input, 'rb')
417 PartialTestResult.join_results(result, pickle.load(input))
418 cid, result_code = os.waitpid(child_id, 0)
420 raise Exception("Tests in module '%s' exited with status %d" %
421 (module_name, result_code >> 8))
424 is_private_field = re.compile('^_[^_]').match
426 class _FakeClass(object):
427 def __init__(self, **kwargs):
428 self.__dict__.update(kwargs)
430 try: # Py2.7+ and Py3.2+
431 from unittest.runner import _TextTestResult
433 from unittest import _TextTestResult
435 class PartialTestResult(_TextTestResult):
436 def __init__(self, base_result):
437 _TextTestResult.__init__(
438 self, self._StringIO(), True,
439 base_result.dots + base_result.showAll*2)
441 def strip_error_results(self, results):
442 for test_case, error in results:
443 for attr_name in filter(is_private_field, dir(test_case)):
444 if attr_name == '_dt_test':
445 test_case._dt_test = _FakeClass(
446 name=test_case._dt_test.name)
448 setattr(test_case, attr_name, None)
451 self.strip_error_results(self.failures)
452 self.strip_error_results(self.errors)
453 return (self.failures, self.errors, self.testsRun,
454 self.stream.getvalue())
456 def join_results(result, data):
457 """Static method for merging the result back into the main
460 errors, failures, tests_run, output = data
462 result.stream.write(output)
463 result.errors.extend(errors)
464 result.failures.extend(failures)
465 result.testsRun += tests_run
467 join_results = staticmethod(join_results)
469 class _StringIO(StringIO):
470 def writeln(self, line):
471 self.write("%s\n" % line)
474 class CythonUnitTestCase(CythonCompileTestCase):
475 def shortDescription(self):
476 return "compiling (%s) tests in %s" % (self.language, self.module)
478 def run(self, result=None):
480 result = self.defaultTestResult()
481 result.startTest(self)
484 self.runCompileTest()
485 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
487 result.addError(self, sys.exc_info())
488 result.stopTest(self)
494 def collect_unittests(path, module_prefix, suite, selectors):
495 def file_matches(filename):
496 return filename.startswith("Test") and filename.endswith(".py")
498 def package_matches(dirname):
499 return dirname == "Tests"
501 loader = unittest.TestLoader()
505 for dirpath, dirnames, filenames in os.walk(path):
506 if dirpath != path and "__init__.py" not in filenames:
507 skipped_dirs.append(dirpath + os.path.sep)
510 for dir in skipped_dirs:
511 if dirpath.startswith(dir):
515 parentname = os.path.split(dirpath)[-1]
516 if package_matches(parentname):
519 filepath = os.path.join(dirpath, f)[:-len(".py")]
520 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
521 if not [ 1 for match in selectors if match(modulename) ]:
523 module = __import__(modulename)
524 for x in modulename.split('.')[1:]:
525 module = getattr(module, x)
526 suite.addTests([loader.loadTestsFromModule(module)])
528 def collect_doctests(path, module_prefix, suite, selectors):
529 def package_matches(dirname):
530 return dirname not in ("Mac", "Distutils", "Plex")
531 def file_matches(filename):
532 return (filename.endswith(".py") and not ('~' in filename
533 or '#' in filename or filename.startswith('.')))
534 import doctest, types
535 for dirpath, dirnames, filenames in os.walk(path):
536 parentname = os.path.split(dirpath)[-1]
537 if package_matches(parentname):
540 if not f.endswith('.py'): continue
541 filepath = os.path.join(dirpath, f)[:-len(".py")]
542 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
543 if not [ 1 for match in selectors if match(modulename) ]:
545 module = __import__(modulename)
546 for x in modulename.split('.')[1:]:
547 module = getattr(module, x)
548 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
550 suite.addTest(doctest.DocTestSuite(module))
551 except ValueError: # no tests
554 class MissingDependencyExcluder:
555 def __init__(self, deps):
556 # deps: { module name : matcher func }
557 self.exclude_matchers = []
558 for mod, matcher in deps.items():
562 self.exclude_matchers.append(matcher)
563 self.tests_missing_deps = []
564 def __call__(self, testname):
565 for matcher in self.exclude_matchers:
566 if matcher(testname):
567 self.tests_missing_deps.append(testname)
571 class VersionDependencyExcluder:
572 def __init__(self, deps):
573 # deps: { version : matcher func }
574 from sys import version_info
575 self.exclude_matchers = []
576 for ver, (compare, matcher) in deps.items():
577 if compare(version_info, ver):
578 self.exclude_matchers.append(matcher)
579 self.tests_missing_deps = []
580 def __call__(self, testname):
581 for matcher in self.exclude_matchers:
582 if matcher(testname):
583 self.tests_missing_deps.append(testname)
587 class FileListExcluder:
589 def __init__(self, list_file):
591 for line in open(list_file).readlines():
593 if line and line[0] != '#':
594 self.excludes[line.split()[0]] = True
596 def __call__(self, testname):
597 return testname.split('.')[-1] in self.excludes
599 if __name__ == '__main__':
600 from optparse import OptionParser
601 parser = OptionParser()
602 parser.add_option("--no-cleanup", dest="cleanup_workdir",
603 action="store_false", default=True,
604 help="do not delete the generated C files (allows passing --no-cython on next run)")
605 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
606 action="store_false", default=True,
607 help="do not delete the generated shared libary files (allows manual module experimentation)")
608 parser.add_option("--no-cython", dest="with_cython",
609 action="store_false", default=True,
610 help="do not run the Cython compiler, only the C compiler")
611 parser.add_option("--no-c", dest="use_c",
612 action="store_false", default=True,
613 help="do not test C compilation")
614 parser.add_option("--no-cpp", dest="use_cpp",
615 action="store_false", default=True,
616 help="do not test C++ compilation")
617 parser.add_option("--no-unit", dest="unittests",
618 action="store_false", default=True,
619 help="do not run the unit tests")
620 parser.add_option("--no-doctest", dest="doctests",
621 action="store_false", default=True,
622 help="do not run the doctests")
623 parser.add_option("--no-file", dest="filetests",
624 action="store_false", default=True,
625 help="do not run the file based tests")
626 parser.add_option("--no-pyregr", dest="pyregr",
627 action="store_false", default=True,
628 help="do not run the regression tests of CPython in tests/pyregr/")
629 parser.add_option("--cython-only", dest="cython_only",
630 action="store_true", default=False,
631 help="only compile pyx to c, do not run C compiler or run the tests")
632 parser.add_option("--no-refnanny", dest="with_refnanny",
633 action="store_false", default=True,
634 help="do not regression test reference counting")
635 parser.add_option("--sys-pyregr", dest="system_pyregr",
636 action="store_true", default=False,
637 help="run the regression tests of the CPython installation")
638 parser.add_option("-x", "--exclude", dest="exclude",
639 action="append", metavar="PATTERN",
640 help="exclude tests matching the PATTERN")
641 parser.add_option("-C", "--coverage", dest="coverage",
642 action="store_true", default=False,
643 help="collect source coverage data for the Compiler")
644 parser.add_option("-A", "--annotate", dest="annotate_source",
645 action="store_true", default=True,
646 help="generate annotated HTML versions of the test source files")
647 parser.add_option("--no-annotate", dest="annotate_source",
648 action="store_false",
649 help="do not generate annotated HTML versions of the test source files")
650 parser.add_option("-v", "--verbose", dest="verbosity",
651 action="count", default=0,
652 help="display test progress, pass twice to print test names")
653 parser.add_option("-T", "--ticket", dest="tickets",
655 help="a bug ticket number to run the respective test in 'tests/bugs'")
657 options, cmd_args = parser.parse_args()
659 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
660 ROOTDIR = os.path.join(DISTDIR, 'tests')
661 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
663 if sys.version_info >= (3,1):
664 options.doctests = False
665 options.unittests = False
666 options.pyregr = False
667 if options.with_cython:
668 # need to convert Cython sources first
669 import lib2to3.refactor
670 from distutils.util import copydir_run_2to3
671 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
672 if fix.split('fix_')[-1] not in ('next',)
674 cy3_dir = os.path.join(WORKDIR, 'Cy3')
675 if not os.path.exists(cy3_dir):
677 import distutils.log as dlog
678 dlog.set_threshold(dlog.DEBUG)
679 copydir_run_2to3(DISTDIR, cy3_dir, fixer_names=fixers,
683 recursive-exclude Cython *
684 recursive-include Cython *.py *.pyx *.pxd
686 sys.path.insert(0, cy3_dir)
687 elif sys.version_info[0] >= 3:
688 # make sure we do not import (or run) Cython itself
689 options.with_cython = False
690 options.doctests = False
691 options.unittests = False
692 options.pyregr = False
699 WITH_CYTHON = options.with_cython
702 from Cython.Compiler.Main import \
703 CompilationOptions, \
704 default_options as pyrex_default_options, \
705 compile as cython_compile
706 from Cython.Compiler import Errors
707 Errors.LEVEL = 0 # show all warnings
708 from Cython.Compiler import Options
709 Options.generate_cleanup_code = 3 # complete cleanup code
710 from Cython.Compiler import DebugFlags
711 DebugFlags.debug_temp_code_comments = 1
714 UNITTEST_MODULE = "Cython"
715 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
717 if os.path.exists(WORKDIR):
718 for path in os.listdir(WORKDIR):
719 if path in ("support", "Cy3"): continue
720 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
721 if not os.path.exists(WORKDIR):
725 from Cython.Compiler.Version import version
726 sys.stderr.write("Running tests against Cython %s\n" % version)
728 sys.stderr.write("Running tests without Cython.\n")
729 sys.stderr.write("Python %s\n" % sys.version)
730 sys.stderr.write("\n")
732 if options.with_refnanny:
733 from pyximport.pyxbuild import pyx_to_dll
734 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
736 pyxbuild_dir=os.path.join(WORKDIR, "support"))
737 sys.path.insert(0, os.path.split(libpath)[0])
738 CFLAGS.append("-DCYTHON_REFNANNY=1")
742 for ticket_number in options.tickets:
744 cmd_args.append('.*T%s$' % ticket_number)
746 for selector in cmd_args:
747 if selector.startswith('bugs'):
751 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
753 selectors = [ lambda x:True ]
755 # Chech which external modules are not present and exclude tests
756 # which depends on them (by prefix)
758 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
759 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
760 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
763 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
766 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
770 languages.append('c')
772 languages.append('cpp')
774 test_suite = unittest.TestSuite()
776 if options.unittests:
777 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
780 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
782 if options.filetests and languages:
783 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
784 options.annotate_source, options.cleanup_workdir,
785 options.cleanup_sharedlibs, options.pyregr,
786 options.cython_only, languages, test_bugs)
787 test_suite.addTest(filetests.build_suite())
789 if options.system_pyregr and languages:
790 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
791 options.annotate_source, options.cleanup_workdir,
792 options.cleanup_sharedlibs, True,
793 options.cython_only, languages, test_bugs)
795 filetests.handle_directory(
796 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
799 unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
803 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
804 modules = [ module for name, module in sys.modules.items()
805 if module is not None and
806 name.startswith('Cython.Compiler.') and
807 name[len('Cython.Compiler.'):] not in ignored_modules ]
808 coverage.report(modules, show_missing=0)
810 if missing_dep_excluder.tests_missing_deps:
811 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
812 for test in missing_dep_excluder.tests_missing_deps:
813 sys.stderr.write(" %s\n" % test)
815 if options.with_refnanny:
817 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))