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:
322 for expected, error in zip(expected_errors, errors):
323 self.assertEquals(expected, error)
324 if len(errors) < len(expected_errors):
325 expected_error = expected_errors[len(errors)]
326 self.assertEquals(expected_error, None)
327 elif len(errors) > len(expected_errors):
328 unexpected_error = errors[len(expected_errors)]
329 self.assertEquals(None, unexpected_error)
330 except AssertionError:
331 print("\n=== Expected errors: ===")
332 print('\n'.join(expected_errors))
333 print("\n\n=== Got errors: ===")
334 print('\n'.join(errors))
338 if not self.cython_only:
339 self.run_distutils(module, workdir, incdir)
341 class CythonRunTestCase(CythonCompileTestCase):
342 def shortDescription(self):
343 return "compiling (%s) and running %s" % (self.language, self.module)
345 def run(self, result=None):
347 result = self.defaultTestResult()
348 result.startTest(self)
351 self.runCompileTest()
352 if not self.cython_only:
353 doctest.DocTestSuite(self.module).run(result)
355 result.addError(self, sys.exc_info())
356 result.stopTest(self)
362 class CythonUnitTestCase(CythonCompileTestCase):
363 def shortDescription(self):
364 return "compiling (%s) tests in %s" % (self.language, self.module)
366 def run(self, result=None):
368 result = self.defaultTestResult()
369 result.startTest(self)
372 self.runCompileTest()
373 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
375 result.addError(self, sys.exc_info())
376 result.stopTest(self)
382 def collect_unittests(path, module_prefix, suite, selectors):
383 def file_matches(filename):
384 return filename.startswith("Test") and filename.endswith(".py")
386 def package_matches(dirname):
387 return dirname == "Tests"
389 loader = unittest.TestLoader()
393 for dirpath, dirnames, filenames in os.walk(path):
394 if dirpath != path and "__init__.py" not in filenames:
395 skipped_dirs.append(dirpath + os.path.sep)
398 for dir in skipped_dirs:
399 if dirpath.startswith(dir):
403 parentname = os.path.split(dirpath)[-1]
404 if package_matches(parentname):
407 filepath = os.path.join(dirpath, f)[:-len(".py")]
408 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
409 if not [ 1 for match in selectors if match(modulename) ]:
411 module = __import__(modulename)
412 for x in modulename.split('.')[1:]:
413 module = getattr(module, x)
414 suite.addTests([loader.loadTestsFromModule(module)])
416 def collect_doctests(path, module_prefix, suite, selectors):
417 def package_matches(dirname):
418 return dirname not in ("Mac", "Distutils", "Plex")
419 def file_matches(filename):
420 return (filename.endswith(".py") and not ('~' in filename
421 or '#' in filename or filename.startswith('.')))
422 import doctest, types
423 for dirpath, dirnames, filenames in os.walk(path):
424 parentname = os.path.split(dirpath)[-1]
425 if package_matches(parentname):
428 if not f.endswith('.py'): continue
429 filepath = os.path.join(dirpath, f)[:-len(".py")]
430 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
431 if not [ 1 for match in selectors if match(modulename) ]:
433 module = __import__(modulename)
434 for x in modulename.split('.')[1:]:
435 module = getattr(module, x)
436 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
438 suite.addTest(doctest.DocTestSuite(module))
439 except ValueError: # no tests
442 class MissingDependencyExcluder:
443 def __init__(self, deps):
444 # deps: { module name : matcher func }
445 self.exclude_matchers = []
446 for mod, matcher in deps.items():
450 self.exclude_matchers.append(matcher)
451 self.tests_missing_deps = []
452 def __call__(self, testname):
453 for matcher in self.exclude_matchers:
454 if matcher(testname):
455 self.tests_missing_deps.append(testname)
459 class VersionDependencyExcluder:
460 def __init__(self, deps):
461 # deps: { version : matcher func }
462 from sys import version_info
463 self.exclude_matchers = []
464 for ver, matcher in deps.items():
465 if version_info < ver:
466 self.exclude_matchers.append(matcher)
467 self.tests_missing_deps = []
468 def __call__(self, testname):
469 for matcher in self.exclude_matchers:
470 if matcher(testname):
471 self.tests_missing_deps.append(testname)
475 class FileListExcluder:
477 def __init__(self, list_file):
479 for line in open(list_file).readlines():
481 if line and line[0] != '#':
482 self.excludes[line.split()[0]] = True
484 def __call__(self, testname):
485 return testname.split('.')[-1] in self.excludes
487 if __name__ == '__main__':
488 from optparse import OptionParser
489 parser = OptionParser()
490 parser.add_option("--no-cleanup", dest="cleanup_workdir",
491 action="store_false", default=True,
492 help="do not delete the generated C files (allows passing --no-cython on next run)")
493 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
494 action="store_false", default=True,
495 help="do not delete the generated shared libary files (allows manual module experimentation)")
496 parser.add_option("--no-cython", dest="with_cython",
497 action="store_false", default=True,
498 help="do not run the Cython compiler, only the C compiler")
499 parser.add_option("--no-c", dest="use_c",
500 action="store_false", default=True,
501 help="do not test C compilation")
502 parser.add_option("--no-cpp", dest="use_cpp",
503 action="store_false", default=True,
504 help="do not test C++ compilation")
505 parser.add_option("--no-unit", dest="unittests",
506 action="store_false", default=True,
507 help="do not run the unit tests")
508 parser.add_option("--no-doctest", dest="doctests",
509 action="store_false", default=True,
510 help="do not run the doctests")
511 parser.add_option("--no-file", dest="filetests",
512 action="store_false", default=True,
513 help="do not run the file based tests")
514 parser.add_option("--no-pyregr", dest="pyregr",
515 action="store_false", default=True,
516 help="do not run the regression tests of CPython in tests/pyregr/")
517 parser.add_option("--cython-only", dest="cython_only",
518 action="store_true", default=False,
519 help="only compile pyx to c, do not run C compiler or run the tests")
520 parser.add_option("--no-refnanny", dest="with_refnanny",
521 action="store_false", default=True,
522 help="do not regression test reference counting")
523 parser.add_option("--sys-pyregr", dest="system_pyregr",
524 action="store_true", default=False,
525 help="run the regression tests of the CPython installation")
526 parser.add_option("-x", "--exclude", dest="exclude",
527 action="append", metavar="PATTERN",
528 help="exclude tests matching the PATTERN")
529 parser.add_option("-C", "--coverage", dest="coverage",
530 action="store_true", default=False,
531 help="collect source coverage data for the Compiler")
532 parser.add_option("-A", "--annotate", dest="annotate_source",
533 action="store_true", default=True,
534 help="generate annotated HTML versions of the test source files")
535 parser.add_option("--no-annotate", dest="annotate_source",
536 action="store_false",
537 help="do not generate annotated HTML versions of the test source files")
538 parser.add_option("-v", "--verbose", dest="verbosity",
539 action="count", default=0,
540 help="display test progress, pass twice to print test names")
541 parser.add_option("-T", "--ticket", dest="tickets",
543 help="a bug ticket number to run the respective test in 'tests/bugs'")
545 options, cmd_args = parser.parse_args()
547 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
548 ROOTDIR = os.path.join(DISTDIR, 'tests')
549 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
551 if sys.version_info >= (3,1):
552 options.doctests = False
553 options.unittests = False
554 options.pyregr = False
555 if options.with_cython:
556 # need to convert Cython sources first
557 import lib2to3.refactor
558 from distutils.util import copydir_run_2to3
559 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
560 if fix.split('fix_')[-1] not in ('next',)
562 cy3_dir = os.path.join(WORKDIR, 'Cy3')
563 if not os.path.exists(cy3_dir):
565 import distutils.log as dlog
566 dlog.set_threshold(dlog.DEBUG)
567 copydir_run_2to3(DISTDIR, cy3_dir, fixer_names=fixers,
571 recursive-exclude Cython *
572 recursive-include Cython *.py *.pyx *.pxd
574 sys.path.insert(0, cy3_dir)
575 elif sys.version_info[0] >= 3:
576 # make sure we do not import (or run) Cython itself
577 options.with_cython = False
578 options.doctests = False
579 options.unittests = False
580 options.pyregr = False
587 WITH_CYTHON = options.with_cython
590 from Cython.Compiler.Main import \
591 CompilationOptions, \
592 default_options as pyrex_default_options, \
593 compile as cython_compile
594 from Cython.Compiler import Errors
595 Errors.LEVEL = 0 # show all warnings
598 UNITTEST_MODULE = "Cython"
599 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
601 if os.path.exists(WORKDIR):
602 for path in os.listdir(WORKDIR):
603 if path in ("support", "Cy3"): continue
604 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
605 if not os.path.exists(WORKDIR):
609 from Cython.Compiler.Version import version
610 sys.stderr.write("Running tests against Cython %s\n" % version)
611 from Cython.Compiler import DebugFlags
612 DebugFlags.debug_temp_code_comments = 1
614 sys.stderr.write("Running tests without Cython.\n")
615 sys.stderr.write("Python %s\n" % sys.version)
616 sys.stderr.write("\n")
618 if options.with_refnanny:
619 from pyximport.pyxbuild import pyx_to_dll
620 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
622 pyxbuild_dir=os.path.join(WORKDIR, "support"))
623 sys.path.insert(0, os.path.split(libpath)[0])
624 CFLAGS.append("-DCYTHON_REFNANNY")
628 for ticket_number in options.tickets:
630 cmd_args.append('.*T%s$' % ticket_number)
632 for selector in cmd_args:
633 if selector.startswith('bugs'):
637 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
639 selectors = [ lambda x:True ]
641 # Chech which external modules are not present and exclude tests
642 # which depends on them (by prefix)
644 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
645 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
646 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
649 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
652 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
656 languages.append('c')
658 languages.append('cpp')
660 test_suite = unittest.TestSuite()
662 if options.unittests:
663 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
666 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
668 if options.filetests and languages:
669 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
670 options.annotate_source, options.cleanup_workdir,
671 options.cleanup_sharedlibs, options.pyregr,
672 options.cython_only, languages, test_bugs)
673 test_suite.addTest(filetests.build_suite())
675 if options.system_pyregr and languages:
676 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
677 options.annotate_source, options.cleanup_workdir,
678 options.cleanup_sharedlibs, True,
679 options.cython_only, languages, test_bugs)
681 filetests.handle_directory(
682 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
685 unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
689 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
690 modules = [ module for name, module in sys.modules.items()
691 if module is not None and
692 name.startswith('Cython.Compiler.') and
693 name[len('Cython.Compiler.'):] not in ignored_modules ]
694 coverage.report(modules, show_missing=0)
696 if missing_dep_excluder.tests_missing_deps:
697 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
698 for test in missing_dep_excluder.tests_missing_deps:
699 sys.stderr.write(" %s\n" % test)
701 if options.with_refnanny:
703 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))