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
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()
29 class build_ext(_build_ext):
30 def build_extension(self, ext):
31 if ext.language == 'c++':
33 self.compiler.compiler_so.remove('-Wstrict-prototypes')
36 _build_ext.build_extension(self, ext)
38 class ErrorWriter(object):
39 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
42 self.write = self.output.append
44 def _collect(self, collect_errors, collect_warnings):
45 s = ''.join(self.output)
47 for line in s.split('\n'):
48 match = self.match_error(line)
50 is_warning, line, column, message = match.groups()
51 if (is_warning and collect_warnings) or \
52 (not is_warning and collect_errors):
53 result.append( (int(line), int(column), message.strip()) )
55 return [ "%d:%d: %s" % values for values in result ]
58 return self._collect(True, False)
60 def getwarnings(self):
61 return self._collect(False, True)
64 return self._collect(True, True)
66 class TestBuilder(object):
67 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
68 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
69 languages, test_bugs):
70 self.rootdir = rootdir
71 self.workdir = workdir
72 self.selectors = selectors
73 self.exclude_selectors = exclude_selectors
74 self.annotate = annotate
75 self.cleanup_workdir = cleanup_workdir
76 self.cleanup_sharedlibs = cleanup_sharedlibs
77 self.with_pyregr = with_pyregr
78 self.cython_only = cython_only
79 self.languages = languages
80 self.test_bugs = test_bugs
82 def build_suite(self):
83 suite = unittest.TestSuite()
85 if self.test_bugs and 'bugs' not in test_dirs:
86 test_dirs.append('bugs')
87 filenames = os.listdir(self.rootdir)
89 for filename in filenames:
90 if not WITH_CYTHON and filename == "errors":
91 # we won't get any errors without running Cython
93 path = os.path.join(self.rootdir, filename)
94 if os.path.isdir(path) and filename in test_dirs:
95 if filename == 'pyregr' and not self.with_pyregr:
98 self.handle_directory(path, filename))
101 def handle_directory(self, path, context):
102 workdir = os.path.join(self.workdir, context)
103 if not os.path.exists(workdir):
106 expect_errors = (context == 'errors')
107 suite = unittest.TestSuite()
108 filenames = os.listdir(path)
110 for filename in filenames:
111 if not (filename.endswith(".pyx") or filename.endswith(".py")):
113 if filename.startswith('.'): continue # certain emacs backup files
114 if context == 'pyregr' and not filename.startswith('test_'):
116 module = os.path.splitext(filename)[0]
117 fqmodule = "%s.%s" % (context, module)
118 if not [ 1 for match in self.selectors
119 if match(fqmodule) ]:
121 if self.exclude_selectors:
122 if [1 for match in self.exclude_selectors if match(fqmodule)]:
124 if context in TEST_RUN_DIRS:
125 if module.startswith("test_"):
126 test_class = CythonUnitTestCase
128 test_class = CythonRunTestCase
130 test_class = CythonCompileTestCase
131 for test in self.build_tests(test_class, path, workdir,
132 module, expect_errors):
136 def build_tests(self, test_class, path, workdir, module, expect_errors):
138 languages = self.languages[:1]
140 languages = self.languages
141 tests = [ self.build_test(test_class, path, workdir, module,
142 language, expect_errors)
143 for language in languages ]
146 def build_test(self, test_class, path, workdir, module,
147 language, expect_errors):
148 workdir = os.path.join(workdir, language)
149 if not os.path.exists(workdir):
151 return test_class(path, workdir, module,
153 expect_errors=expect_errors,
154 annotate=self.annotate,
155 cleanup_workdir=self.cleanup_workdir,
156 cleanup_sharedlibs=self.cleanup_sharedlibs,
157 cython_only=self.cython_only)
159 class CythonCompileTestCase(unittest.TestCase):
160 def __init__(self, directory, workdir, module, language='c',
161 expect_errors=False, annotate=False, cleanup_workdir=True,
162 cleanup_sharedlibs=True, cython_only=False):
163 self.directory = directory
164 self.workdir = workdir
166 self.language = language
167 self.expect_errors = expect_errors
168 self.annotate = annotate
169 self.cleanup_workdir = cleanup_workdir
170 self.cleanup_sharedlibs = cleanup_sharedlibs
171 self.cython_only = cython_only
172 unittest.TestCase.__init__(self)
174 def shortDescription(self):
175 return "compiling (%s) %s" % (self.language, self.module)
178 if self.workdir not in sys.path:
179 sys.path.insert(0, self.workdir)
183 sys.path.remove(self.workdir)
187 del sys.modules[self.module]
190 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
191 cleanup_lib_files = self.cleanup_sharedlibs
192 if os.path.exists(self.workdir):
193 for rmfile in os.listdir(self.workdir):
194 if not cleanup_c_files:
195 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
197 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
199 if self.annotate and rmfile.endswith(".html"):
202 rmfile = os.path.join(self.workdir, rmfile)
203 if os.path.isdir(rmfile):
204 shutil.rmtree(rmfile, ignore_errors=True)
210 os.makedirs(self.workdir)
213 self.runCompileTest()
215 def runCompileTest(self):
216 self.compile(self.directory, self.module, self.workdir,
217 self.directory, self.expect_errors, self.annotate)
219 def find_module_source_file(self, source_file):
220 if not os.path.exists(source_file):
221 source_file = source_file[:-1]
224 def build_target_filename(self, module_name):
225 target = '%s.%s' % (module_name, self.language)
228 def split_source_and_output(self, directory, module, workdir):
229 source_file = os.path.join(directory, module) + '.pyx'
230 source_and_output = open(
231 self.find_module_source_file(source_file), 'rU')
232 out = open(os.path.join(workdir, module + '.pyx'), 'w')
233 for line in source_and_output:
235 if line.startswith("_ERRORS"):
241 geterrors = out.geterrors
242 except AttributeError:
247 def run_cython(self, directory, module, targetdir, incdir, annotate):
248 include_dirs = INCLUDE_DIRS[:]
250 include_dirs.append(incdir)
251 source = self.find_module_source_file(
252 os.path.join(directory, module + '.pyx'))
253 target = os.path.join(targetdir, self.build_target_filename(module))
254 options = CompilationOptions(
255 pyrex_default_options,
256 include_path = include_dirs,
257 output_file = target,
259 use_listing_file = False,
260 cplus = self.language == 'cpp',
261 generate_pxi = False)
262 cython_compile(source, options=options,
263 full_module_name=module)
265 def run_distutils(self, module, workdir, incdir):
269 build_extension = build_ext(distutils_distro)
270 build_extension.include_dirs = INCLUDE_DIRS[:]
272 build_extension.include_dirs.append(incdir)
273 build_extension.finalize_options()
274 extension = Extension(
276 sources = [self.build_target_filename(module)],
277 extra_compile_args = CFLAGS,
279 if self.language == 'cpp':
280 extension.language = 'c++'
281 build_extension.extensions = [extension]
282 build_extension.build_temp = workdir
283 build_extension.build_lib = workdir
284 build_extension.run()
288 def compile(self, directory, module, workdir, incdir,
289 expect_errors, annotate):
290 expected_errors = errors = ()
292 expected_errors = self.split_source_and_output(
293 directory, module, workdir)
297 old_stderr = sys.stderr
299 sys.stderr = ErrorWriter()
300 self.run_cython(directory, module, workdir, incdir, annotate)
301 errors = sys.stderr.geterrors()
303 sys.stderr = old_stderr
305 if errors or expected_errors:
306 for expected, error in zip(expected_errors, errors):
307 self.assertEquals(expected, error)
308 if len(errors) < len(expected_errors):
309 expected_error = expected_errors[len(errors)]
310 self.assertEquals(expected_error, None)
311 elif len(errors) > len(expected_errors):
312 unexpected_error = errors[len(expected_errors)]
313 self.assertEquals(None, unexpected_error)
315 if not self.cython_only:
316 self.run_distutils(module, workdir, incdir)
318 class CythonRunTestCase(CythonCompileTestCase):
319 def shortDescription(self):
320 return "compiling (%s) and running %s" % (self.language, self.module)
322 def run(self, result=None):
324 result = self.defaultTestResult()
325 result.startTest(self)
328 self.runCompileTest()
329 if not self.cython_only:
330 sys.stderr.write('running doctests in %s ...\n' % self.module)
331 doctest.DocTestSuite(self.module).run(result)
333 result.addError(self, sys.exc_info())
334 result.stopTest(self)
340 class CythonUnitTestCase(CythonCompileTestCase):
341 def shortDescription(self):
342 return "compiling (%s) tests in %s" % (self.language, self.module)
344 def run(self, result=None):
346 result = self.defaultTestResult()
347 result.startTest(self)
350 self.runCompileTest()
351 sys.stderr.write('running tests in %s ...\n' % self.module)
352 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
354 result.addError(self, sys.exc_info())
355 result.stopTest(self)
361 def collect_unittests(path, module_prefix, suite, selectors):
362 def file_matches(filename):
363 return filename.startswith("Test") and filename.endswith(".py")
365 def package_matches(dirname):
366 return dirname == "Tests"
368 loader = unittest.TestLoader()
372 for dirpath, dirnames, filenames in os.walk(path):
373 if dirpath != path and "__init__.py" not in filenames:
374 skipped_dirs.append(dirpath + os.path.sep)
377 for dir in skipped_dirs:
378 if dirpath.startswith(dir):
382 parentname = os.path.split(dirpath)[-1]
383 if package_matches(parentname):
386 filepath = os.path.join(dirpath, f)[:-len(".py")]
387 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
388 if not [ 1 for match in selectors if match(modulename) ]:
390 module = __import__(modulename)
391 for x in modulename.split('.')[1:]:
392 module = getattr(module, x)
393 suite.addTests([loader.loadTestsFromModule(module)])
395 def collect_doctests(path, module_prefix, suite, selectors):
396 def package_matches(dirname):
397 return dirname not in ("Mac", "Distutils", "Plex")
398 def file_matches(filename):
399 return (filename.endswith(".py") and not ('~' in filename
400 or '#' in filename or filename.startswith('.')))
401 import doctest, types
402 for dirpath, dirnames, filenames in os.walk(path):
403 parentname = os.path.split(dirpath)[-1]
404 if package_matches(parentname):
407 if not f.endswith('.py'): continue
408 filepath = os.path.join(dirpath, f)[:-len(".py")]
409 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
410 if not [ 1 for match in selectors if match(modulename) ]:
412 module = __import__(modulename)
413 for x in modulename.split('.')[1:]:
414 module = getattr(module, x)
415 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
417 suite.addTest(doctest.DocTestSuite(module))
418 except ValueError: # no tests
421 class MissingDependencyExcluder:
422 def __init__(self, deps):
423 # deps: { module name : matcher func }
424 self.exclude_matchers = []
425 for mod, matcher in deps.items():
429 self.exclude_matchers.append(matcher)
430 self.tests_missing_deps = []
431 def __call__(self, testname):
432 for matcher in self.exclude_matchers:
433 if matcher(testname):
434 self.tests_missing_deps.append(testname)
438 class VersionDependencyExcluder:
439 def __init__(self, deps):
440 # deps: { version : matcher func }
441 from sys import version_info
442 self.exclude_matchers = []
443 for ver, matcher in deps.items():
444 if version_info < ver:
445 self.exclude_matchers.append(matcher)
446 self.tests_missing_deps = []
447 def __call__(self, testname):
448 for matcher in self.exclude_matchers:
449 if matcher(testname):
450 self.tests_missing_deps.append(testname)
454 if __name__ == '__main__':
455 from optparse import OptionParser
456 parser = OptionParser()
457 parser.add_option("--no-cleanup", dest="cleanup_workdir",
458 action="store_false", default=True,
459 help="do not delete the generated C files (allows passing --no-cython on next run)")
460 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
461 action="store_false", default=True,
462 help="do not delete the generated shared libary files (allows manual module experimentation)")
463 parser.add_option("--no-cython", dest="with_cython",
464 action="store_false", default=True,
465 help="do not run the Cython compiler, only the C compiler")
466 parser.add_option("--no-c", dest="use_c",
467 action="store_false", default=True,
468 help="do not test C compilation")
469 parser.add_option("--no-cpp", dest="use_cpp",
470 action="store_false", default=True,
471 help="do not test C++ compilation")
472 parser.add_option("--no-unit", dest="unittests",
473 action="store_false", default=True,
474 help="do not run the unit tests")
475 parser.add_option("--no-doctest", dest="doctests",
476 action="store_false", default=True,
477 help="do not run the doctests")
478 parser.add_option("--no-file", dest="filetests",
479 action="store_false", default=True,
480 help="do not run the file based tests")
481 parser.add_option("--no-pyregr", dest="pyregr",
482 action="store_false", default=True,
483 help="do not run the regression tests of CPython in tests/pyregr/")
484 parser.add_option("--cython-only", dest="cython_only",
485 action="store_true", default=False,
486 help="only compile pyx to c, do not run C compiler or run the tests")
487 parser.add_option("--refnanny", dest="with_refnanny",
488 action="store_true", default=False,
489 help="also test that Cython-generated code does correct reference counting")
490 parser.add_option("--sys-pyregr", dest="system_pyregr",
491 action="store_true", default=False,
492 help="run the regression tests of the CPython installation")
493 parser.add_option("-x", "--exclude", dest="exclude",
494 action="append", metavar="PATTERN",
495 help="exclude tests matching the PATTERN")
496 parser.add_option("-C", "--coverage", dest="coverage",
497 action="store_true", default=False,
498 help="collect source coverage data for the Compiler")
499 parser.add_option("-A", "--annotate", dest="annotate_source",
500 action="store_true", default=True,
501 help="generate annotated HTML versions of the test source files")
502 parser.add_option("--no-annotate", dest="annotate_source",
503 action="store_false",
504 help="do not generate annotated HTML versions of the test source files")
505 parser.add_option("-v", "--verbose", dest="verbosity",
506 action="count", default=0,
507 help="display test progress, pass twice to print test names")
508 parser.add_option("-T", "--ticket", dest="tickets",
510 help="a bug ticket number to run the respective test in 'tests/bugs'")
512 options, cmd_args = parser.parse_args()
514 if sys.version_info[0] >= 3:
515 # make sure we do not import (or run) Cython itself
516 options.doctests = False
517 options.with_cython = False
518 options.unittests = False
519 options.pyregr = False
526 WITH_CYTHON = options.with_cython
529 from Cython.Compiler.Main import \
530 CompilationOptions, \
531 default_options as pyrex_default_options, \
532 compile as cython_compile
533 from Cython.Compiler import Errors
534 Errors.LEVEL = 0 # show all warnings
536 if options.with_refnanny:
538 ctypes.PyDLL("Cython/Runtime/refnanny.so", mode=ctypes.RTLD_GLOBAL)
539 sys.path.append("Cython/Runtime")
542 CFLAGS.append("-DCYTHON_REFNANNY")
545 ROOTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), 'tests')
546 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
547 UNITTEST_MODULE = "Cython"
548 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
550 if os.path.exists(WORKDIR):
551 shutil.rmtree(WORKDIR, ignore_errors=True)
552 if not os.path.exists(WORKDIR):
556 from Cython.Compiler.Version import version
557 sys.stderr.write("Running tests against Cython %s\n" % version)
559 sys.stderr.write("Running tests without Cython.\n")
560 sys.stderr.write("Python %s\n" % sys.version)
561 sys.stderr.write("\n")
565 for ticket_number in options.tickets:
567 cmd_args.append('bugs.*T%s$' % ticket_number)
569 for selector in cmd_args:
570 if selector.startswith('bugs'):
574 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
576 selectors = [ lambda x:True ]
578 # Chech which external modules are not present and exclude tests
579 # which depends on them (by prefix)
581 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
582 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
583 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
586 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
590 languages.append('c')
592 languages.append('cpp')
594 test_suite = unittest.TestSuite()
596 if options.unittests:
597 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
600 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
602 if options.filetests and languages:
603 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
604 options.annotate_source, options.cleanup_workdir,
605 options.cleanup_sharedlibs, options.pyregr,
606 options.cython_only, languages, test_bugs)
607 test_suite.addTest(filetests.build_suite())
609 if options.system_pyregr and languages:
610 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
611 options.annotate_source, options.cleanup_workdir,
612 options.cleanup_sharedlibs, True,
613 options.cython_only, languages)
615 filetests.handle_directory(
616 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
619 unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
623 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
624 modules = [ module for name, module in sys.modules.items()
625 if module is not None and
626 name.startswith('Cython.Compiler.') and
627 name[len('Cython.Compiler.'):] not in ignored_modules ]
628 coverage.report(modules, show_missing=0)
630 if missing_dep_excluder.tests_missing_deps:
631 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
632 for test in missing_dep_excluder.tests_missing_deps:
633 sys.stderr.write(" %s\n" % test)
635 if options.with_refnanny:
636 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))