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 if 'cpp' in module and 'c' in languages:
151 languages = list(languages)
152 languages.remove('c')
153 tests = [ self.build_test(test_class, path, workdir, module,
154 language, expect_errors)
155 for language in languages ]
158 def build_test(self, test_class, path, workdir, module,
159 language, expect_errors):
160 workdir = os.path.join(workdir, language)
161 if not os.path.exists(workdir):
163 return test_class(path, workdir, module,
165 expect_errors=expect_errors,
166 annotate=self.annotate,
167 cleanup_workdir=self.cleanup_workdir,
168 cleanup_sharedlibs=self.cleanup_sharedlibs,
169 cython_only=self.cython_only)
171 class CythonCompileTestCase(unittest.TestCase):
172 def __init__(self, directory, workdir, module, language='c',
173 expect_errors=False, annotate=False, cleanup_workdir=True,
174 cleanup_sharedlibs=True, cython_only=False):
175 self.directory = directory
176 self.workdir = workdir
178 self.language = language
179 self.expect_errors = expect_errors
180 self.annotate = annotate
181 self.cleanup_workdir = cleanup_workdir
182 self.cleanup_sharedlibs = cleanup_sharedlibs
183 self.cython_only = cython_only
184 unittest.TestCase.__init__(self)
186 def shortDescription(self):
187 return "compiling (%s) %s" % (self.language, self.module)
190 if self.workdir not in sys.path:
191 sys.path.insert(0, self.workdir)
195 sys.path.remove(self.workdir)
199 del sys.modules[self.module]
202 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
203 cleanup_lib_files = self.cleanup_sharedlibs
204 if os.path.exists(self.workdir):
205 for rmfile in os.listdir(self.workdir):
206 if not cleanup_c_files:
207 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
209 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
211 if self.annotate and rmfile.endswith(".html"):
214 rmfile = os.path.join(self.workdir, rmfile)
215 if os.path.isdir(rmfile):
216 shutil.rmtree(rmfile, ignore_errors=True)
222 os.makedirs(self.workdir)
225 self.runCompileTest()
227 def runCompileTest(self):
228 self.compile(self.directory, self.module, self.workdir,
229 self.directory, self.expect_errors, self.annotate)
231 def find_module_source_file(self, source_file):
232 if not os.path.exists(source_file):
233 source_file = source_file[:-1]
236 def build_target_filename(self, module_name):
237 target = '%s.%s' % (module_name, self.language)
240 def split_source_and_output(self, directory, module, workdir):
241 source_file = os.path.join(directory, module) + '.pyx'
242 source_and_output = open(
243 self.find_module_source_file(source_file), 'rU')
244 out = open(os.path.join(workdir, module + '.pyx'), 'w')
245 for line in source_and_output:
247 if line.startswith("_ERRORS"):
253 geterrors = out.geterrors
254 except AttributeError:
259 def run_cython(self, directory, module, targetdir, incdir, annotate):
260 include_dirs = INCLUDE_DIRS[:]
262 include_dirs.append(incdir)
263 source = self.find_module_source_file(
264 os.path.join(directory, module + '.pyx'))
265 target = os.path.join(targetdir, self.build_target_filename(module))
266 options = CompilationOptions(
267 pyrex_default_options,
268 include_path = include_dirs,
269 output_file = target,
271 use_listing_file = False,
272 cplus = self.language == 'cpp',
273 generate_pxi = False)
274 cython_compile(source, options=options,
275 full_module_name=module)
277 def run_distutils(self, module, workdir, incdir):
281 build_extension = build_ext(distutils_distro)
282 build_extension.include_dirs = INCLUDE_DIRS[:]
284 build_extension.include_dirs.append(incdir)
285 build_extension.finalize_options()
286 ext_include_dirs = []
287 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
289 ext_include_dirs += get_additional_include_dirs()
290 extension = Extension(
292 sources = [self.build_target_filename(module)],
293 include_dirs = ext_include_dirs,
294 extra_compile_args = CFLAGS,
296 if self.language == 'cpp':
297 extension.language = 'c++'
298 build_extension.extensions = [extension]
299 build_extension.build_temp = workdir
300 build_extension.build_lib = workdir
301 build_extension.run()
305 def compile(self, directory, module, workdir, incdir,
306 expect_errors, annotate):
307 expected_errors = errors = ()
309 expected_errors = self.split_source_and_output(
310 directory, module, workdir)
314 old_stderr = sys.stderr
316 sys.stderr = ErrorWriter()
317 self.run_cython(directory, module, workdir, incdir, annotate)
318 errors = sys.stderr.geterrors()
320 sys.stderr = old_stderr
322 if errors or expected_errors:
323 for expected, error in zip(expected_errors, errors):
324 self.assertEquals(expected, error)
325 if len(errors) < len(expected_errors):
326 expected_error = expected_errors[len(errors)]
327 self.assertEquals(expected_error, None)
328 elif len(errors) > len(expected_errors):
329 unexpected_error = errors[len(expected_errors)]
330 self.assertEquals(None, unexpected_error)
332 if not self.cython_only:
333 self.run_distutils(module, workdir, incdir)
335 class CythonRunTestCase(CythonCompileTestCase):
336 def shortDescription(self):
337 return "compiling (%s) and running %s" % (self.language, self.module)
339 def run(self, result=None):
341 result = self.defaultTestResult()
342 result.startTest(self)
345 self.runCompileTest()
346 if not self.cython_only:
347 doctest.DocTestSuite(self.module).run(result)
349 result.addError(self, sys.exc_info())
350 result.stopTest(self)
356 class CythonUnitTestCase(CythonCompileTestCase):
357 def shortDescription(self):
358 return "compiling (%s) tests in %s" % (self.language, self.module)
360 def run(self, result=None):
362 result = self.defaultTestResult()
363 result.startTest(self)
366 self.runCompileTest()
367 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
369 result.addError(self, sys.exc_info())
370 result.stopTest(self)
376 def collect_unittests(path, module_prefix, suite, selectors):
377 def file_matches(filename):
378 return filename.startswith("Test") and filename.endswith(".py")
380 def package_matches(dirname):
381 return dirname == "Tests"
383 loader = unittest.TestLoader()
387 for dirpath, dirnames, filenames in os.walk(path):
388 if dirpath != path and "__init__.py" not in filenames:
389 skipped_dirs.append(dirpath + os.path.sep)
392 for dir in skipped_dirs:
393 if dirpath.startswith(dir):
397 parentname = os.path.split(dirpath)[-1]
398 if package_matches(parentname):
401 filepath = os.path.join(dirpath, f)[:-len(".py")]
402 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
403 if not [ 1 for match in selectors if match(modulename) ]:
405 module = __import__(modulename)
406 for x in modulename.split('.')[1:]:
407 module = getattr(module, x)
408 suite.addTests([loader.loadTestsFromModule(module)])
410 def collect_doctests(path, module_prefix, suite, selectors):
411 def package_matches(dirname):
412 return dirname not in ("Mac", "Distutils", "Plex")
413 def file_matches(filename):
414 return (filename.endswith(".py") and not ('~' in filename
415 or '#' in filename or filename.startswith('.')))
416 import doctest, types
417 for dirpath, dirnames, filenames in os.walk(path):
418 parentname = os.path.split(dirpath)[-1]
419 if package_matches(parentname):
422 if not f.endswith('.py'): continue
423 filepath = os.path.join(dirpath, f)[:-len(".py")]
424 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
425 if not [ 1 for match in selectors if match(modulename) ]:
427 module = __import__(modulename)
428 for x in modulename.split('.')[1:]:
429 module = getattr(module, x)
430 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
432 suite.addTest(doctest.DocTestSuite(module))
433 except ValueError: # no tests
436 class MissingDependencyExcluder:
437 def __init__(self, deps):
438 # deps: { module name : matcher func }
439 self.exclude_matchers = []
440 for mod, matcher in deps.items():
444 self.exclude_matchers.append(matcher)
445 self.tests_missing_deps = []
446 def __call__(self, testname):
447 for matcher in self.exclude_matchers:
448 if matcher(testname):
449 self.tests_missing_deps.append(testname)
453 class VersionDependencyExcluder:
454 def __init__(self, deps):
455 # deps: { version : matcher func }
456 from sys import version_info
457 self.exclude_matchers = []
458 for ver, matcher in deps.items():
459 if version_info < ver:
460 self.exclude_matchers.append(matcher)
461 self.tests_missing_deps = []
462 def __call__(self, testname):
463 for matcher in self.exclude_matchers:
464 if matcher(testname):
465 self.tests_missing_deps.append(testname)
469 if __name__ == '__main__':
470 from optparse import OptionParser
471 parser = OptionParser()
472 parser.add_option("--no-cleanup", dest="cleanup_workdir",
473 action="store_false", default=True,
474 help="do not delete the generated C files (allows passing --no-cython on next run)")
475 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
476 action="store_false", default=True,
477 help="do not delete the generated shared libary files (allows manual module experimentation)")
478 parser.add_option("--no-cython", dest="with_cython",
479 action="store_false", default=True,
480 help="do not run the Cython compiler, only the C compiler")
481 parser.add_option("--no-c", dest="use_c",
482 action="store_false", default=True,
483 help="do not test C compilation")
484 parser.add_option("--no-cpp", dest="use_cpp",
485 action="store_false", default=True,
486 help="do not test C++ compilation")
487 parser.add_option("--no-unit", dest="unittests",
488 action="store_false", default=True,
489 help="do not run the unit tests")
490 parser.add_option("--no-doctest", dest="doctests",
491 action="store_false", default=True,
492 help="do not run the doctests")
493 parser.add_option("--no-file", dest="filetests",
494 action="store_false", default=True,
495 help="do not run the file based tests")
496 parser.add_option("--no-pyregr", dest="pyregr",
497 action="store_false", default=True,
498 help="do not run the regression tests of CPython in tests/pyregr/")
499 parser.add_option("--cython-only", dest="cython_only",
500 action="store_true", default=False,
501 help="only compile pyx to c, do not run C compiler or run the tests")
502 parser.add_option("--no-refnanny", dest="with_refnanny",
503 action="store_false", default=True,
504 help="do not regression test reference counting")
505 parser.add_option("--sys-pyregr", dest="system_pyregr",
506 action="store_true", default=False,
507 help="run the regression tests of the CPython installation")
508 parser.add_option("-x", "--exclude", dest="exclude",
509 action="append", metavar="PATTERN",
510 help="exclude tests matching the PATTERN")
511 parser.add_option("-C", "--coverage", dest="coverage",
512 action="store_true", default=False,
513 help="collect source coverage data for the Compiler")
514 parser.add_option("-A", "--annotate", dest="annotate_source",
515 action="store_true", default=True,
516 help="generate annotated HTML versions of the test source files")
517 parser.add_option("--no-annotate", dest="annotate_source",
518 action="store_false",
519 help="do not generate annotated HTML versions of the test source files")
520 parser.add_option("-v", "--verbose", dest="verbosity",
521 action="count", default=0,
522 help="display test progress, pass twice to print test names")
523 parser.add_option("-T", "--ticket", dest="tickets",
525 help="a bug ticket number to run the respective test in 'tests/bugs'")
527 options, cmd_args = parser.parse_args()
529 if sys.version_info[0] >= 3:
530 # make sure we do not import (or run) Cython itself
531 options.doctests = False
532 options.with_cython = False
533 options.unittests = False
534 options.pyregr = False
541 WITH_CYTHON = options.with_cython
544 from Cython.Compiler.Main import \
545 CompilationOptions, \
546 default_options as pyrex_default_options, \
547 compile as cython_compile
548 from Cython.Compiler import Errors
549 Errors.LEVEL = 0 # show all warnings
552 ROOTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), 'tests')
553 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
554 UNITTEST_MODULE = "Cython"
555 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
557 if os.path.exists(WORKDIR):
558 for path in os.listdir(WORKDIR):
559 if path in ("support",): continue
560 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
561 if not os.path.exists(WORKDIR):
565 from Cython.Compiler.Version import version
566 sys.stderr.write("Running tests against Cython %s\n" % version)
567 from Cython.Compiler import DebugFlags
568 DebugFlags.debug_temp_code_comments = 1
570 sys.stderr.write("Running tests without Cython.\n")
571 sys.stderr.write("Python %s\n" % sys.version)
572 sys.stderr.write("\n")
574 if options.with_refnanny:
575 from pyximport.pyxbuild import pyx_to_dll
576 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
578 pyxbuild_dir=os.path.join(WORKDIR, "support"))
579 sys.path.insert(0, os.path.split(libpath)[0])
580 CFLAGS.append("-DCYTHON_REFNANNY")
584 for ticket_number in options.tickets:
586 cmd_args.append('bugs.*T%s$' % ticket_number)
588 for selector in cmd_args:
589 if selector.startswith('bugs'):
593 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
595 selectors = [ lambda x:True ]
597 # Chech which external modules are not present and exclude tests
598 # which depends on them (by prefix)
600 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
601 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
602 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
605 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
609 languages.append('c')
611 languages.append('cpp')
613 test_suite = unittest.TestSuite()
615 if options.unittests:
616 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
619 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
621 if options.filetests and languages:
622 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
623 options.annotate_source, options.cleanup_workdir,
624 options.cleanup_sharedlibs, options.pyregr,
625 options.cython_only, languages, test_bugs)
626 test_suite.addTest(filetests.build_suite())
628 if options.system_pyregr and languages:
629 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
630 options.annotate_source, options.cleanup_workdir,
631 options.cleanup_sharedlibs, True,
632 options.cython_only, languages)
634 filetests.handle_directory(
635 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
638 unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
642 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
643 modules = [ module for name, module in sys.modules.items()
644 if module is not None and
645 name.startswith('Cython.Compiler.') and
646 name[len('Cython.Compiler.'):] not in ignored_modules ]
647 coverage.report(modules, show_missing=0)
649 if missing_dep_excluder.tests_missing_deps:
650 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
651 for test in missing_dep_excluder.tests_missing_deps:
652 sys.stderr.write(" %s\n" % test)
654 if options.with_refnanny:
656 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))