14 from StringIO import StringIO
16 from io import StringIO
19 import cPickle as pickle
26 from distutils.dist import Distribution
27 from distutils.core import Extension
28 from distutils.command.build_ext import build_ext as _build_ext
29 distutils_distro = Distribution()
31 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr']
32 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
34 # Lists external modules, and a matcher matching tests
35 # which should be excluded if the module is not present.
37 'numpy' : re.compile('.*\.numpy_.*').match,
38 'pstats' : re.compile('.*\.pstats_.*').match,
39 'posix' : re.compile('.*\.posix_.*').match,
42 def get_numpy_include_dirs():
44 return [numpy.get_include()]
47 # test name matcher , callable returning list
48 (re.compile('numpy_.*').match, get_numpy_include_dirs),
52 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
53 # (2,4) : (operator.le, ...) excludes ... when PyVer <= 2.4.x
54 (2,5) : (operator.lt, lambda x: x in ['run.any',
57 (2,4) : (operator.le, lambda x: x in ['run.extern_builtins_T258'
59 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
62 # The next line should start (3,); but this is a dictionary, so
63 # we can only have one (3,) key. Since 2.7 is supposed to be the
64 # last 2.x release, things would have to change drastically for this
66 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
67 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
68 'compile.extsetslice',
69 'compile.extdelslice',
70 'run.special_methods_T561_py2']),
73 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
74 CFLAGS = os.getenv('CFLAGS', '').split()
76 class build_ext(_build_ext):
77 def build_extension(self, ext):
78 if ext.language == 'c++':
80 try: # Py2.7+ & Py3.2+
81 compiler_obj = self.compiler_obj
82 except AttributeError:
83 compiler_obj = self.compiler
84 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
87 _build_ext.build_extension(self, ext)
89 class ErrorWriter(object):
90 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
93 self.write = self.output.append
95 def _collect(self, collect_errors, collect_warnings):
96 s = ''.join(self.output)
98 for line in s.split('\n'):
99 match = self.match_error(line)
101 is_warning, line, column, message = match.groups()
102 if (is_warning and collect_warnings) or \
103 (not is_warning and collect_errors):
104 result.append( (int(line), int(column), message.strip()) )
106 return [ "%d:%d: %s" % values for values in result ]
109 return self._collect(True, False)
111 def getwarnings(self):
112 return self._collect(False, True)
115 return self._collect(True, True)
117 class TestBuilder(object):
118 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
119 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
120 languages, test_bugs, fork):
121 self.rootdir = rootdir
122 self.workdir = workdir
123 self.selectors = selectors
124 self.exclude_selectors = exclude_selectors
125 self.annotate = annotate
126 self.cleanup_workdir = cleanup_workdir
127 self.cleanup_sharedlibs = cleanup_sharedlibs
128 self.with_pyregr = with_pyregr
129 self.cython_only = cython_only
130 self.languages = languages
131 self.test_bugs = test_bugs
134 def build_suite(self):
135 suite = unittest.TestSuite()
136 test_dirs = TEST_DIRS
137 filenames = os.listdir(self.rootdir)
139 for filename in filenames:
140 if not WITH_CYTHON and filename == "errors":
141 # we won't get any errors without running Cython
143 path = os.path.join(self.rootdir, filename)
144 if os.path.isdir(path) and filename in test_dirs:
145 if filename == 'pyregr' and not self.with_pyregr:
148 self.handle_directory(path, filename))
149 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
150 # Non-Windows makefile, can't run Cython under Py3.
151 if [1 for selector in self.selectors if selector("embedded")]:
152 suite.addTest(unittest.makeSuite(EmbedTest))
155 def handle_directory(self, path, context):
156 workdir = os.path.join(self.workdir, context)
157 if not os.path.exists(workdir):
160 expect_errors = (context == 'errors')
161 suite = unittest.TestSuite()
162 filenames = os.listdir(path)
164 for filename in filenames:
165 if not (filename.endswith(".pyx") or filename.endswith(".py")):
167 if filename.startswith('.'): continue # certain emacs backup files
168 if context == 'pyregr' and not filename.startswith('test_'):
170 module = os.path.splitext(filename)[0]
171 fqmodule = "%s.%s" % (context, module)
172 if not [ 1 for match in self.selectors
173 if match(fqmodule) ]:
175 if self.exclude_selectors:
176 if [1 for match in self.exclude_selectors if match(fqmodule)]:
178 if context in TEST_RUN_DIRS:
179 if module.startswith("test_"):
180 test_class = CythonUnitTestCase
182 test_class = CythonRunTestCase
184 test_class = CythonCompileTestCase
185 for test in self.build_tests(test_class, path, workdir,
186 module, expect_errors):
190 def build_tests(self, test_class, path, workdir, module, expect_errors):
192 if 'cpp' in module and 'cpp' in self.languages:
195 languages = self.languages[:1]
197 languages = self.languages
198 if 'cpp' in module and 'c' in languages:
199 languages = list(languages)
200 languages.remove('c')
201 tests = [ self.build_test(test_class, path, workdir, module,
202 language, expect_errors)
203 for language in languages ]
206 def build_test(self, test_class, path, workdir, module,
207 language, expect_errors):
208 workdir = os.path.join(workdir, language)
209 if not os.path.exists(workdir):
211 return test_class(path, workdir, module,
213 expect_errors=expect_errors,
214 annotate=self.annotate,
215 cleanup_workdir=self.cleanup_workdir,
216 cleanup_sharedlibs=self.cleanup_sharedlibs,
217 cython_only=self.cython_only,
220 class CythonCompileTestCase(unittest.TestCase):
221 def __init__(self, test_directory, workdir, module, language='c',
222 expect_errors=False, annotate=False, cleanup_workdir=True,
223 cleanup_sharedlibs=True, cython_only=False, fork=True):
224 self.test_directory = test_directory
225 self.workdir = workdir
227 self.language = language
228 self.expect_errors = expect_errors
229 self.annotate = annotate
230 self.cleanup_workdir = cleanup_workdir
231 self.cleanup_sharedlibs = cleanup_sharedlibs
232 self.cython_only = cython_only
234 unittest.TestCase.__init__(self)
236 def shortDescription(self):
237 return "compiling (%s) %s" % (self.language, self.module)
240 if self.workdir not in sys.path:
241 sys.path.insert(0, self.workdir)
245 sys.path.remove(self.workdir)
249 del sys.modules[self.module]
252 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
253 cleanup_lib_files = self.cleanup_sharedlibs
254 if os.path.exists(self.workdir):
255 for rmfile in os.listdir(self.workdir):
256 if not cleanup_c_files:
257 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
259 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
261 if self.annotate and rmfile.endswith(".html"):
264 rmfile = os.path.join(self.workdir, rmfile)
265 if os.path.isdir(rmfile):
266 shutil.rmtree(rmfile, ignore_errors=True)
272 os.makedirs(self.workdir)
275 self.runCompileTest()
277 def runCompileTest(self):
278 self.compile(self.test_directory, self.module, self.workdir,
279 self.test_directory, self.expect_errors, self.annotate)
281 def find_module_source_file(self, source_file):
282 if not os.path.exists(source_file):
283 source_file = source_file[:-1]
286 def build_target_filename(self, module_name):
287 target = '%s.%s' % (module_name, self.language)
290 def copy_related_files(self, test_directory, target_directory, module_name):
291 is_related = re.compile('%s_.*[.].*' % module_name).match
292 for filename in os.listdir(test_directory):
293 if is_related(filename):
294 shutil.copy(os.path.join(test_directory, filename),
297 def find_source_files(self, workdir, module_name):
298 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
299 return [self.build_target_filename(module_name)] + [
300 filename for filename in os.listdir(workdir)
301 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
303 def split_source_and_output(self, test_directory, module, workdir):
304 source_file = os.path.join(test_directory, module) + '.pyx'
305 source_and_output = codecs.open(
306 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
307 out = codecs.open(os.path.join(workdir, module + '.pyx'),
309 for line in source_and_output:
311 if line.startswith("_ERRORS"):
317 geterrors = out.geterrors
318 except AttributeError:
323 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
324 include_dirs = INCLUDE_DIRS[:]
326 include_dirs.append(incdir)
327 source = self.find_module_source_file(
328 os.path.join(test_directory, module + '.pyx'))
329 target = os.path.join(targetdir, self.build_target_filename(module))
330 options = CompilationOptions(
331 pyrex_default_options,
332 include_path = include_dirs,
333 output_file = target,
335 use_listing_file = False,
336 cplus = self.language == 'cpp',
337 generate_pxi = False,
338 evaluate_tree_assertions = True,
340 cython_compile(source, options=options,
341 full_module_name=module)
343 def run_distutils(self, test_directory, module, workdir, incdir):
347 build_extension = build_ext(distutils_distro)
348 build_extension.include_dirs = INCLUDE_DIRS[:]
350 build_extension.include_dirs.append(incdir)
351 build_extension.finalize_options()
352 ext_include_dirs = []
353 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
355 ext_include_dirs += get_additional_include_dirs()
356 self.copy_related_files(test_directory, workdir, module)
357 extension = Extension(
359 sources = self.find_source_files(workdir, module),
360 include_dirs = ext_include_dirs,
361 extra_compile_args = CFLAGS,
363 if self.language == 'cpp':
364 extension.language = 'c++'
365 build_extension.extensions = [extension]
366 build_extension.build_temp = workdir
367 build_extension.build_lib = workdir
368 build_extension.run()
372 def compile(self, test_directory, module, workdir, incdir,
373 expect_errors, annotate):
374 expected_errors = errors = ()
376 expected_errors = self.split_source_and_output(
377 test_directory, module, workdir)
378 test_directory = workdir
381 old_stderr = sys.stderr
383 sys.stderr = ErrorWriter()
384 self.run_cython(test_directory, module, workdir, incdir, annotate)
385 errors = sys.stderr.geterrors()
387 sys.stderr = old_stderr
389 if errors or expected_errors:
391 for expected, error in zip(expected_errors, errors):
392 self.assertEquals(expected, error)
393 if len(errors) < len(expected_errors):
394 expected_error = expected_errors[len(errors)]
395 self.assertEquals(expected_error, None)
396 elif len(errors) > len(expected_errors):
397 unexpected_error = errors[len(expected_errors)]
398 self.assertEquals(None, unexpected_error)
399 except AssertionError:
400 print("\n=== Expected errors: ===")
401 print('\n'.join(expected_errors))
402 print("\n\n=== Got errors: ===")
403 print('\n'.join(errors))
407 if not self.cython_only:
408 self.run_distutils(test_directory, module, workdir, incdir)
410 class CythonRunTestCase(CythonCompileTestCase):
411 def shortDescription(self):
412 return "compiling (%s) and running %s" % (self.language, self.module)
414 def run(self, result=None):
416 result = self.defaultTestResult()
417 result.startTest(self)
420 self.runCompileTest()
421 if not self.cython_only:
422 self.run_doctests(self.module, result)
424 result.addError(self, sys.exc_info())
425 result.stopTest(self)
431 def run_doctests(self, module_name, result):
432 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
433 doctest.DocTestSuite(module_name).run(result)
437 # fork to make sure we do not keep the tested module loaded
438 result_handle, result_file = tempfile.mkstemp()
439 os.close(result_handle)
447 partial_result = PartialTestResult(result)
448 tests = doctest.DocTestSuite(module_name)
449 tests.run(partial_result)
453 # importing failed, try to fake a test class
455 failureException=sys.exc_info()[1],
456 _shortDescription=self.shortDescription(),
458 partial_result.addError(tests, sys.exc_info())
460 output = open(result_file, 'wb')
461 pickle.dump(partial_result.data(), output)
464 traceback.print_exc()
468 os._exit(result_code)
471 cid, result_code = os.waitpid(child_id, 0)
472 # os.waitpid returns the child's result code in the
473 # upper byte of result_code, and the signal it was
474 # killed by in the lower byte
475 if result_code & 255:
476 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
477 (module_name, result_code & 255))
478 result_code = result_code >> 8
479 if result_code in (0,1):
480 input = open(result_file, 'rb')
482 PartialTestResult.join_results(result, pickle.load(input))
486 raise Exception("Tests in module '%s' exited with status %d" %
487 (module_name, result_code))
489 try: os.unlink(result_file)
493 is_private_field = re.compile('^_[^_]').match
495 class _FakeClass(object):
496 def __init__(self, **kwargs):
497 self._shortDescription = kwargs.get('module_name')
498 self.__dict__.update(kwargs)
499 def shortDescription(self):
500 return self._shortDescription
502 try: # Py2.7+ and Py3.2+
503 from unittest.runner import _TextTestResult
505 from unittest import _TextTestResult
507 class PartialTestResult(_TextTestResult):
508 def __init__(self, base_result):
509 _TextTestResult.__init__(
510 self, self._StringIO(), True,
511 base_result.dots + base_result.showAll*2)
513 def strip_error_results(self, results):
514 for test_case, error in results:
515 for attr_name in filter(is_private_field, dir(test_case)):
516 if attr_name == '_dt_test':
517 test_case._dt_test = _FakeClass(
518 name=test_case._dt_test.name)
519 elif attr_name != '_shortDescription':
520 setattr(test_case, attr_name, None)
523 self.strip_error_results(self.failures)
524 self.strip_error_results(self.errors)
525 return (self.failures, self.errors, self.testsRun,
526 self.stream.getvalue())
528 def join_results(result, data):
529 """Static method for merging the result back into the main
532 failures, errors, tests_run, output = data
534 result.stream.write(output)
535 result.errors.extend(errors)
536 result.failures.extend(failures)
537 result.testsRun += tests_run
539 join_results = staticmethod(join_results)
541 class _StringIO(StringIO):
542 def writeln(self, line):
543 self.write("%s\n" % line)
546 class CythonUnitTestCase(CythonCompileTestCase):
547 def shortDescription(self):
548 return "compiling (%s) tests in %s" % (self.language, self.module)
550 def run(self, result=None):
552 result = self.defaultTestResult()
553 result.startTest(self)
556 self.runCompileTest()
557 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
559 result.addError(self, sys.exc_info())
560 result.stopTest(self)
566 def collect_unittests(path, module_prefix, suite, selectors):
567 def file_matches(filename):
568 return filename.startswith("Test") and filename.endswith(".py")
570 def package_matches(dirname):
571 return dirname == "Tests"
573 loader = unittest.TestLoader()
577 for dirpath, dirnames, filenames in os.walk(path):
578 if dirpath != path and "__init__.py" not in filenames:
579 skipped_dirs.append(dirpath + os.path.sep)
582 for dir in skipped_dirs:
583 if dirpath.startswith(dir):
587 parentname = os.path.split(dirpath)[-1]
588 if package_matches(parentname):
591 filepath = os.path.join(dirpath, f)[:-len(".py")]
592 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
593 if not [ 1 for match in selectors if match(modulename) ]:
595 module = __import__(modulename)
596 for x in modulename.split('.')[1:]:
597 module = getattr(module, x)
598 suite.addTests([loader.loadTestsFromModule(module)])
600 def collect_doctests(path, module_prefix, suite, selectors):
601 def package_matches(dirname):
602 return dirname not in ("Mac", "Distutils", "Plex")
603 def file_matches(filename):
604 return (filename.endswith(".py") and not ('~' in filename
605 or '#' in filename or filename.startswith('.')))
606 import doctest, types
607 for dirpath, dirnames, filenames in os.walk(path):
608 parentname = os.path.split(dirpath)[-1]
609 if package_matches(parentname):
612 if not f.endswith('.py'): continue
613 filepath = os.path.join(dirpath, f)[:-len(".py")]
614 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
615 if not [ 1 for match in selectors if match(modulename) ]:
617 module = __import__(modulename)
618 for x in modulename.split('.')[1:]:
619 module = getattr(module, x)
620 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
622 suite.addTest(doctest.DocTestSuite(module))
623 except ValueError: # no tests
626 # TODO: Support cython_freeze needed here as well.
627 # TODO: Windows support.
629 class EmbedTest(unittest.TestCase):
631 working_dir = "Demos/embed"
634 self.old_dir = os.getcwd()
635 os.chdir(self.working_dir)
637 "make PYTHON='%s' clean > /dev/null" % sys.executable)
642 "make PYTHON='%s' clean > /dev/null" % sys.executable)
645 os.chdir(self.old_dir)
647 def test_embed(self):
648 self.assert_(os.system(
649 "make PYTHON='%s' test > make.output" % sys.executable) == 0)
651 os.remove('make.output')
655 class MissingDependencyExcluder:
656 def __init__(self, deps):
657 # deps: { module name : matcher func }
658 self.exclude_matchers = []
659 for mod, matcher in deps.items():
663 self.exclude_matchers.append(matcher)
664 self.tests_missing_deps = []
665 def __call__(self, testname):
666 for matcher in self.exclude_matchers:
667 if matcher(testname):
668 self.tests_missing_deps.append(testname)
672 class VersionDependencyExcluder:
673 def __init__(self, deps):
674 # deps: { version : matcher func }
675 from sys import version_info
676 self.exclude_matchers = []
677 for ver, (compare, matcher) in deps.items():
678 if compare(version_info, ver):
679 self.exclude_matchers.append(matcher)
680 self.tests_missing_deps = []
681 def __call__(self, testname):
682 for matcher in self.exclude_matchers:
683 if matcher(testname):
684 self.tests_missing_deps.append(testname)
688 class FileListExcluder:
690 def __init__(self, list_file):
692 for line in open(list_file).readlines():
694 if line and line[0] != '#':
695 self.excludes[line.split()[0]] = True
697 def __call__(self, testname):
698 return testname in self.excludes or testname.split('.')[-1] in self.excludes
700 def refactor_for_py3(distdir, cy3_dir):
701 # need to convert Cython sources first
702 import lib2to3.refactor
703 from distutils.util import copydir_run_2to3
704 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
705 if fix.split('fix_')[-1] not in ('next',)
707 if not os.path.exists(cy3_dir):
709 import distutils.log as dlog
710 dlog.set_threshold(dlog.INFO)
711 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
715 recursive-exclude Cython *
716 recursive-include Cython *.py *.pyx *.pxd
718 sys.path.insert(0, cy3_dir)
721 if __name__ == '__main__':
722 from optparse import OptionParser
723 parser = OptionParser()
724 parser.add_option("--no-cleanup", dest="cleanup_workdir",
725 action="store_false", default=True,
726 help="do not delete the generated C files (allows passing --no-cython on next run)")
727 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
728 action="store_false", default=True,
729 help="do not delete the generated shared libary files (allows manual module experimentation)")
730 parser.add_option("--no-cython", dest="with_cython",
731 action="store_false", default=True,
732 help="do not run the Cython compiler, only the C compiler")
733 parser.add_option("--no-c", dest="use_c",
734 action="store_false", default=True,
735 help="do not test C compilation")
736 parser.add_option("--no-cpp", dest="use_cpp",
737 action="store_false", default=True,
738 help="do not test C++ compilation")
739 parser.add_option("--no-unit", dest="unittests",
740 action="store_false", default=True,
741 help="do not run the unit tests")
742 parser.add_option("--no-doctest", dest="doctests",
743 action="store_false", default=True,
744 help="do not run the doctests")
745 parser.add_option("--no-file", dest="filetests",
746 action="store_false", default=True,
747 help="do not run the file based tests")
748 parser.add_option("--no-pyregr", dest="pyregr",
749 action="store_false", default=True,
750 help="do not run the regression tests of CPython in tests/pyregr/")
751 parser.add_option("--cython-only", dest="cython_only",
752 action="store_true", default=False,
753 help="only compile pyx to c, do not run C compiler or run the tests")
754 parser.add_option("--no-refnanny", dest="with_refnanny",
755 action="store_false", default=True,
756 help="do not regression test reference counting")
757 parser.add_option("--no-fork", dest="fork",
758 action="store_false", default=True,
759 help="do not fork to run tests")
760 parser.add_option("--sys-pyregr", dest="system_pyregr",
761 action="store_true", default=False,
762 help="run the regression tests of the CPython installation")
763 parser.add_option("-x", "--exclude", dest="exclude",
764 action="append", metavar="PATTERN",
765 help="exclude tests matching the PATTERN")
766 parser.add_option("-C", "--coverage", dest="coverage",
767 action="store_true", default=False,
768 help="collect source coverage data for the Compiler")
769 parser.add_option("--coverage-xml", dest="coverage_xml",
770 action="store_true", default=False,
771 help="collect source coverage data for the Compiler in XML format")
772 parser.add_option("-A", "--annotate", dest="annotate_source",
773 action="store_true", default=True,
774 help="generate annotated HTML versions of the test source files")
775 parser.add_option("--no-annotate", dest="annotate_source",
776 action="store_false",
777 help="do not generate annotated HTML versions of the test source files")
778 parser.add_option("-v", "--verbose", dest="verbosity",
779 action="count", default=0,
780 help="display test progress, pass twice to print test names")
781 parser.add_option("-T", "--ticket", dest="tickets",
783 help="a bug ticket number to run the respective test in 'tests/*'")
784 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
785 help="write test results in XML to directory DIR")
786 parser.add_option("--exit-ok", dest="exit_ok", default=False,
788 help="exit without error code even on test failures")
790 options, cmd_args = parser.parse_args()
792 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
793 ROOTDIR = os.path.join(DISTDIR, 'tests')
794 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
796 if sys.version_info[0] >= 3:
797 options.doctests = False
798 if options.with_cython:
800 # try if Cython is installed in a Py3 version
801 import Cython.Compiler.Main
803 cy_modules = [ name for name in sys.modules
804 if name == 'Cython' or name.startswith('Cython.') ]
805 for name in cy_modules:
806 del sys.modules[name]
807 # hasn't been refactored yet - do it now
808 cy3_dir = os.path.join(WORKDIR, 'Cy3')
809 if sys.version_info >= (3,1):
810 refactor_for_py3(DISTDIR, cy3_dir)
811 elif os.path.isdir(cy3_dir):
812 sys.path.insert(0, cy3_dir)
814 options.with_cython = False
816 WITH_CYTHON = options.with_cython
818 if options.coverage or options.coverage_xml:
820 options.coverage = options.coverage_xml = False
822 from coverage import coverage as _coverage
823 coverage = _coverage(branch=True)
828 from Cython.Compiler.Main import \
829 CompilationOptions, \
830 default_options as pyrex_default_options, \
831 compile as cython_compile
832 from Cython.Compiler import Errors
833 Errors.LEVEL = 0 # show all warnings
834 from Cython.Compiler import Options
835 Options.generate_cleanup_code = 3 # complete cleanup code
836 from Cython.Compiler import DebugFlags
837 DebugFlags.debug_temp_code_comments = 1
840 UNITTEST_MODULE = "Cython"
841 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
843 if os.path.exists(WORKDIR):
844 for path in os.listdir(WORKDIR):
845 if path in ("support", "Cy3"): continue
846 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
847 if not os.path.exists(WORKDIR):
851 from Cython.Compiler.Version import version
852 sys.stderr.write("Running tests against Cython %s\n" % version)
854 sys.stderr.write("Running tests without Cython.\n")
855 sys.stderr.write("Python %s\n" % sys.version)
856 sys.stderr.write("\n")
858 if options.with_refnanny:
859 from pyximport.pyxbuild import pyx_to_dll
860 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
862 pyxbuild_dir=os.path.join(WORKDIR, "support"))
863 sys.path.insert(0, os.path.split(libpath)[0])
864 CFLAGS.append("-DCYTHON_REFNANNY=1")
866 if options.xml_output_dir and options.fork:
867 # doesn't currently work together
868 sys.stderr.write("Disabling forked testing to support XML test output\n")
873 for ticket_number in options.tickets:
875 cmd_args.append('.*T%s$' % ticket_number)
877 for selector in cmd_args:
878 if selector.startswith('bugs'):
882 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
884 selectors = [ lambda x:True ]
886 # Chech which external modules are not present and exclude tests
887 # which depends on them (by prefix)
889 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
890 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
891 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
894 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
897 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
899 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
900 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
904 languages.append('c')
906 languages.append('cpp')
908 test_suite = unittest.TestSuite()
910 if options.unittests:
911 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
914 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
916 if options.filetests and languages:
917 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
918 options.annotate_source, options.cleanup_workdir,
919 options.cleanup_sharedlibs, options.pyregr,
920 options.cython_only, languages, test_bugs,
922 test_suite.addTest(filetests.build_suite())
924 if options.system_pyregr and languages:
925 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
926 options.annotate_source, options.cleanup_workdir,
927 options.cleanup_sharedlibs, True,
928 options.cython_only, languages, test_bugs,
931 filetests.handle_directory(
932 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
935 if options.xml_output_dir:
936 from Cython.Tests.xmlrunner import XMLTestRunner
937 test_runner = XMLTestRunner(output=options.xml_output_dir,
938 verbose=options.verbosity > 0)
940 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
942 result = test_runner.run(test_suite)
944 if options.coverage or options.coverage_xml:
946 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
947 modules = [ module for name, module in sys.modules.items()
948 if module is not None and
949 name.startswith('Cython.Compiler.') and
950 name[len('Cython.Compiler.'):] not in ignored_modules ]
952 coverage.report(modules, show_missing=0)
953 if options.coverage_xml:
954 coverage.xml_report(modules, outfile="coverage-report.xml")
956 if missing_dep_excluder.tests_missing_deps:
957 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
958 for test in missing_dep_excluder.tests_missing_deps:
959 sys.stderr.write(" %s\n" % test)
961 if options.with_refnanny:
963 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
968 sys.exit(not result.wasSuccessful())