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 try: # Py2.7+ & Py3.2+
63 compiler_obj = self.compiler_obj
64 except AttributeError:
65 compiler_obj = self.compiler
66 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
69 _build_ext.build_extension(self, ext)
71 class ErrorWriter(object):
72 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
75 self.write = self.output.append
77 def _collect(self, collect_errors, collect_warnings):
78 s = ''.join(self.output)
80 for line in s.split('\n'):
81 match = self.match_error(line)
83 is_warning, line, column, message = match.groups()
84 if (is_warning and collect_warnings) or \
85 (not is_warning and collect_errors):
86 result.append( (int(line), int(column), message.strip()) )
88 return [ "%d:%d: %s" % values for values in result ]
91 return self._collect(True, False)
93 def getwarnings(self):
94 return self._collect(False, True)
97 return self._collect(True, True)
99 class TestBuilder(object):
100 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
101 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
102 languages, test_bugs):
103 self.rootdir = rootdir
104 self.workdir = workdir
105 self.selectors = selectors
106 self.exclude_selectors = exclude_selectors
107 self.annotate = annotate
108 self.cleanup_workdir = cleanup_workdir
109 self.cleanup_sharedlibs = cleanup_sharedlibs
110 self.with_pyregr = with_pyregr
111 self.cython_only = cython_only
112 self.languages = languages
113 self.test_bugs = test_bugs
115 def build_suite(self):
116 suite = unittest.TestSuite()
117 test_dirs = TEST_DIRS
118 filenames = os.listdir(self.rootdir)
120 for filename in filenames:
121 if not WITH_CYTHON and filename == "errors":
122 # we won't get any errors without running Cython
124 path = os.path.join(self.rootdir, filename)
125 if os.path.isdir(path) and filename in test_dirs:
126 if filename == 'pyregr' and not self.with_pyregr:
129 self.handle_directory(path, filename))
132 def handle_directory(self, path, context):
133 workdir = os.path.join(self.workdir, context)
134 if not os.path.exists(workdir):
137 expect_errors = (context == 'errors')
138 suite = unittest.TestSuite()
139 filenames = os.listdir(path)
141 for filename in filenames:
142 if not (filename.endswith(".pyx") or filename.endswith(".py")):
144 if filename.startswith('.'): continue # certain emacs backup files
145 if context == 'pyregr' and not filename.startswith('test_'):
147 module = os.path.splitext(filename)[0]
148 fqmodule = "%s.%s" % (context, module)
149 if not [ 1 for match in self.selectors
150 if match(fqmodule) ]:
152 if self.exclude_selectors:
153 if [1 for match in self.exclude_selectors if match(fqmodule)]:
155 if context in TEST_RUN_DIRS:
156 if module.startswith("test_"):
157 test_class = CythonUnitTestCase
159 test_class = CythonRunTestCase
161 test_class = CythonCompileTestCase
162 for test in self.build_tests(test_class, path, workdir,
163 module, expect_errors):
167 def build_tests(self, test_class, path, workdir, module, expect_errors):
169 languages = self.languages[:1]
171 languages = self.languages
172 if 'cpp' in module and 'c' in languages:
173 languages = list(languages)
174 languages.remove('c')
175 tests = [ self.build_test(test_class, path, workdir, module,
176 language, expect_errors)
177 for language in languages ]
180 def build_test(self, test_class, path, workdir, module,
181 language, expect_errors):
182 workdir = os.path.join(workdir, language)
183 if not os.path.exists(workdir):
185 return test_class(path, workdir, module,
187 expect_errors=expect_errors,
188 annotate=self.annotate,
189 cleanup_workdir=self.cleanup_workdir,
190 cleanup_sharedlibs=self.cleanup_sharedlibs,
191 cython_only=self.cython_only)
193 class CythonCompileTestCase(unittest.TestCase):
194 def __init__(self, directory, workdir, module, language='c',
195 expect_errors=False, annotate=False, cleanup_workdir=True,
196 cleanup_sharedlibs=True, cython_only=False):
197 self.directory = directory
198 self.workdir = workdir
200 self.language = language
201 self.expect_errors = expect_errors
202 self.annotate = annotate
203 self.cleanup_workdir = cleanup_workdir
204 self.cleanup_sharedlibs = cleanup_sharedlibs
205 self.cython_only = cython_only
206 unittest.TestCase.__init__(self)
208 def shortDescription(self):
209 return "compiling (%s) %s" % (self.language, self.module)
212 if self.workdir not in sys.path:
213 sys.path.insert(0, self.workdir)
217 sys.path.remove(self.workdir)
221 del sys.modules[self.module]
224 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
225 cleanup_lib_files = self.cleanup_sharedlibs
226 if os.path.exists(self.workdir):
227 for rmfile in os.listdir(self.workdir):
228 if not cleanup_c_files:
229 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
231 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
233 if self.annotate and rmfile.endswith(".html"):
236 rmfile = os.path.join(self.workdir, rmfile)
237 if os.path.isdir(rmfile):
238 shutil.rmtree(rmfile, ignore_errors=True)
244 os.makedirs(self.workdir)
247 self.runCompileTest()
249 def runCompileTest(self):
250 self.compile(self.directory, self.module, self.workdir,
251 self.directory, self.expect_errors, self.annotate)
253 def find_module_source_file(self, source_file):
254 if not os.path.exists(source_file):
255 source_file = source_file[:-1]
258 def build_target_filename(self, module_name):
259 target = '%s.%s' % (module_name, self.language)
262 def split_source_and_output(self, directory, module, workdir):
263 source_file = os.path.join(directory, module) + '.pyx'
264 source_and_output = codecs.open(
265 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
266 out = codecs.open(os.path.join(workdir, module + '.pyx'),
268 for line in source_and_output:
270 if line.startswith("_ERRORS"):
276 geterrors = out.geterrors
277 except AttributeError:
282 def run_cython(self, directory, module, targetdir, incdir, annotate):
283 include_dirs = INCLUDE_DIRS[:]
285 include_dirs.append(incdir)
286 source = self.find_module_source_file(
287 os.path.join(directory, module + '.pyx'))
288 target = os.path.join(targetdir, self.build_target_filename(module))
289 options = CompilationOptions(
290 pyrex_default_options,
291 include_path = include_dirs,
292 output_file = target,
294 use_listing_file = False,
295 cplus = self.language == 'cpp',
296 generate_pxi = False,
297 evaluate_tree_assertions = True,
299 cython_compile(source, options=options,
300 full_module_name=module)
302 def run_distutils(self, module, workdir, incdir):
306 build_extension = build_ext(distutils_distro)
307 build_extension.include_dirs = INCLUDE_DIRS[:]
309 build_extension.include_dirs.append(incdir)
310 build_extension.finalize_options()
311 ext_include_dirs = []
312 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
314 ext_include_dirs += get_additional_include_dirs()
315 extension = Extension(
317 sources = [self.build_target_filename(module)],
318 include_dirs = ext_include_dirs,
319 extra_compile_args = CFLAGS,
321 if self.language == 'cpp':
322 extension.language = 'c++'
323 build_extension.extensions = [extension]
324 build_extension.build_temp = workdir
325 build_extension.build_lib = workdir
326 build_extension.run()
330 def compile(self, directory, module, workdir, incdir,
331 expect_errors, annotate):
332 expected_errors = errors = ()
334 expected_errors = self.split_source_and_output(
335 directory, module, workdir)
339 old_stderr = sys.stderr
341 sys.stderr = ErrorWriter()
342 self.run_cython(directory, module, workdir, incdir, annotate)
343 errors = sys.stderr.geterrors()
345 sys.stderr = old_stderr
347 if errors or expected_errors:
349 for expected, error in zip(expected_errors, errors):
350 self.assertEquals(expected, error)
351 if len(errors) < len(expected_errors):
352 expected_error = expected_errors[len(errors)]
353 self.assertEquals(expected_error, None)
354 elif len(errors) > len(expected_errors):
355 unexpected_error = errors[len(expected_errors)]
356 self.assertEquals(None, unexpected_error)
357 except AssertionError:
358 print("\n=== Expected errors: ===")
359 print('\n'.join(expected_errors))
360 print("\n\n=== Got errors: ===")
361 print('\n'.join(errors))
365 if not self.cython_only:
366 self.run_distutils(module, workdir, incdir)
368 class CythonRunTestCase(CythonCompileTestCase):
369 def shortDescription(self):
370 return "compiling (%s) and running %s" % (self.language, self.module)
372 def run(self, result=None):
374 result = self.defaultTestResult()
375 result.startTest(self)
378 self.runCompileTest()
379 if not self.cython_only:
380 self.run_doctests(self.module, result)
382 result.addError(self, sys.exc_info())
383 result.stopTest(self)
389 def run_doctests(self, module_name, result):
390 if sys.version_info[0] >= 3 or not hasattr(os, 'fork'):
391 doctest.DocTestSuite(module_name).run(result)
394 # fork to make sure we do not keep the tested module loaded
395 input, output = os.pipe()
400 output = os.fdopen(output, 'wb')
403 partial_result = PartialTestResult(result)
404 tests = doctest.DocTestSuite(module_name)
405 tests.run(partial_result)
408 # importing failed, try to fake a test class
410 failureException=None,
411 **{module_name: None})
412 partial_result.addError(tests, sys.exc_info())
414 pickle.dump(partial_result.data(), output)
418 os._exit(result_code)
420 input = os.fdopen(input, 'rb')
421 PartialTestResult.join_results(result, pickle.load(input))
422 cid, result_code = os.waitpid(child_id, 0)
424 raise Exception("Tests in module '%s' exited with status %d" %
425 (module_name, result_code >> 8))
428 is_private_field = re.compile('^_[^_]').match
430 class _FakeClass(object):
431 def __init__(self, **kwargs):
432 self.__dict__.update(kwargs)
434 try: # Py2.7+ and Py3.2+
435 from unittest.runner import _TextTestResult
437 from unittest import _TextTestResult
439 class PartialTestResult(_TextTestResult):
440 def __init__(self, base_result):
441 _TextTestResult.__init__(
442 self, self._StringIO(), True,
443 base_result.dots + base_result.showAll*2)
445 def strip_error_results(self, results):
446 for test_case, error in results:
447 for attr_name in filter(is_private_field, dir(test_case)):
448 if attr_name == '_dt_test':
449 test_case._dt_test = _FakeClass(
450 name=test_case._dt_test.name)
452 setattr(test_case, attr_name, None)
455 self.strip_error_results(self.failures)
456 self.strip_error_results(self.errors)
457 return (self.failures, self.errors, self.testsRun,
458 self.stream.getvalue())
460 def join_results(result, data):
461 """Static method for merging the result back into the main
464 errors, failures, tests_run, output = data
466 result.stream.write(output)
467 result.errors.extend(errors)
468 result.failures.extend(failures)
469 result.testsRun += tests_run
471 join_results = staticmethod(join_results)
473 class _StringIO(StringIO):
474 def writeln(self, line):
475 self.write("%s\n" % line)
478 class CythonUnitTestCase(CythonCompileTestCase):
479 def shortDescription(self):
480 return "compiling (%s) tests in %s" % (self.language, self.module)
482 def run(self, result=None):
484 result = self.defaultTestResult()
485 result.startTest(self)
488 self.runCompileTest()
489 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
491 result.addError(self, sys.exc_info())
492 result.stopTest(self)
498 def collect_unittests(path, module_prefix, suite, selectors):
499 def file_matches(filename):
500 return filename.startswith("Test") and filename.endswith(".py")
502 def package_matches(dirname):
503 return dirname == "Tests"
505 loader = unittest.TestLoader()
509 for dirpath, dirnames, filenames in os.walk(path):
510 if dirpath != path and "__init__.py" not in filenames:
511 skipped_dirs.append(dirpath + os.path.sep)
514 for dir in skipped_dirs:
515 if dirpath.startswith(dir):
519 parentname = os.path.split(dirpath)[-1]
520 if package_matches(parentname):
523 filepath = os.path.join(dirpath, f)[:-len(".py")]
524 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
525 if not [ 1 for match in selectors if match(modulename) ]:
527 module = __import__(modulename)
528 for x in modulename.split('.')[1:]:
529 module = getattr(module, x)
530 suite.addTests([loader.loadTestsFromModule(module)])
532 def collect_doctests(path, module_prefix, suite, selectors):
533 def package_matches(dirname):
534 return dirname not in ("Mac", "Distutils", "Plex")
535 def file_matches(filename):
536 return (filename.endswith(".py") and not ('~' in filename
537 or '#' in filename or filename.startswith('.')))
538 import doctest, types
539 for dirpath, dirnames, filenames in os.walk(path):
540 parentname = os.path.split(dirpath)[-1]
541 if package_matches(parentname):
544 if not f.endswith('.py'): continue
545 filepath = os.path.join(dirpath, f)[:-len(".py")]
546 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
547 if not [ 1 for match in selectors if match(modulename) ]:
549 module = __import__(modulename)
550 for x in modulename.split('.')[1:]:
551 module = getattr(module, x)
552 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
554 suite.addTest(doctest.DocTestSuite(module))
555 except ValueError: # no tests
558 class MissingDependencyExcluder:
559 def __init__(self, deps):
560 # deps: { module name : matcher func }
561 self.exclude_matchers = []
562 for mod, matcher in deps.items():
566 self.exclude_matchers.append(matcher)
567 self.tests_missing_deps = []
568 def __call__(self, testname):
569 for matcher in self.exclude_matchers:
570 if matcher(testname):
571 self.tests_missing_deps.append(testname)
575 class VersionDependencyExcluder:
576 def __init__(self, deps):
577 # deps: { version : matcher func }
578 from sys import version_info
579 self.exclude_matchers = []
580 for ver, (compare, matcher) in deps.items():
581 if compare(version_info, ver):
582 self.exclude_matchers.append(matcher)
583 self.tests_missing_deps = []
584 def __call__(self, testname):
585 for matcher in self.exclude_matchers:
586 if matcher(testname):
587 self.tests_missing_deps.append(testname)
591 class FileListExcluder:
593 def __init__(self, list_file):
595 for line in open(list_file).readlines():
597 if line and line[0] != '#':
598 self.excludes[line.split()[0]] = True
600 def __call__(self, testname):
601 return testname.split('.')[-1] in self.excludes
603 if __name__ == '__main__':
604 from optparse import OptionParser
605 parser = OptionParser()
606 parser.add_option("--no-cleanup", dest="cleanup_workdir",
607 action="store_false", default=True,
608 help="do not delete the generated C files (allows passing --no-cython on next run)")
609 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
610 action="store_false", default=True,
611 help="do not delete the generated shared libary files (allows manual module experimentation)")
612 parser.add_option("--no-cython", dest="with_cython",
613 action="store_false", default=True,
614 help="do not run the Cython compiler, only the C compiler")
615 parser.add_option("--no-c", dest="use_c",
616 action="store_false", default=True,
617 help="do not test C compilation")
618 parser.add_option("--no-cpp", dest="use_cpp",
619 action="store_false", default=True,
620 help="do not test C++ compilation")
621 parser.add_option("--no-unit", dest="unittests",
622 action="store_false", default=True,
623 help="do not run the unit tests")
624 parser.add_option("--no-doctest", dest="doctests",
625 action="store_false", default=True,
626 help="do not run the doctests")
627 parser.add_option("--no-file", dest="filetests",
628 action="store_false", default=True,
629 help="do not run the file based tests")
630 parser.add_option("--no-pyregr", dest="pyregr",
631 action="store_false", default=True,
632 help="do not run the regression tests of CPython in tests/pyregr/")
633 parser.add_option("--cython-only", dest="cython_only",
634 action="store_true", default=False,
635 help="only compile pyx to c, do not run C compiler or run the tests")
636 parser.add_option("--no-refnanny", dest="with_refnanny",
637 action="store_false", default=True,
638 help="do not regression test reference counting")
639 parser.add_option("--sys-pyregr", dest="system_pyregr",
640 action="store_true", default=False,
641 help="run the regression tests of the CPython installation")
642 parser.add_option("-x", "--exclude", dest="exclude",
643 action="append", metavar="PATTERN",
644 help="exclude tests matching the PATTERN")
645 parser.add_option("-C", "--coverage", dest="coverage",
646 action="store_true", default=False,
647 help="collect source coverage data for the Compiler")
648 parser.add_option("-A", "--annotate", dest="annotate_source",
649 action="store_true", default=True,
650 help="generate annotated HTML versions of the test source files")
651 parser.add_option("--no-annotate", dest="annotate_source",
652 action="store_false",
653 help="do not generate annotated HTML versions of the test source files")
654 parser.add_option("-v", "--verbose", dest="verbosity",
655 action="count", default=0,
656 help="display test progress, pass twice to print test names")
657 parser.add_option("-T", "--ticket", dest="tickets",
659 help="a bug ticket number to run the respective test in 'tests/bugs'")
661 options, cmd_args = parser.parse_args()
663 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
664 ROOTDIR = os.path.join(DISTDIR, 'tests')
665 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
667 if sys.version_info >= (3,1):
668 options.doctests = False
669 options.unittests = False
670 options.pyregr = False
671 if options.with_cython:
672 # need to convert Cython sources first
673 import lib2to3.refactor
674 from distutils.util import copydir_run_2to3
675 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
676 if fix.split('fix_')[-1] not in ('next',)
678 cy3_dir = os.path.join(WORKDIR, 'Cy3')
679 if not os.path.exists(cy3_dir):
681 import distutils.log as dlog
682 dlog.set_threshold(dlog.DEBUG)
683 copydir_run_2to3(DISTDIR, cy3_dir, fixer_names=fixers,
687 recursive-exclude Cython *
688 recursive-include Cython *.py *.pyx *.pxd
690 sys.path.insert(0, cy3_dir)
691 elif sys.version_info[0] >= 3:
692 # make sure we do not import (or run) Cython itself
693 options.with_cython = False
694 options.doctests = False
695 options.unittests = False
696 options.pyregr = False
703 WITH_CYTHON = options.with_cython
706 from Cython.Compiler.Main import \
707 CompilationOptions, \
708 default_options as pyrex_default_options, \
709 compile as cython_compile
710 from Cython.Compiler import Errors
711 Errors.LEVEL = 0 # show all warnings
712 from Cython.Compiler import Options
713 Options.generate_cleanup_code = 3 # complete cleanup code
714 from Cython.Compiler import DebugFlags
715 DebugFlags.debug_temp_code_comments = 1
718 UNITTEST_MODULE = "Cython"
719 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
721 if os.path.exists(WORKDIR):
722 for path in os.listdir(WORKDIR):
723 if path in ("support", "Cy3"): continue
724 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
725 if not os.path.exists(WORKDIR):
729 from Cython.Compiler.Version import version
730 sys.stderr.write("Running tests against Cython %s\n" % version)
732 sys.stderr.write("Running tests without Cython.\n")
733 sys.stderr.write("Python %s\n" % sys.version)
734 sys.stderr.write("\n")
736 if options.with_refnanny:
737 from pyximport.pyxbuild import pyx_to_dll
738 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
740 pyxbuild_dir=os.path.join(WORKDIR, "support"))
741 sys.path.insert(0, os.path.split(libpath)[0])
742 CFLAGS.append("-DCYTHON_REFNANNY=1")
746 for ticket_number in options.tickets:
748 cmd_args.append('.*T%s$' % ticket_number)
750 for selector in cmd_args:
751 if selector.startswith('bugs'):
755 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
757 selectors = [ lambda x:True ]
759 # Chech which external modules are not present and exclude tests
760 # which depends on them (by prefix)
762 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
763 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
764 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
767 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
770 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
774 languages.append('c')
776 languages.append('cpp')
778 test_suite = unittest.TestSuite()
780 if options.unittests:
781 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
784 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
786 if options.filetests and languages:
787 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
788 options.annotate_source, options.cleanup_workdir,
789 options.cleanup_sharedlibs, options.pyregr,
790 options.cython_only, languages, test_bugs)
791 test_suite.addTest(filetests.build_suite())
793 if options.system_pyregr and languages:
794 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
795 options.annotate_source, options.cleanup_workdir,
796 options.cleanup_sharedlibs, True,
797 options.cython_only, languages, test_bugs)
799 filetests.handle_directory(
800 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
803 unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
807 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
808 modules = [ module for name, module in sys.modules.items()
809 if module is not None and
810 name.startswith('Cython.Compiler.') and
811 name[len('Cython.Compiler.'):] not in ignored_modules ]
812 coverage.report(modules, show_missing=0)
814 if missing_dep_excluder.tests_missing_deps:
815 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
816 for test in missing_dep_excluder.tests_missing_deps:
817 sys.stderr.write(" %s\n" % test)
819 if options.with_refnanny:
821 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))