14 from distutils.dist import Distribution
15 from distutils.core import Extension
16 from distutils.command.build_ext import build_ext as _build_ext
17 distutils_distro = Distribution()
19 TEST_DIRS = ['compile', 'errors', 'run', 'pyregr']
20 TEST_RUN_DIRS = ['run', 'pyregr']
22 # Lists external modules, and a matcher matching tests
23 # which should be excluded if the module is not present.
25 'numpy' : re.compile('.*\.numpy_.*').match
28 def get_numpy_include_dirs():
30 return [numpy.get_include()]
33 # test name matcher , callable returning list
34 (re.compile('numpy_.*').match, get_numpy_include_dirs),
39 # (2,4) : (operator.le, lambda x: x in ['run.set']),
40 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
41 'compile.extsetslice',
42 'compile.extdelslice']),
45 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
46 CFLAGS = os.getenv('CFLAGS', '').split()
48 class build_ext(_build_ext):
49 def build_extension(self, ext):
50 if ext.language == 'c++':
52 self.compiler.compiler_so.remove('-Wstrict-prototypes')
55 _build_ext.build_extension(self, ext)
57 class ErrorWriter(object):
58 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
61 self.write = self.output.append
63 def _collect(self, collect_errors, collect_warnings):
64 s = ''.join(self.output)
66 for line in s.split('\n'):
67 match = self.match_error(line)
69 is_warning, line, column, message = match.groups()
70 if (is_warning and collect_warnings) or \
71 (not is_warning and collect_errors):
72 result.append( (int(line), int(column), message.strip()) )
74 return [ "%d:%d: %s" % values for values in result ]
77 return self._collect(True, False)
79 def getwarnings(self):
80 return self._collect(False, True)
83 return self._collect(True, True)
85 class TestBuilder(object):
86 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
87 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
88 languages, test_bugs):
89 self.rootdir = rootdir
90 self.workdir = workdir
91 self.selectors = selectors
92 self.exclude_selectors = exclude_selectors
93 self.annotate = annotate
94 self.cleanup_workdir = cleanup_workdir
95 self.cleanup_sharedlibs = cleanup_sharedlibs
96 self.with_pyregr = with_pyregr
97 self.cython_only = cython_only
98 self.languages = languages
99 self.test_bugs = test_bugs
101 def build_suite(self):
102 suite = unittest.TestSuite()
103 test_dirs = TEST_DIRS
104 filenames = os.listdir(self.rootdir)
106 for filename in filenames:
107 if not WITH_CYTHON and filename == "errors":
108 # we won't get any errors without running Cython
110 path = os.path.join(self.rootdir, filename)
111 if os.path.isdir(path) and filename in test_dirs:
112 if filename == 'pyregr' and not self.with_pyregr:
115 self.handle_directory(path, filename))
118 def handle_directory(self, path, context):
119 workdir = os.path.join(self.workdir, context)
120 if not os.path.exists(workdir):
123 expect_errors = (context == 'errors')
124 suite = unittest.TestSuite()
125 filenames = os.listdir(path)
127 for filename in filenames:
128 if not (filename.endswith(".pyx") or filename.endswith(".py")):
130 if filename.startswith('.'): continue # certain emacs backup files
131 if context == 'pyregr' and not filename.startswith('test_'):
133 module = os.path.splitext(filename)[0]
134 fqmodule = "%s.%s" % (context, module)
135 if not [ 1 for match in self.selectors
136 if match(fqmodule) ]:
138 if self.exclude_selectors:
139 if [1 for match in self.exclude_selectors if match(fqmodule)]:
141 if context in TEST_RUN_DIRS:
142 if module.startswith("test_"):
143 test_class = CythonUnitTestCase
145 test_class = CythonRunTestCase
147 test_class = CythonCompileTestCase
148 for test in self.build_tests(test_class, path, workdir,
149 module, expect_errors):
153 def build_tests(self, test_class, path, workdir, module, expect_errors):
155 languages = self.languages[:1]
157 languages = self.languages
158 if 'cpp' in module and 'c' in languages:
159 languages = list(languages)
160 languages.remove('c')
161 tests = [ self.build_test(test_class, path, workdir, module,
162 language, expect_errors)
163 for language in languages ]
166 def build_test(self, test_class, path, workdir, module,
167 language, expect_errors):
168 workdir = os.path.join(workdir, language)
169 if not os.path.exists(workdir):
171 return test_class(path, workdir, module,
173 expect_errors=expect_errors,
174 annotate=self.annotate,
175 cleanup_workdir=self.cleanup_workdir,
176 cleanup_sharedlibs=self.cleanup_sharedlibs,
177 cython_only=self.cython_only)
179 class CythonCompileTestCase(unittest.TestCase):
180 def __init__(self, directory, workdir, module, language='c',
181 expect_errors=False, annotate=False, cleanup_workdir=True,
182 cleanup_sharedlibs=True, cython_only=False):
183 self.directory = directory
184 self.workdir = workdir
186 self.language = language
187 self.expect_errors = expect_errors
188 self.annotate = annotate
189 self.cleanup_workdir = cleanup_workdir
190 self.cleanup_sharedlibs = cleanup_sharedlibs
191 self.cython_only = cython_only
192 unittest.TestCase.__init__(self)
194 def shortDescription(self):
195 return "compiling (%s) %s" % (self.language, self.module)
198 if self.workdir not in sys.path:
199 sys.path.insert(0, self.workdir)
203 sys.path.remove(self.workdir)
207 del sys.modules[self.module]
210 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
211 cleanup_lib_files = self.cleanup_sharedlibs
212 if os.path.exists(self.workdir):
213 for rmfile in os.listdir(self.workdir):
214 if not cleanup_c_files:
215 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
217 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
219 if self.annotate and rmfile.endswith(".html"):
222 rmfile = os.path.join(self.workdir, rmfile)
223 if os.path.isdir(rmfile):
224 shutil.rmtree(rmfile, ignore_errors=True)
230 os.makedirs(self.workdir)
233 self.runCompileTest()
235 def runCompileTest(self):
236 self.compile(self.directory, self.module, self.workdir,
237 self.directory, self.expect_errors, self.annotate)
239 def find_module_source_file(self, source_file):
240 if not os.path.exists(source_file):
241 source_file = source_file[:-1]
244 def build_target_filename(self, module_name):
245 target = '%s.%s' % (module_name, self.language)
248 def split_source_and_output(self, directory, module, workdir):
249 source_file = os.path.join(directory, module) + '.pyx'
250 source_and_output = codecs.open(
251 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
252 out = codecs.open(os.path.join(workdir, module + '.pyx'),
254 for line in source_and_output:
256 if line.startswith("_ERRORS"):
262 geterrors = out.geterrors
263 except AttributeError:
268 def run_cython(self, directory, module, targetdir, incdir, annotate):
269 include_dirs = INCLUDE_DIRS[:]
271 include_dirs.append(incdir)
272 source = self.find_module_source_file(
273 os.path.join(directory, module + '.pyx'))
274 target = os.path.join(targetdir, self.build_target_filename(module))
275 options = CompilationOptions(
276 pyrex_default_options,
277 include_path = include_dirs,
278 output_file = target,
280 use_listing_file = False,
281 cplus = self.language == 'cpp',
282 generate_pxi = False,
283 evaluate_tree_assertions = True,
285 cython_compile(source, options=options,
286 full_module_name=module)
288 def run_distutils(self, module, workdir, incdir):
292 build_extension = build_ext(distutils_distro)
293 build_extension.include_dirs = INCLUDE_DIRS[:]
295 build_extension.include_dirs.append(incdir)
296 build_extension.finalize_options()
297 ext_include_dirs = []
298 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
300 ext_include_dirs += get_additional_include_dirs()
301 extension = Extension(
303 sources = [self.build_target_filename(module)],
304 include_dirs = ext_include_dirs,
305 extra_compile_args = CFLAGS,
307 if self.language == 'cpp':
308 extension.language = 'c++'
309 build_extension.extensions = [extension]
310 build_extension.build_temp = workdir
311 build_extension.build_lib = workdir
312 build_extension.run()
316 def compile(self, directory, module, workdir, incdir,
317 expect_errors, annotate):
318 expected_errors = errors = ()
320 expected_errors = self.split_source_and_output(
321 directory, module, workdir)
325 old_stderr = sys.stderr
327 sys.stderr = ErrorWriter()
328 self.run_cython(directory, module, workdir, incdir, annotate)
329 errors = sys.stderr.geterrors()
331 sys.stderr = old_stderr
333 if errors or expected_errors:
335 for expected, error in zip(expected_errors, errors):
336 self.assertEquals(expected, error)
337 if len(errors) < len(expected_errors):
338 expected_error = expected_errors[len(errors)]
339 self.assertEquals(expected_error, None)
340 elif len(errors) > len(expected_errors):
341 unexpected_error = errors[len(expected_errors)]
342 self.assertEquals(None, unexpected_error)
343 except AssertionError:
344 print("\n=== Expected errors: ===")
345 print('\n'.join(expected_errors))
346 print("\n\n=== Got errors: ===")
347 print('\n'.join(errors))
351 if not self.cython_only:
352 self.run_distutils(module, workdir, incdir)
354 class CythonRunTestCase(CythonCompileTestCase):
355 def shortDescription(self):
356 return "compiling (%s) and running %s" % (self.language, self.module)
358 def run(self, result=None):
360 result = self.defaultTestResult()
361 result.startTest(self)
364 self.runCompileTest()
365 if not self.cython_only:
366 doctest.DocTestSuite(self.module).run(result)
368 result.addError(self, sys.exc_info())
369 result.stopTest(self)
375 class CythonUnitTestCase(CythonCompileTestCase):
376 def shortDescription(self):
377 return "compiling (%s) tests in %s" % (self.language, self.module)
379 def run(self, result=None):
381 result = self.defaultTestResult()
382 result.startTest(self)
385 self.runCompileTest()
386 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
388 result.addError(self, sys.exc_info())
389 result.stopTest(self)
395 def collect_unittests(path, module_prefix, suite, selectors):
396 def file_matches(filename):
397 return filename.startswith("Test") and filename.endswith(".py")
399 def package_matches(dirname):
400 return dirname == "Tests"
402 loader = unittest.TestLoader()
406 for dirpath, dirnames, filenames in os.walk(path):
407 if dirpath != path and "__init__.py" not in filenames:
408 skipped_dirs.append(dirpath + os.path.sep)
411 for dir in skipped_dirs:
412 if dirpath.startswith(dir):
416 parentname = os.path.split(dirpath)[-1]
417 if package_matches(parentname):
420 filepath = os.path.join(dirpath, f)[:-len(".py")]
421 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
422 if not [ 1 for match in selectors if match(modulename) ]:
424 module = __import__(modulename)
425 for x in modulename.split('.')[1:]:
426 module = getattr(module, x)
427 suite.addTests([loader.loadTestsFromModule(module)])
429 def collect_doctests(path, module_prefix, suite, selectors):
430 def package_matches(dirname):
431 return dirname not in ("Mac", "Distutils", "Plex")
432 def file_matches(filename):
433 return (filename.endswith(".py") and not ('~' in filename
434 or '#' in filename or filename.startswith('.')))
435 import doctest, types
436 for dirpath, dirnames, filenames in os.walk(path):
437 parentname = os.path.split(dirpath)[-1]
438 if package_matches(parentname):
441 if not f.endswith('.py'): continue
442 filepath = os.path.join(dirpath, f)[:-len(".py")]
443 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
444 if not [ 1 for match in selectors if match(modulename) ]:
446 module = __import__(modulename)
447 for x in modulename.split('.')[1:]:
448 module = getattr(module, x)
449 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
451 suite.addTest(doctest.DocTestSuite(module))
452 except ValueError: # no tests
455 class MissingDependencyExcluder:
456 def __init__(self, deps):
457 # deps: { module name : matcher func }
458 self.exclude_matchers = []
459 for mod, matcher in deps.items():
463 self.exclude_matchers.append(matcher)
464 self.tests_missing_deps = []
465 def __call__(self, testname):
466 for matcher in self.exclude_matchers:
467 if matcher(testname):
468 self.tests_missing_deps.append(testname)
472 class VersionDependencyExcluder:
473 def __init__(self, deps):
474 # deps: { version : matcher func }
475 from sys import version_info
476 self.exclude_matchers = []
477 for ver, (compare, matcher) in deps.items():
478 if compare(version_info, ver):
479 self.exclude_matchers.append(matcher)
480 self.tests_missing_deps = []
481 def __call__(self, testname):
482 for matcher in self.exclude_matchers:
483 if matcher(testname):
484 self.tests_missing_deps.append(testname)
488 class FileListExcluder:
490 def __init__(self, list_file):
492 for line in open(list_file).readlines():
494 if line and line[0] != '#':
495 self.excludes[line.split()[0]] = True
497 def __call__(self, testname):
498 return testname.split('.')[-1] in self.excludes
500 if __name__ == '__main__':
501 from optparse import OptionParser
502 parser = OptionParser()
503 parser.add_option("--no-cleanup", dest="cleanup_workdir",
504 action="store_false", default=True,
505 help="do not delete the generated C files (allows passing --no-cython on next run)")
506 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
507 action="store_false", default=True,
508 help="do not delete the generated shared libary files (allows manual module experimentation)")
509 parser.add_option("--no-cython", dest="with_cython",
510 action="store_false", default=True,
511 help="do not run the Cython compiler, only the C compiler")
512 parser.add_option("--no-c", dest="use_c",
513 action="store_false", default=True,
514 help="do not test C compilation")
515 parser.add_option("--no-cpp", dest="use_cpp",
516 action="store_false", default=True,
517 help="do not test C++ compilation")
518 parser.add_option("--no-unit", dest="unittests",
519 action="store_false", default=True,
520 help="do not run the unit tests")
521 parser.add_option("--no-doctest", dest="doctests",
522 action="store_false", default=True,
523 help="do not run the doctests")
524 parser.add_option("--no-file", dest="filetests",
525 action="store_false", default=True,
526 help="do not run the file based tests")
527 parser.add_option("--no-pyregr", dest="pyregr",
528 action="store_false", default=True,
529 help="do not run the regression tests of CPython in tests/pyregr/")
530 parser.add_option("--cython-only", dest="cython_only",
531 action="store_true", default=False,
532 help="only compile pyx to c, do not run C compiler or run the tests")
533 parser.add_option("--no-refnanny", dest="with_refnanny",
534 action="store_false", default=True,
535 help="do not regression test reference counting")
536 parser.add_option("--sys-pyregr", dest="system_pyregr",
537 action="store_true", default=False,
538 help="run the regression tests of the CPython installation")
539 parser.add_option("-x", "--exclude", dest="exclude",
540 action="append", metavar="PATTERN",
541 help="exclude tests matching the PATTERN")
542 parser.add_option("-C", "--coverage", dest="coverage",
543 action="store_true", default=False,
544 help="collect source coverage data for the Compiler")
545 parser.add_option("-A", "--annotate", dest="annotate_source",
546 action="store_true", default=True,
547 help="generate annotated HTML versions of the test source files")
548 parser.add_option("--no-annotate", dest="annotate_source",
549 action="store_false",
550 help="do not generate annotated HTML versions of the test source files")
551 parser.add_option("-v", "--verbose", dest="verbosity",
552 action="count", default=0,
553 help="display test progress, pass twice to print test names")
554 parser.add_option("-T", "--ticket", dest="tickets",
556 help="a bug ticket number to run the respective test in 'tests/bugs'")
558 options, cmd_args = parser.parse_args()
560 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
561 ROOTDIR = os.path.join(DISTDIR, 'tests')
562 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
564 if sys.version_info >= (3,1):
565 options.doctests = False
566 options.unittests = False
567 options.pyregr = False
568 if options.with_cython:
569 # need to convert Cython sources first
570 import lib2to3.refactor
571 from distutils.util import copydir_run_2to3
572 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
573 if fix.split('fix_')[-1] not in ('next',)
575 cy3_dir = os.path.join(WORKDIR, 'Cy3')
576 if not os.path.exists(cy3_dir):
578 import distutils.log as dlog
579 dlog.set_threshold(dlog.DEBUG)
580 copydir_run_2to3(DISTDIR, cy3_dir, fixer_names=fixers,
584 recursive-exclude Cython *
585 recursive-include Cython *.py *.pyx *.pxd
587 sys.path.insert(0, cy3_dir)
588 elif sys.version_info[0] >= 3:
589 # make sure we do not import (or run) Cython itself
590 options.with_cython = False
591 options.doctests = False
592 options.unittests = False
593 options.pyregr = False
600 WITH_CYTHON = options.with_cython
603 from Cython.Compiler.Main import \
604 CompilationOptions, \
605 default_options as pyrex_default_options, \
606 compile as cython_compile
607 from Cython.Compiler import Errors
608 Errors.LEVEL = 0 # show all warnings
611 UNITTEST_MODULE = "Cython"
612 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
614 if os.path.exists(WORKDIR):
615 for path in os.listdir(WORKDIR):
616 if path in ("support", "Cy3"): continue
617 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
618 if not os.path.exists(WORKDIR):
622 from Cython.Compiler.Version import version
623 sys.stderr.write("Running tests against Cython %s\n" % version)
624 from Cython.Compiler import DebugFlags
625 DebugFlags.debug_temp_code_comments = 1
627 sys.stderr.write("Running tests without Cython.\n")
628 sys.stderr.write("Python %s\n" % sys.version)
629 sys.stderr.write("\n")
631 if options.with_refnanny:
632 from pyximport.pyxbuild import pyx_to_dll
633 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
635 pyxbuild_dir=os.path.join(WORKDIR, "support"))
636 sys.path.insert(0, os.path.split(libpath)[0])
637 CFLAGS.append("-DCYTHON_REFNANNY")
641 for ticket_number in options.tickets:
643 cmd_args.append('.*T%s$' % ticket_number)
645 for selector in cmd_args:
646 if selector.startswith('bugs'):
650 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
652 selectors = [ lambda x:True ]
654 # Chech which external modules are not present and exclude tests
655 # which depends on them (by prefix)
657 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
658 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
659 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
662 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
665 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
669 languages.append('c')
671 languages.append('cpp')
673 test_suite = unittest.TestSuite()
675 if options.unittests:
676 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
679 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
681 if options.filetests and languages:
682 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
683 options.annotate_source, options.cleanup_workdir,
684 options.cleanup_sharedlibs, options.pyregr,
685 options.cython_only, languages, test_bugs)
686 test_suite.addTest(filetests.build_suite())
688 if options.system_pyregr and languages:
689 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
690 options.annotate_source, options.cleanup_workdir,
691 options.cleanup_sharedlibs, True,
692 options.cython_only, languages, test_bugs)
694 filetests.handle_directory(
695 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
698 unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
702 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
703 modules = [ module for name, module in sys.modules.items()
704 if module is not None and
705 name.startswith('Cython.Compiler.') and
706 name[len('Cython.Compiler.'):] not in ignored_modules ]
707 coverage.report(modules, show_missing=0)
709 if missing_dep_excluder.tests_missing_deps:
710 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
711 for test in missing_dep_excluder.tests_missing_deps:
712 sys.stderr.write(" %s\n" % test)
714 if options.with_refnanny:
716 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))