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']
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 filenames = os.listdir(self.rootdir)
96 for filename in filenames:
97 if not WITH_CYTHON and filename == "errors":
98 # we won't get any errors without running Cython
100 path = os.path.join(self.rootdir, filename)
101 if os.path.isdir(path) and filename in test_dirs:
102 if filename == 'pyregr' and not self.with_pyregr:
105 self.handle_directory(path, filename))
108 def handle_directory(self, path, context):
109 workdir = os.path.join(self.workdir, context)
110 if not os.path.exists(workdir):
113 expect_errors = (context == 'errors')
114 suite = unittest.TestSuite()
115 filenames = os.listdir(path)
117 for filename in filenames:
118 if not (filename.endswith(".pyx") or filename.endswith(".py")):
120 if filename.startswith('.'): continue # certain emacs backup files
121 if context == 'pyregr' and not filename.startswith('test_'):
123 module = os.path.splitext(filename)[0]
124 fqmodule = "%s.%s" % (context, module)
125 if not [ 1 for match in self.selectors
126 if match(fqmodule) ]:
128 if self.exclude_selectors:
129 if [1 for match in self.exclude_selectors if match(fqmodule)]:
131 if context in TEST_RUN_DIRS:
132 if module.startswith("test_"):
133 test_class = CythonUnitTestCase
135 test_class = CythonRunTestCase
137 test_class = CythonCompileTestCase
138 for test in self.build_tests(test_class, path, workdir,
139 module, expect_errors):
143 def build_tests(self, test_class, path, workdir, module, expect_errors):
145 languages = self.languages[:1]
147 languages = self.languages
148 if 'cpp' in module and 'c' in languages:
149 languages = list(languages)
150 languages.remove('c')
151 tests = [ self.build_test(test_class, path, workdir, module,
152 language, expect_errors)
153 for language in languages ]
156 def build_test(self, test_class, path, workdir, module,
157 language, expect_errors):
158 workdir = os.path.join(workdir, language)
159 if not os.path.exists(workdir):
161 return test_class(path, workdir, module,
163 expect_errors=expect_errors,
164 annotate=self.annotate,
165 cleanup_workdir=self.cleanup_workdir,
166 cleanup_sharedlibs=self.cleanup_sharedlibs,
167 cython_only=self.cython_only)
169 class CythonCompileTestCase(unittest.TestCase):
170 def __init__(self, directory, workdir, module, language='c',
171 expect_errors=False, annotate=False, cleanup_workdir=True,
172 cleanup_sharedlibs=True, cython_only=False):
173 self.directory = directory
174 self.workdir = workdir
176 self.language = language
177 self.expect_errors = expect_errors
178 self.annotate = annotate
179 self.cleanup_workdir = cleanup_workdir
180 self.cleanup_sharedlibs = cleanup_sharedlibs
181 self.cython_only = cython_only
182 unittest.TestCase.__init__(self)
184 def shortDescription(self):
185 return "compiling (%s) %s" % (self.language, self.module)
188 if self.workdir not in sys.path:
189 sys.path.insert(0, self.workdir)
193 sys.path.remove(self.workdir)
197 del sys.modules[self.module]
200 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
201 cleanup_lib_files = self.cleanup_sharedlibs
202 if os.path.exists(self.workdir):
203 for rmfile in os.listdir(self.workdir):
204 if not cleanup_c_files:
205 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
207 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
209 if self.annotate and rmfile.endswith(".html"):
212 rmfile = os.path.join(self.workdir, rmfile)
213 if os.path.isdir(rmfile):
214 shutil.rmtree(rmfile, ignore_errors=True)
220 os.makedirs(self.workdir)
223 self.runCompileTest()
225 def runCompileTest(self):
226 self.compile(self.directory, self.module, self.workdir,
227 self.directory, self.expect_errors, self.annotate)
229 def find_module_source_file(self, source_file):
230 if not os.path.exists(source_file):
231 source_file = source_file[:-1]
234 def build_target_filename(self, module_name):
235 target = '%s.%s' % (module_name, self.language)
238 def split_source_and_output(self, directory, module, workdir):
239 source_file = os.path.join(directory, module) + '.pyx'
240 source_and_output = open(
241 self.find_module_source_file(source_file), 'rU')
242 out = open(os.path.join(workdir, module + '.pyx'), 'w')
243 for line in source_and_output:
245 if line.startswith("_ERRORS"):
251 geterrors = out.geterrors
252 except AttributeError:
257 def run_cython(self, directory, module, targetdir, incdir, annotate):
258 include_dirs = INCLUDE_DIRS[:]
260 include_dirs.append(incdir)
261 source = self.find_module_source_file(
262 os.path.join(directory, module + '.pyx'))
263 target = os.path.join(targetdir, self.build_target_filename(module))
264 options = CompilationOptions(
265 pyrex_default_options,
266 include_path = include_dirs,
267 output_file = target,
269 use_listing_file = False,
270 cplus = self.language == 'cpp',
271 generate_pxi = False)
272 cython_compile(source, options=options,
273 full_module_name=module)
275 def run_distutils(self, module, workdir, incdir):
279 build_extension = build_ext(distutils_distro)
280 build_extension.include_dirs = INCLUDE_DIRS[:]
282 build_extension.include_dirs.append(incdir)
283 build_extension.finalize_options()
284 ext_include_dirs = []
285 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
287 ext_include_dirs += get_additional_include_dirs()
288 extension = Extension(
290 sources = [self.build_target_filename(module)],
291 include_dirs = ext_include_dirs,
292 extra_compile_args = CFLAGS,
294 if self.language == 'cpp':
295 extension.language = 'c++'
296 build_extension.extensions = [extension]
297 build_extension.build_temp = workdir
298 build_extension.build_lib = workdir
299 build_extension.run()
303 def compile(self, directory, module, workdir, incdir,
304 expect_errors, annotate):
305 expected_errors = errors = ()
307 expected_errors = self.split_source_and_output(
308 directory, module, workdir)
312 old_stderr = sys.stderr
314 sys.stderr = ErrorWriter()
315 self.run_cython(directory, module, workdir, incdir, annotate)
316 errors = sys.stderr.geterrors()
318 sys.stderr = old_stderr
320 if errors or expected_errors:
321 for expected, error in zip(expected_errors, errors):
322 self.assertEquals(expected, error)
323 if len(errors) < len(expected_errors):
324 expected_error = expected_errors[len(errors)]
325 self.assertEquals(expected_error, None)
326 elif len(errors) > len(expected_errors):
327 unexpected_error = errors[len(expected_errors)]
328 self.assertEquals(None, unexpected_error)
330 if not self.cython_only:
331 self.run_distutils(module, workdir, incdir)
333 class CythonRunTestCase(CythonCompileTestCase):
334 def shortDescription(self):
335 return "compiling (%s) and running %s" % (self.language, self.module)
337 def run(self, result=None):
339 result = self.defaultTestResult()
340 result.startTest(self)
343 self.runCompileTest()
344 if not self.cython_only:
345 doctest.DocTestSuite(self.module).run(result)
347 result.addError(self, sys.exc_info())
348 result.stopTest(self)
354 class CythonUnitTestCase(CythonCompileTestCase):
355 def shortDescription(self):
356 return "compiling (%s) tests in %s" % (self.language, self.module)
358 def run(self, result=None):
360 result = self.defaultTestResult()
361 result.startTest(self)
364 self.runCompileTest()
365 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
367 result.addError(self, sys.exc_info())
368 result.stopTest(self)
374 def collect_unittests(path, module_prefix, suite, selectors):
375 def file_matches(filename):
376 return filename.startswith("Test") and filename.endswith(".py")
378 def package_matches(dirname):
379 return dirname == "Tests"
381 loader = unittest.TestLoader()
385 for dirpath, dirnames, filenames in os.walk(path):
386 if dirpath != path and "__init__.py" not in filenames:
387 skipped_dirs.append(dirpath + os.path.sep)
390 for dir in skipped_dirs:
391 if dirpath.startswith(dir):
395 parentname = os.path.split(dirpath)[-1]
396 if package_matches(parentname):
399 filepath = os.path.join(dirpath, f)[:-len(".py")]
400 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
401 if not [ 1 for match in selectors if match(modulename) ]:
403 module = __import__(modulename)
404 for x in modulename.split('.')[1:]:
405 module = getattr(module, x)
406 suite.addTests([loader.loadTestsFromModule(module)])
408 def collect_doctests(path, module_prefix, suite, selectors):
409 def package_matches(dirname):
410 return dirname not in ("Mac", "Distutils", "Plex")
411 def file_matches(filename):
412 return (filename.endswith(".py") and not ('~' in filename
413 or '#' in filename or filename.startswith('.')))
414 import doctest, types
415 for dirpath, dirnames, filenames in os.walk(path):
416 parentname = os.path.split(dirpath)[-1]
417 if package_matches(parentname):
420 if not f.endswith('.py'): continue
421 filepath = os.path.join(dirpath, f)[:-len(".py")]
422 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
423 if not [ 1 for match in selectors if match(modulename) ]:
425 module = __import__(modulename)
426 for x in modulename.split('.')[1:]:
427 module = getattr(module, x)
428 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
430 suite.addTest(doctest.DocTestSuite(module))
431 except ValueError: # no tests
434 class MissingDependencyExcluder:
435 def __init__(self, deps):
436 # deps: { module name : matcher func }
437 self.exclude_matchers = []
438 for mod, matcher in deps.items():
442 self.exclude_matchers.append(matcher)
443 self.tests_missing_deps = []
444 def __call__(self, testname):
445 for matcher in self.exclude_matchers:
446 if matcher(testname):
447 self.tests_missing_deps.append(testname)
451 class VersionDependencyExcluder:
452 def __init__(self, deps):
453 # deps: { version : matcher func }
454 from sys import version_info
455 self.exclude_matchers = []
456 for ver, matcher in deps.items():
457 if version_info < ver:
458 self.exclude_matchers.append(matcher)
459 self.tests_missing_deps = []
460 def __call__(self, testname):
461 for matcher in self.exclude_matchers:
462 if matcher(testname):
463 self.tests_missing_deps.append(testname)
467 class FileListExcluder:
469 def __init__(self, list_file):
471 for line in open(list_file).readlines():
473 if line and line[0] != '#':
474 self.excludes[line.split()[0]] = True
476 def __call__(self, testname):
477 return testname.split('.')[-1] in self.excludes
479 if __name__ == '__main__':
480 from optparse import OptionParser
481 parser = OptionParser()
482 parser.add_option("--no-cleanup", dest="cleanup_workdir",
483 action="store_false", default=True,
484 help="do not delete the generated C files (allows passing --no-cython on next run)")
485 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
486 action="store_false", default=True,
487 help="do not delete the generated shared libary files (allows manual module experimentation)")
488 parser.add_option("--no-cython", dest="with_cython",
489 action="store_false", default=True,
490 help="do not run the Cython compiler, only the C compiler")
491 parser.add_option("--no-c", dest="use_c",
492 action="store_false", default=True,
493 help="do not test C compilation")
494 parser.add_option("--no-cpp", dest="use_cpp",
495 action="store_false", default=True,
496 help="do not test C++ compilation")
497 parser.add_option("--no-unit", dest="unittests",
498 action="store_false", default=True,
499 help="do not run the unit tests")
500 parser.add_option("--no-doctest", dest="doctests",
501 action="store_false", default=True,
502 help="do not run the doctests")
503 parser.add_option("--no-file", dest="filetests",
504 action="store_false", default=True,
505 help="do not run the file based tests")
506 parser.add_option("--no-pyregr", dest="pyregr",
507 action="store_false", default=True,
508 help="do not run the regression tests of CPython in tests/pyregr/")
509 parser.add_option("--cython-only", dest="cython_only",
510 action="store_true", default=False,
511 help="only compile pyx to c, do not run C compiler or run the tests")
512 parser.add_option("--no-refnanny", dest="with_refnanny",
513 action="store_false", default=True,
514 help="do not regression test reference counting")
515 parser.add_option("--sys-pyregr", dest="system_pyregr",
516 action="store_true", default=False,
517 help="run the regression tests of the CPython installation")
518 parser.add_option("-x", "--exclude", dest="exclude",
519 action="append", metavar="PATTERN",
520 help="exclude tests matching the PATTERN")
521 parser.add_option("-C", "--coverage", dest="coverage",
522 action="store_true", default=False,
523 help="collect source coverage data for the Compiler")
524 parser.add_option("-A", "--annotate", dest="annotate_source",
525 action="store_true", default=True,
526 help="generate annotated HTML versions of the test source files")
527 parser.add_option("--no-annotate", dest="annotate_source",
528 action="store_false",
529 help="do not generate annotated HTML versions of the test source files")
530 parser.add_option("-v", "--verbose", dest="verbosity",
531 action="count", default=0,
532 help="display test progress, pass twice to print test names")
533 parser.add_option("-T", "--ticket", dest="tickets",
535 help="a bug ticket number to run the respective test in 'tests/bugs'")
537 options, cmd_args = parser.parse_args()
539 if sys.version_info[0] >= 3:
540 # make sure we do not import (or run) Cython itself
541 options.doctests = False
542 options.with_cython = False
543 options.unittests = False
544 options.pyregr = False
551 WITH_CYTHON = options.with_cython
554 from Cython.Compiler.Main import \
555 CompilationOptions, \
556 default_options as pyrex_default_options, \
557 compile as cython_compile
558 from Cython.Compiler import Errors
559 Errors.LEVEL = 0 # show all warnings
562 ROOTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), 'tests')
563 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
564 UNITTEST_MODULE = "Cython"
565 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
567 if os.path.exists(WORKDIR):
568 for path in os.listdir(WORKDIR):
569 if path in ("support",): continue
570 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
571 if not os.path.exists(WORKDIR):
575 from Cython.Compiler.Version import version
576 sys.stderr.write("Running tests against Cython %s\n" % version)
577 from Cython.Compiler import DebugFlags
578 DebugFlags.debug_temp_code_comments = 1
580 sys.stderr.write("Running tests without Cython.\n")
581 sys.stderr.write("Python %s\n" % sys.version)
582 sys.stderr.write("\n")
584 if options.with_refnanny:
585 from pyximport.pyxbuild import pyx_to_dll
586 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
588 pyxbuild_dir=os.path.join(WORKDIR, "support"))
589 sys.path.insert(0, os.path.split(libpath)[0])
590 CFLAGS.append("-DCYTHON_REFNANNY")
594 for ticket_number in options.tickets:
596 cmd_args.append('.*T%s$' % ticket_number)
598 for selector in cmd_args:
599 if selector.startswith('bugs'):
603 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
605 selectors = [ lambda x:True ]
607 # Chech which external modules are not present and exclude tests
608 # which depends on them (by prefix)
610 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
611 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
612 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
615 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
618 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
622 languages.append('c')
624 languages.append('cpp')
626 test_suite = unittest.TestSuite()
628 if options.unittests:
629 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
632 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
634 if options.filetests and languages:
635 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
636 options.annotate_source, options.cleanup_workdir,
637 options.cleanup_sharedlibs, options.pyregr,
638 options.cython_only, languages, test_bugs)
639 test_suite.addTest(filetests.build_suite())
641 if options.system_pyregr and languages:
642 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
643 options.annotate_source, options.cleanup_workdir,
644 options.cleanup_sharedlibs, True,
645 options.cython_only, languages, test_bugs)
647 filetests.handle_directory(
648 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
651 unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
655 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
656 modules = [ module for name, module in sys.modules.items()
657 if module is not None and
658 name.startswith('Cython.Compiler.') and
659 name[len('Cython.Compiler.'):] not in ignored_modules ]
660 coverage.report(modules, show_missing=0)
662 if missing_dep_excluder.tests_missing_deps:
663 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
664 for test in missing_dep_excluder.tests_missing_deps:
665 sys.stderr.write(" %s\n" % test)
667 if options.with_refnanny:
669 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))