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 doctest.DocTestSuite(self.module).run(result)
332 result.addError(self, sys.exc_info())
333 result.stopTest(self)
339 class CythonUnitTestCase(CythonCompileTestCase):
340 def shortDescription(self):
341 return "compiling (%s) tests in %s" % (self.language, self.module)
343 def run(self, result=None):
345 result = self.defaultTestResult()
346 result.startTest(self)
349 self.runCompileTest()
350 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
352 result.addError(self, sys.exc_info())
353 result.stopTest(self)
359 def collect_unittests(path, module_prefix, suite, selectors):
360 def file_matches(filename):
361 return filename.startswith("Test") and filename.endswith(".py")
363 def package_matches(dirname):
364 return dirname == "Tests"
366 loader = unittest.TestLoader()
370 for dirpath, dirnames, filenames in os.walk(path):
371 if dirpath != path and "__init__.py" not in filenames:
372 skipped_dirs.append(dirpath + os.path.sep)
375 for dir in skipped_dirs:
376 if dirpath.startswith(dir):
380 parentname = os.path.split(dirpath)[-1]
381 if package_matches(parentname):
384 filepath = os.path.join(dirpath, f)[:-len(".py")]
385 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
386 if not [ 1 for match in selectors if match(modulename) ]:
388 module = __import__(modulename)
389 for x in modulename.split('.')[1:]:
390 module = getattr(module, x)
391 suite.addTests([loader.loadTestsFromModule(module)])
393 def collect_doctests(path, module_prefix, suite, selectors):
394 def package_matches(dirname):
395 return dirname not in ("Mac", "Distutils", "Plex")
396 def file_matches(filename):
397 return (filename.endswith(".py") and not ('~' in filename
398 or '#' in filename or filename.startswith('.')))
399 import doctest, types
400 for dirpath, dirnames, filenames in os.walk(path):
401 parentname = os.path.split(dirpath)[-1]
402 if package_matches(parentname):
405 if not f.endswith('.py'): continue
406 filepath = os.path.join(dirpath, f)[:-len(".py")]
407 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
408 if not [ 1 for match in selectors if match(modulename) ]:
410 module = __import__(modulename)
411 for x in modulename.split('.')[1:]:
412 module = getattr(module, x)
413 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
415 suite.addTest(doctest.DocTestSuite(module))
416 except ValueError: # no tests
419 class MissingDependencyExcluder:
420 def __init__(self, deps):
421 # deps: { module name : matcher func }
422 self.exclude_matchers = []
423 for mod, matcher in deps.items():
427 self.exclude_matchers.append(matcher)
428 self.tests_missing_deps = []
429 def __call__(self, testname):
430 for matcher in self.exclude_matchers:
431 if matcher(testname):
432 self.tests_missing_deps.append(testname)
436 class VersionDependencyExcluder:
437 def __init__(self, deps):
438 # deps: { version : matcher func }
439 from sys import version_info
440 self.exclude_matchers = []
441 for ver, matcher in deps.items():
442 if version_info < ver:
443 self.exclude_matchers.append(matcher)
444 self.tests_missing_deps = []
445 def __call__(self, testname):
446 for matcher in self.exclude_matchers:
447 if matcher(testname):
448 self.tests_missing_deps.append(testname)
452 if __name__ == '__main__':
453 from optparse import OptionParser
454 parser = OptionParser()
455 parser.add_option("--no-cleanup", dest="cleanup_workdir",
456 action="store_false", default=True,
457 help="do not delete the generated C files (allows passing --no-cython on next run)")
458 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
459 action="store_false", default=True,
460 help="do not delete the generated shared libary files (allows manual module experimentation)")
461 parser.add_option("--no-cython", dest="with_cython",
462 action="store_false", default=True,
463 help="do not run the Cython compiler, only the C compiler")
464 parser.add_option("--no-c", dest="use_c",
465 action="store_false", default=True,
466 help="do not test C compilation")
467 parser.add_option("--no-cpp", dest="use_cpp",
468 action="store_false", default=True,
469 help="do not test C++ compilation")
470 parser.add_option("--no-unit", dest="unittests",
471 action="store_false", default=True,
472 help="do not run the unit tests")
473 parser.add_option("--no-doctest", dest="doctests",
474 action="store_false", default=True,
475 help="do not run the doctests")
476 parser.add_option("--no-file", dest="filetests",
477 action="store_false", default=True,
478 help="do not run the file based tests")
479 parser.add_option("--no-pyregr", dest="pyregr",
480 action="store_false", default=True,
481 help="do not run the regression tests of CPython in tests/pyregr/")
482 parser.add_option("--cython-only", dest="cython_only",
483 action="store_true", default=False,
484 help="only compile pyx to c, do not run C compiler or run the tests")
485 parser.add_option("--no-refnanny", dest="with_refnanny",
486 action="store_false", default=(sys.version_info[0] < 3),
487 help="do not regression test reference counting")
488 parser.add_option("--sys-pyregr", dest="system_pyregr",
489 action="store_true", default=False,
490 help="run the regression tests of the CPython installation")
491 parser.add_option("-x", "--exclude", dest="exclude",
492 action="append", metavar="PATTERN",
493 help="exclude tests matching the PATTERN")
494 parser.add_option("-C", "--coverage", dest="coverage",
495 action="store_true", default=False,
496 help="collect source coverage data for the Compiler")
497 parser.add_option("-A", "--annotate", dest="annotate_source",
498 action="store_true", default=True,
499 help="generate annotated HTML versions of the test source files")
500 parser.add_option("--no-annotate", dest="annotate_source",
501 action="store_false",
502 help="do not generate annotated HTML versions of the test source files")
503 parser.add_option("-v", "--verbose", dest="verbosity",
504 action="count", default=0,
505 help="display test progress, pass twice to print test names")
506 parser.add_option("-T", "--ticket", dest="tickets",
508 help="a bug ticket number to run the respective test in 'tests/bugs'")
510 options, cmd_args = parser.parse_args()
512 if sys.version_info[0] >= 3:
513 # make sure we do not import (or run) Cython itself
514 options.doctests = False
515 options.with_cython = False
516 options.unittests = False
517 options.pyregr = False
524 WITH_CYTHON = options.with_cython
527 from Cython.Compiler.Main import \
528 CompilationOptions, \
529 default_options as pyrex_default_options, \
530 compile as cython_compile
531 from Cython.Compiler import Errors
532 Errors.LEVEL = 0 # show all warnings
535 ROOTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), 'tests')
536 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
537 UNITTEST_MODULE = "Cython"
538 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
540 if os.path.exists(WORKDIR):
541 for path in os.listdir(WORKDIR):
542 if path in ("support",): continue
543 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
544 if not os.path.exists(WORKDIR):
548 from Cython.Compiler.Version import version
549 sys.stderr.write("Running tests against Cython %s\n" % version)
551 sys.stderr.write("Running tests without Cython.\n")
552 sys.stderr.write("Python %s\n" % sys.version)
553 sys.stderr.write("\n")
555 if options.with_refnanny:
556 from pyximport.pyxbuild import pyx_to_dll
557 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
559 pyxbuild_dir=os.path.join(WORKDIR, "support"))
560 sys.path.insert(0, os.path.split(libpath)[0])
561 CFLAGS.append("-DCYTHON_REFNANNY")
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:
637 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))