3 import os, sys, re, shutil, unittest, doctest
7 from distutils.dist import Distribution
8 from distutils.core import Extension
9 from distutils.command.build_ext import build_ext as _build_ext
10 distutils_distro = Distribution()
12 TEST_DIRS = ['compile', 'errors', 'run', 'pyregr']
13 TEST_RUN_DIRS = ['run', 'pyregr', 'bugs']
15 # Lists external modules, and a matcher matching tests
16 # which should be excluded if the module is not present.
18 'numpy' : re.compile('.*\.numpy_.*').match
21 def get_numpy_include_dirs():
23 return [numpy.get_include()]
26 # test name matcher , callable returning list
27 (re.compile('numpy_.*').match, get_numpy_include_dirs),
32 # (2,4) : lambda x: x in ['run.set']
35 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
36 CFLAGS = os.getenv('CFLAGS', '').split()
38 class build_ext(_build_ext):
39 def build_extension(self, ext):
40 if ext.language == 'c++':
42 self.compiler.compiler_so.remove('-Wstrict-prototypes')
45 _build_ext.build_extension(self, ext)
47 class ErrorWriter(object):
48 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
51 self.write = self.output.append
53 def _collect(self, collect_errors, collect_warnings):
54 s = ''.join(self.output)
56 for line in s.split('\n'):
57 match = self.match_error(line)
59 is_warning, line, column, message = match.groups()
60 if (is_warning and collect_warnings) or \
61 (not is_warning and collect_errors):
62 result.append( (int(line), int(column), message.strip()) )
64 return [ "%d:%d: %s" % values for values in result ]
67 return self._collect(True, False)
69 def getwarnings(self):
70 return self._collect(False, True)
73 return self._collect(True, True)
75 class TestBuilder(object):
76 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
77 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
78 languages, test_bugs):
79 self.rootdir = rootdir
80 self.workdir = workdir
81 self.selectors = selectors
82 self.exclude_selectors = exclude_selectors
83 self.annotate = annotate
84 self.cleanup_workdir = cleanup_workdir
85 self.cleanup_sharedlibs = cleanup_sharedlibs
86 self.with_pyregr = with_pyregr
87 self.cython_only = cython_only
88 self.languages = languages
89 self.test_bugs = test_bugs
91 def build_suite(self):
92 suite = unittest.TestSuite()
94 if self.test_bugs and 'bugs' not in test_dirs:
95 test_dirs.append('bugs')
96 filenames = os.listdir(self.rootdir)
98 for filename in filenames:
99 if not WITH_CYTHON and filename == "errors":
100 # we won't get any errors without running Cython
102 path = os.path.join(self.rootdir, filename)
103 if os.path.isdir(path) and filename in test_dirs:
104 if filename == 'pyregr' and not self.with_pyregr:
107 self.handle_directory(path, filename))
110 def handle_directory(self, path, context):
111 workdir = os.path.join(self.workdir, context)
112 if not os.path.exists(workdir):
115 expect_errors = (context == 'errors')
116 suite = unittest.TestSuite()
117 filenames = os.listdir(path)
119 for filename in filenames:
120 if not (filename.endswith(".pyx") or filename.endswith(".py")):
122 if filename.startswith('.'): continue # certain emacs backup files
123 if context == 'pyregr' and not filename.startswith('test_'):
125 module = os.path.splitext(filename)[0]
126 fqmodule = "%s.%s" % (context, module)
127 if not [ 1 for match in self.selectors
128 if match(fqmodule) ]:
130 if self.exclude_selectors:
131 if [1 for match in self.exclude_selectors if match(fqmodule)]:
133 if context in TEST_RUN_DIRS:
134 if module.startswith("test_"):
135 test_class = CythonUnitTestCase
137 test_class = CythonRunTestCase
139 test_class = CythonCompileTestCase
140 for test in self.build_tests(test_class, path, workdir,
141 module, expect_errors):
145 def build_tests(self, test_class, path, workdir, module, expect_errors):
147 languages = self.languages[:1]
149 languages = self.languages
150 tests = [ self.build_test(test_class, path, workdir, module,
151 language, expect_errors)
152 for language in languages ]
155 def build_test(self, test_class, path, workdir, module,
156 language, expect_errors):
157 workdir = os.path.join(workdir, language)
158 if not os.path.exists(workdir):
160 return test_class(path, workdir, module,
162 expect_errors=expect_errors,
163 annotate=self.annotate,
164 cleanup_workdir=self.cleanup_workdir,
165 cleanup_sharedlibs=self.cleanup_sharedlibs,
166 cython_only=self.cython_only)
168 class CythonCompileTestCase(unittest.TestCase):
169 def __init__(self, directory, workdir, module, language='c',
170 expect_errors=False, annotate=False, cleanup_workdir=True,
171 cleanup_sharedlibs=True, cython_only=False):
172 self.directory = directory
173 self.workdir = workdir
175 self.language = language
176 self.expect_errors = expect_errors
177 self.annotate = annotate
178 self.cleanup_workdir = cleanup_workdir
179 self.cleanup_sharedlibs = cleanup_sharedlibs
180 self.cython_only = cython_only
181 unittest.TestCase.__init__(self)
183 def shortDescription(self):
184 return "compiling (%s) %s" % (self.language, self.module)
187 if self.workdir not in sys.path:
188 sys.path.insert(0, self.workdir)
192 sys.path.remove(self.workdir)
196 del sys.modules[self.module]
199 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
200 cleanup_lib_files = self.cleanup_sharedlibs
201 if os.path.exists(self.workdir):
202 for rmfile in os.listdir(self.workdir):
203 if not cleanup_c_files:
204 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
206 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
208 if self.annotate and rmfile.endswith(".html"):
211 rmfile = os.path.join(self.workdir, rmfile)
212 if os.path.isdir(rmfile):
213 shutil.rmtree(rmfile, ignore_errors=True)
219 os.makedirs(self.workdir)
222 self.runCompileTest()
224 def runCompileTest(self):
225 self.compile(self.directory, self.module, self.workdir,
226 self.directory, self.expect_errors, self.annotate)
228 def find_module_source_file(self, source_file):
229 if not os.path.exists(source_file):
230 source_file = source_file[:-1]
233 def build_target_filename(self, module_name):
234 target = '%s.%s' % (module_name, self.language)
237 def split_source_and_output(self, directory, module, workdir):
238 source_file = os.path.join(directory, module) + '.pyx'
239 source_and_output = open(
240 self.find_module_source_file(source_file), 'rU')
241 out = open(os.path.join(workdir, module + '.pyx'), 'w')
242 for line in source_and_output:
244 if line.startswith("_ERRORS"):
250 geterrors = out.geterrors
251 except AttributeError:
256 def run_cython(self, directory, module, targetdir, incdir, annotate):
257 include_dirs = INCLUDE_DIRS[:]
259 include_dirs.append(incdir)
260 source = self.find_module_source_file(
261 os.path.join(directory, module + '.pyx'))
262 target = os.path.join(targetdir, self.build_target_filename(module))
263 options = CompilationOptions(
264 pyrex_default_options,
265 include_path = include_dirs,
266 output_file = target,
268 use_listing_file = False,
269 cplus = self.language == 'cpp',
270 generate_pxi = False)
271 cython_compile(source, options=options,
272 full_module_name=module)
274 def run_distutils(self, module, workdir, incdir):
278 build_extension = build_ext(distutils_distro)
279 build_extension.include_dirs = INCLUDE_DIRS[:]
281 build_extension.include_dirs.append(incdir)
282 build_extension.finalize_options()
283 ext_include_dirs = []
284 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
286 ext_include_dirs += get_additional_include_dirs()
287 extension = Extension(
289 sources = [self.build_target_filename(module)],
290 include_dirs = ext_include_dirs,
291 extra_compile_args = CFLAGS,
293 if self.language == 'cpp':
294 extension.language = 'c++'
295 build_extension.extensions = [extension]
296 build_extension.build_temp = workdir
297 build_extension.build_lib = workdir
298 build_extension.run()
302 def compile(self, directory, module, workdir, incdir,
303 expect_errors, annotate):
304 expected_errors = errors = ()
306 expected_errors = self.split_source_and_output(
307 directory, module, workdir)
311 old_stderr = sys.stderr
313 sys.stderr = ErrorWriter()
314 self.run_cython(directory, module, workdir, incdir, annotate)
315 errors = sys.stderr.geterrors()
317 sys.stderr = old_stderr
319 if errors or expected_errors:
320 for expected, error in zip(expected_errors, errors):
321 self.assertEquals(expected, error)
322 if len(errors) < len(expected_errors):
323 expected_error = expected_errors[len(errors)]
324 self.assertEquals(expected_error, None)
325 elif len(errors) > len(expected_errors):
326 unexpected_error = errors[len(expected_errors)]
327 self.assertEquals(None, unexpected_error)
329 if not self.cython_only:
330 self.run_distutils(module, workdir, incdir)
332 class CythonRunTestCase(CythonCompileTestCase):
333 def shortDescription(self):
334 return "compiling (%s) and running %s" % (self.language, self.module)
336 def run(self, result=None):
338 result = self.defaultTestResult()
339 result.startTest(self)
342 self.runCompileTest()
343 if not self.cython_only:
344 doctest.DocTestSuite(self.module).run(result)
346 result.addError(self, sys.exc_info())
347 result.stopTest(self)
353 class CythonUnitTestCase(CythonCompileTestCase):
354 def shortDescription(self):
355 return "compiling (%s) tests in %s" % (self.language, self.module)
357 def run(self, result=None):
359 result = self.defaultTestResult()
360 result.startTest(self)
363 self.runCompileTest()
364 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
366 result.addError(self, sys.exc_info())
367 result.stopTest(self)
373 def collect_unittests(path, module_prefix, suite, selectors):
374 def file_matches(filename):
375 return filename.startswith("Test") and filename.endswith(".py")
377 def package_matches(dirname):
378 return dirname == "Tests"
380 loader = unittest.TestLoader()
384 for dirpath, dirnames, filenames in os.walk(path):
385 if dirpath != path and "__init__.py" not in filenames:
386 skipped_dirs.append(dirpath + os.path.sep)
389 for dir in skipped_dirs:
390 if dirpath.startswith(dir):
394 parentname = os.path.split(dirpath)[-1]
395 if package_matches(parentname):
398 filepath = os.path.join(dirpath, f)[:-len(".py")]
399 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
400 if not [ 1 for match in selectors if match(modulename) ]:
402 module = __import__(modulename)
403 for x in modulename.split('.')[1:]:
404 module = getattr(module, x)
405 suite.addTests([loader.loadTestsFromModule(module)])
407 def collect_doctests(path, module_prefix, suite, selectors):
408 def package_matches(dirname):
409 return dirname not in ("Mac", "Distutils", "Plex")
410 def file_matches(filename):
411 return (filename.endswith(".py") and not ('~' in filename
412 or '#' in filename or filename.startswith('.')))
413 import doctest, types
414 for dirpath, dirnames, filenames in os.walk(path):
415 parentname = os.path.split(dirpath)[-1]
416 if package_matches(parentname):
419 if not f.endswith('.py'): continue
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 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
429 suite.addTest(doctest.DocTestSuite(module))
430 except ValueError: # no tests
433 class MissingDependencyExcluder:
434 def __init__(self, deps):
435 # deps: { module name : matcher func }
436 self.exclude_matchers = []
437 for mod, matcher in deps.items():
441 self.exclude_matchers.append(matcher)
442 self.tests_missing_deps = []
443 def __call__(self, testname):
444 for matcher in self.exclude_matchers:
445 if matcher(testname):
446 self.tests_missing_deps.append(testname)
450 class VersionDependencyExcluder:
451 def __init__(self, deps):
452 # deps: { version : matcher func }
453 from sys import version_info
454 self.exclude_matchers = []
455 for ver, matcher in deps.items():
456 if version_info < ver:
457 self.exclude_matchers.append(matcher)
458 self.tests_missing_deps = []
459 def __call__(self, testname):
460 for matcher in self.exclude_matchers:
461 if matcher(testname):
462 self.tests_missing_deps.append(testname)
466 if __name__ == '__main__':
467 from optparse import OptionParser
468 parser = OptionParser()
469 parser.add_option("--no-cleanup", dest="cleanup_workdir",
470 action="store_false", default=True,
471 help="do not delete the generated C files (allows passing --no-cython on next run)")
472 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
473 action="store_false", default=True,
474 help="do not delete the generated shared libary files (allows manual module experimentation)")
475 parser.add_option("--no-cython", dest="with_cython",
476 action="store_false", default=True,
477 help="do not run the Cython compiler, only the C compiler")
478 parser.add_option("--no-c", dest="use_c",
479 action="store_false", default=True,
480 help="do not test C compilation")
481 parser.add_option("--no-cpp", dest="use_cpp",
482 action="store_false", default=True,
483 help="do not test C++ compilation")
484 parser.add_option("--no-unit", dest="unittests",
485 action="store_false", default=True,
486 help="do not run the unit tests")
487 parser.add_option("--no-doctest", dest="doctests",
488 action="store_false", default=True,
489 help="do not run the doctests")
490 parser.add_option("--no-file", dest="filetests",
491 action="store_false", default=True,
492 help="do not run the file based tests")
493 parser.add_option("--no-pyregr", dest="pyregr",
494 action="store_false", default=True,
495 help="do not run the regression tests of CPython in tests/pyregr/")
496 parser.add_option("--cython-only", dest="cython_only",
497 action="store_true", default=False,
498 help="only compile pyx to c, do not run C compiler or run the tests")
499 parser.add_option("--no-refnanny", dest="with_refnanny",
500 action="store_false", default=True,
501 help="do not regression test reference counting")
502 parser.add_option("--sys-pyregr", dest="system_pyregr",
503 action="store_true", default=False,
504 help="run the regression tests of the CPython installation")
505 parser.add_option("-x", "--exclude", dest="exclude",
506 action="append", metavar="PATTERN",
507 help="exclude tests matching the PATTERN")
508 parser.add_option("-C", "--coverage", dest="coverage",
509 action="store_true", default=False,
510 help="collect source coverage data for the Compiler")
511 parser.add_option("-A", "--annotate", dest="annotate_source",
512 action="store_true", default=True,
513 help="generate annotated HTML versions of the test source files")
514 parser.add_option("--no-annotate", dest="annotate_source",
515 action="store_false",
516 help="do not generate annotated HTML versions of the test source files")
517 parser.add_option("-v", "--verbose", dest="verbosity",
518 action="count", default=0,
519 help="display test progress, pass twice to print test names")
520 parser.add_option("-T", "--ticket", dest="tickets",
522 help="a bug ticket number to run the respective test in 'tests/bugs'")
524 options, cmd_args = parser.parse_args()
526 if sys.version_info[0] >= 3:
527 # make sure we do not import (or run) Cython itself
528 options.doctests = False
529 options.with_cython = False
530 options.unittests = False
531 options.pyregr = False
538 WITH_CYTHON = options.with_cython
541 from Cython.Compiler.Main import \
542 CompilationOptions, \
543 default_options as pyrex_default_options, \
544 compile as cython_compile
545 from Cython.Compiler import Errors
546 Errors.LEVEL = 0 # show all warnings
549 ROOTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), 'tests')
550 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
551 UNITTEST_MODULE = "Cython"
552 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
554 if os.path.exists(WORKDIR):
555 for path in os.listdir(WORKDIR):
556 if path in ("support",): continue
557 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
558 if not os.path.exists(WORKDIR):
562 from Cython.Compiler.Version import version
563 sys.stderr.write("Running tests against Cython %s\n" % version)
564 from Cython.Compiler import DebugFlags
565 DebugFlags.debug_temp_code_comments = 1
567 sys.stderr.write("Running tests without Cython.\n")
568 sys.stderr.write("Python %s\n" % sys.version)
569 sys.stderr.write("\n")
571 if options.with_refnanny:
572 from pyximport.pyxbuild import pyx_to_dll
573 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
575 pyxbuild_dir=os.path.join(WORKDIR, "support"))
576 sys.path.insert(0, os.path.split(libpath)[0])
577 CFLAGS.append("-DCYTHON_REFNANNY")
581 for ticket_number in options.tickets:
583 cmd_args.append('bugs.*T%s$' % ticket_number)
585 for selector in cmd_args:
586 if selector.startswith('bugs'):
590 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
592 selectors = [ lambda x:True ]
594 # Chech which external modules are not present and exclude tests
595 # which depends on them (by prefix)
597 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
598 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
599 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
602 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
606 languages.append('c')
608 languages.append('cpp')
610 test_suite = unittest.TestSuite()
612 if options.unittests:
613 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
616 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
618 if options.filetests and languages:
619 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
620 options.annotate_source, options.cleanup_workdir,
621 options.cleanup_sharedlibs, options.pyregr,
622 options.cython_only, languages, test_bugs)
623 test_suite.addTest(filetests.build_suite())
625 if options.system_pyregr and languages:
626 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
627 options.annotate_source, options.cleanup_workdir,
628 options.cleanup_sharedlibs, True,
629 options.cython_only, languages)
631 filetests.handle_directory(
632 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
635 unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
639 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
640 modules = [ module for name, module in sys.modules.items()
641 if module is not None and
642 name.startswith('Cython.Compiler.') and
643 name[len('Cython.Compiler.'):] not in ignored_modules ]
644 coverage.report(modules, show_missing=0)
646 if missing_dep_excluder.tests_missing_deps:
647 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
648 for test in missing_dep_excluder.tests_missing_deps:
649 sys.stderr.write(" %s\n" % test)
651 if options.with_refnanny:
653 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))