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
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
23 # (2,4) : lambda x: x in ['run.set']
26 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
27 CFLAGS = os.getenv('CFLAGS', '').split()
30 class ErrorWriter(object):
31 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
34 self.write = self.output.append
36 def _collect(self, collect_errors, collect_warnings):
37 s = ''.join(self.output)
39 for line in s.split('\n'):
40 match = self.match_error(line)
42 is_warning, line, column, message = match.groups()
43 if (is_warning and collect_warnings) or \
44 (not is_warning and collect_errors):
45 result.append( (int(line), int(column), message.strip()) )
47 return [ "%d:%d: %s" % values for values in result ]
50 return self._collect(True, False)
52 def getwarnings(self):
53 return self._collect(False, True)
56 return self._collect(True, True)
58 class TestBuilder(object):
59 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
60 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
62 self.rootdir = rootdir
63 self.workdir = workdir
64 self.selectors = selectors
65 self.exclude_selectors = exclude_selectors
66 self.annotate = annotate
67 self.cleanup_workdir = cleanup_workdir
68 self.cleanup_sharedlibs = cleanup_sharedlibs
69 self.with_pyregr = with_pyregr
70 self.cython_only = cython_only
71 self.languages = languages
73 def build_suite(self):
74 suite = unittest.TestSuite()
75 filenames = os.listdir(self.rootdir)
77 for filename in filenames:
78 if not WITH_CYTHON and filename == "errors":
79 # we won't get any errors without running Cython
81 path = os.path.join(self.rootdir, filename)
82 if os.path.isdir(path) and filename in TEST_DIRS:
83 if filename == 'pyregr' and not self.with_pyregr:
86 self.handle_directory(path, filename))
89 def handle_directory(self, path, context):
90 workdir = os.path.join(self.workdir, context)
91 if not os.path.exists(workdir):
94 expect_errors = (context == 'errors')
95 suite = unittest.TestSuite()
96 filenames = os.listdir(path)
98 for filename in filenames:
99 if not (filename.endswith(".pyx") or filename.endswith(".py")):
101 if filename.startswith('.'): continue # certain emacs backup files
102 if context == 'pyregr' and not filename.startswith('test_'):
104 module = os.path.splitext(filename)[0]
105 fqmodule = "%s.%s" % (context, module)
106 if not [ 1 for match in self.selectors
107 if match(fqmodule) ]:
109 if self.exclude_selectors:
110 if [1 for match in self.exclude_selectors if match(fqmodule)]:
112 if context in TEST_RUN_DIRS:
113 if module.startswith("test_"):
114 test_class = CythonUnitTestCase
116 test_class = CythonRunTestCase
118 test_class = CythonCompileTestCase
119 for test in self.build_tests(test_class, path, workdir,
120 module, expect_errors):
124 def build_tests(self, test_class, path, workdir, module, expect_errors):
126 languages = self.languages[:1]
128 languages = self.languages
129 tests = [ self.build_test(test_class, path, workdir, module,
130 language, expect_errors)
131 for language in languages ]
134 def build_test(self, test_class, path, workdir, module,
135 language, expect_errors):
136 workdir = os.path.join(workdir, language)
137 if not os.path.exists(workdir):
139 return test_class(path, workdir, module,
141 expect_errors=expect_errors,
142 annotate=self.annotate,
143 cleanup_workdir=self.cleanup_workdir,
144 cleanup_sharedlibs=self.cleanup_sharedlibs,
145 cython_only=self.cython_only)
147 class CythonCompileTestCase(unittest.TestCase):
148 def __init__(self, directory, workdir, module, language='c',
149 expect_errors=False, annotate=False, cleanup_workdir=True,
150 cleanup_sharedlibs=True, cython_only=False):
151 self.directory = directory
152 self.workdir = workdir
154 self.language = language
155 self.expect_errors = expect_errors
156 self.annotate = annotate
157 self.cleanup_workdir = cleanup_workdir
158 self.cleanup_sharedlibs = cleanup_sharedlibs
159 self.cython_only = cython_only
160 unittest.TestCase.__init__(self)
162 def shortDescription(self):
163 return "compiling (%s) %s" % (self.language, self.module)
166 if self.workdir not in sys.path:
167 sys.path.insert(0, self.workdir)
171 sys.path.remove(self.workdir)
175 del sys.modules[self.module]
178 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
179 cleanup_lib_files = self.cleanup_sharedlibs
180 if os.path.exists(self.workdir):
181 for rmfile in os.listdir(self.workdir):
182 if not cleanup_c_files:
183 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
185 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
187 if self.annotate and rmfile.endswith(".html"):
190 rmfile = os.path.join(self.workdir, rmfile)
191 if os.path.isdir(rmfile):
192 shutil.rmtree(rmfile, ignore_errors=True)
198 os.makedirs(self.workdir)
201 self.runCompileTest()
203 def runCompileTest(self):
204 self.compile(self.directory, self.module, self.workdir,
205 self.directory, self.expect_errors, self.annotate)
207 def find_module_source_file(self, source_file):
208 if not os.path.exists(source_file):
209 source_file = source_file[:-1]
212 def build_target_filename(self, module_name):
213 target = '%s.%s' % (module_name, self.language)
216 def split_source_and_output(self, directory, module, workdir):
217 source_file = os.path.join(directory, module) + '.pyx'
218 source_and_output = open(
219 self.find_module_source_file(source_file), 'rU')
220 out = open(os.path.join(workdir, module + '.pyx'), 'w')
221 for line in source_and_output:
223 if line.startswith("_ERRORS"):
229 geterrors = out.geterrors
230 except AttributeError:
235 def run_cython(self, directory, module, targetdir, incdir, annotate):
236 include_dirs = INCLUDE_DIRS[:]
238 include_dirs.append(incdir)
239 source = self.find_module_source_file(
240 os.path.join(directory, module + '.pyx'))
241 target = os.path.join(targetdir, self.build_target_filename(module))
242 options = CompilationOptions(
243 pyrex_default_options,
244 include_path = include_dirs,
245 output_file = target,
247 use_listing_file = False,
248 cplus = self.language == 'cpp',
249 generate_pxi = False)
250 cython_compile(source, options=options,
251 full_module_name=module)
253 def run_distutils(self, module, workdir, incdir):
257 build_extension = build_ext(distutils_distro)
258 build_extension.include_dirs = INCLUDE_DIRS[:]
260 build_extension.include_dirs.append(incdir)
261 build_extension.finalize_options()
263 extension = Extension(
265 sources = [self.build_target_filename(module)],
266 extra_compile_args = CFLAGS,
268 build_extension.extensions = [extension]
269 build_extension.build_temp = workdir
270 build_extension.build_lib = workdir
271 build_extension.run()
275 def compile(self, directory, module, workdir, incdir,
276 expect_errors, annotate):
277 expected_errors = errors = ()
279 expected_errors = self.split_source_and_output(
280 directory, module, workdir)
284 old_stderr = sys.stderr
286 sys.stderr = ErrorWriter()
287 self.run_cython(directory, module, workdir, incdir, annotate)
288 errors = sys.stderr.geterrors()
290 sys.stderr = old_stderr
292 if errors or expected_errors:
293 for expected, error in zip(expected_errors, errors):
294 self.assertEquals(expected, error)
295 if len(errors) < len(expected_errors):
296 expected_error = expected_errors[len(errors)]
297 self.assertEquals(expected_error, None)
298 elif len(errors) > len(expected_errors):
299 unexpected_error = errors[len(expected_errors)]
300 self.assertEquals(None, unexpected_error)
302 if not self.cython_only:
303 self.run_distutils(module, workdir, incdir)
305 class CythonRunTestCase(CythonCompileTestCase):
306 def shortDescription(self):
307 return "compiling (%s) and running %s" % (self.language, self.module)
309 def run(self, result=None):
311 result = self.defaultTestResult()
312 result.startTest(self)
315 self.runCompileTest()
316 if not self.cython_only:
317 sys.stderr.write('running doctests in %s ...\n' % self.module)
318 doctest.DocTestSuite(self.module).run(result)
320 result.addError(self, sys.exc_info())
321 result.stopTest(self)
327 class CythonUnitTestCase(CythonCompileTestCase):
328 def shortDescription(self):
329 return "compiling (%s) tests in %s" % (self.language, self.module)
331 def run(self, result=None):
333 result = self.defaultTestResult()
334 result.startTest(self)
337 self.runCompileTest()
338 sys.stderr.write('running tests in %s ...\n' % self.module)
339 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
341 result.addError(self, sys.exc_info())
342 result.stopTest(self)
348 def collect_unittests(path, module_prefix, suite, selectors):
349 def file_matches(filename):
350 return filename.startswith("Test") and filename.endswith(".py")
352 def package_matches(dirname):
353 return dirname == "Tests"
355 loader = unittest.TestLoader()
359 for dirpath, dirnames, filenames in os.walk(path):
360 if dirpath != path and "__init__.py" not in filenames:
361 skipped_dirs.append(dirpath + os.path.sep)
364 for dir in skipped_dirs:
365 if dirpath.startswith(dir):
369 parentname = os.path.split(dirpath)[-1]
370 if package_matches(parentname):
373 filepath = os.path.join(dirpath, f)[:-len(".py")]
374 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
375 if not [ 1 for match in selectors if match(modulename) ]:
377 module = __import__(modulename)
378 for x in modulename.split('.')[1:]:
379 module = getattr(module, x)
380 suite.addTests([loader.loadTestsFromModule(module)])
382 def collect_doctests(path, module_prefix, suite, selectors):
383 def package_matches(dirname):
384 return dirname not in ("Mac", "Distutils", "Plex")
385 def file_matches(filename):
386 return (filename.endswith(".py") and not ('~' in filename
387 or '#' in filename or filename.startswith('.')))
388 import doctest, types
389 for dirpath, dirnames, filenames in os.walk(path):
390 parentname = os.path.split(dirpath)[-1]
391 if package_matches(parentname):
394 if not f.endswith('.py'): continue
395 filepath = os.path.join(dirpath, f)[:-len(".py")]
396 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
397 if not [ 1 for match in selectors if match(modulename) ]:
399 module = __import__(modulename)
400 for x in modulename.split('.')[1:]:
401 module = getattr(module, x)
402 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
404 suite.addTest(doctest.DocTestSuite(module))
405 except ValueError: # no tests
408 class MissingDependencyExcluder:
409 def __init__(self, deps):
410 # deps: { module name : matcher func }
411 self.exclude_matchers = []
412 for mod, matcher in deps.items():
416 self.exclude_matchers.append(matcher)
417 self.tests_missing_deps = []
418 def __call__(self, testname):
419 for matcher in self.exclude_matchers:
420 if matcher(testname):
421 self.tests_missing_deps.append(testname)
425 class VersionDependencyExcluder:
426 def __init__(self, deps):
427 # deps: { version : matcher func }
428 from sys import version_info
429 self.exclude_matchers = []
430 for ver, matcher in deps.items():
431 if version_info < ver:
432 self.exclude_matchers.append(matcher)
433 self.tests_missing_deps = []
434 def __call__(self, testname):
435 for matcher in self.exclude_matchers:
436 if matcher(testname):
437 self.tests_missing_deps.append(testname)
441 if __name__ == '__main__':
442 from optparse import OptionParser
443 parser = OptionParser()
444 parser.add_option("--no-cleanup", dest="cleanup_workdir",
445 action="store_false", default=True,
446 help="do not delete the generated C files (allows passing --no-cython on next run)")
447 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
448 action="store_false", default=True,
449 help="do not delete the generated shared libary files (allows manual module experimentation)")
450 parser.add_option("--no-cython", dest="with_cython",
451 action="store_false", default=True,
452 help="do not run the Cython compiler, only the C compiler")
453 parser.add_option("--no-c", dest="use_c",
454 action="store_false", default=True,
455 help="do not test C compilation")
456 parser.add_option("--no-cpp", dest="use_cpp",
457 action="store_false", default=True,
458 help="do not test C++ compilation")
459 parser.add_option("--no-unit", dest="unittests",
460 action="store_false", default=True,
461 help="do not run the unit tests")
462 parser.add_option("--no-doctest", dest="doctests",
463 action="store_false", default=True,
464 help="do not run the doctests")
465 parser.add_option("--no-file", dest="filetests",
466 action="store_false", default=True,
467 help="do not run the file based tests")
468 parser.add_option("--no-pyregr", dest="pyregr",
469 action="store_false", default=True,
470 help="do not run the regression tests of CPython in tests/pyregr/")
471 parser.add_option("--cython-only", dest="cython_only",
472 action="store_true", default=False,
473 help="only compile pyx to c, do not run C compiler or run the tests")
474 parser.add_option("--sys-pyregr", dest="system_pyregr",
475 action="store_true", default=False,
476 help="run the regression tests of the CPython installation")
477 parser.add_option("-x", "--exclude", dest="exclude",
478 action="append", metavar="PATTERN",
479 help="exclude tests matching the PATTERN")
480 parser.add_option("-C", "--coverage", dest="coverage",
481 action="store_true", default=False,
482 help="collect source coverage data for the Compiler")
483 parser.add_option("-A", "--annotate", dest="annotate_source",
484 action="store_true", default=True,
485 help="generate annotated HTML versions of the test source files")
486 parser.add_option("--no-annotate", dest="annotate_source",
487 action="store_false",
488 help="do not generate annotated HTML versions of the test source files")
489 parser.add_option("-v", "--verbose", dest="verbosity",
490 action="count", default=0,
491 help="display test progress, pass twice to print test names")
493 options, cmd_args = parser.parse_args()
495 if sys.version_info[0] >= 3:
496 # make sure we do not import (or run) Cython itself
497 options.doctests = False
498 options.with_cython = False
499 options.unittests = False
500 options.pyregr = False
507 WITH_CYTHON = options.with_cython
510 from Cython.Compiler.Main import \
511 CompilationOptions, \
512 default_options as pyrex_default_options, \
513 compile as cython_compile
514 from Cython.Compiler import Errors
515 Errors.LEVEL = 0 # show all warnings
518 ROOTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), 'tests')
519 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
520 UNITTEST_MODULE = "Cython"
521 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
523 if os.path.exists(WORKDIR):
524 shutil.rmtree(WORKDIR, ignore_errors=True)
525 if not os.path.exists(WORKDIR):
529 from Cython.Compiler.Version import version
530 sys.stderr.write("Running tests against Cython %s\n" % version)
532 sys.stderr.write("Running tests without Cython.\n")
533 sys.stderr.write("Python %s\n" % sys.version)
534 sys.stderr.write("\n")
537 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
539 selectors = [ lambda x:True ]
541 # Chech which external modules are not present and exclude tests
542 # which depends on them (by prefix)
544 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
545 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
546 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
549 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
553 languages.append('c')
555 languages.append('cpp')
557 test_suite = unittest.TestSuite()
559 if options.unittests:
560 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
563 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
565 if options.filetests and languages:
566 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
567 options.annotate_source, options.cleanup_workdir,
568 options.cleanup_sharedlibs, options.pyregr,
569 options.cython_only, languages)
570 test_suite.addTest(filetests.build_suite())
572 if options.system_pyregr and languages:
573 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
574 options.annotate_source, options.cleanup_workdir,
575 options.cleanup_sharedlibs, True,
576 options.cython_only, languages)
578 filetests.handle_directory(
579 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
582 unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
586 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
587 modules = [ module for name, module in sys.modules.items()
588 if module is not None and
589 name.startswith('Cython.Compiler.') and
590 name[len('Cython.Compiler.'):] not in ignored_modules ]
591 coverage.report(modules, show_missing=0)
593 if missing_dep_excluder.tests_missing_deps:
594 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
595 for test in missing_dep_excluder.tests_missing_deps:
596 sys.stderr.write(" %s\n" % test)