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 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
63 'compile.extsetslice',
64 'compile.extdelslice']),
67 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
68 CFLAGS = os.getenv('CFLAGS', '').split()
70 class build_ext(_build_ext):
71 def build_extension(self, ext):
72 if ext.language == 'c++':
74 try: # Py2.7+ & Py3.2+
75 compiler_obj = self.compiler_obj
76 except AttributeError:
77 compiler_obj = self.compiler
78 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
81 _build_ext.build_extension(self, ext)
83 class ErrorWriter(object):
84 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
87 self.write = self.output.append
89 def _collect(self, collect_errors, collect_warnings):
90 s = ''.join(self.output)
92 for line in s.split('\n'):
93 match = self.match_error(line)
95 is_warning, line, column, message = match.groups()
96 if (is_warning and collect_warnings) or \
97 (not is_warning and collect_errors):
98 result.append( (int(line), int(column), message.strip()) )
100 return [ "%d:%d: %s" % values for values in result ]
103 return self._collect(True, False)
105 def getwarnings(self):
106 return self._collect(False, True)
109 return self._collect(True, True)
111 class TestBuilder(object):
112 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
113 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
114 languages, test_bugs, fork):
115 self.rootdir = rootdir
116 self.workdir = workdir
117 self.selectors = selectors
118 self.exclude_selectors = exclude_selectors
119 self.annotate = annotate
120 self.cleanup_workdir = cleanup_workdir
121 self.cleanup_sharedlibs = cleanup_sharedlibs
122 self.with_pyregr = with_pyregr
123 self.cython_only = cython_only
124 self.languages = languages
125 self.test_bugs = test_bugs
128 def build_suite(self):
129 suite = unittest.TestSuite()
130 test_dirs = TEST_DIRS
131 filenames = os.listdir(self.rootdir)
133 for filename in filenames:
134 if not WITH_CYTHON and filename == "errors":
135 # we won't get any errors without running Cython
137 path = os.path.join(self.rootdir, filename)
138 if os.path.isdir(path) and filename in test_dirs:
139 if filename == 'pyregr' and not self.with_pyregr:
142 self.handle_directory(path, filename))
143 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
144 # Non-Windows makefile, can't run Cython under Py3.
145 if [1 for selector in self.selectors if selector("embedded")]:
146 suite.addTest(unittest.makeSuite(EmbedTest))
149 def handle_directory(self, path, context):
150 workdir = os.path.join(self.workdir, context)
151 if not os.path.exists(workdir):
154 expect_errors = (context == 'errors')
155 suite = unittest.TestSuite()
156 filenames = os.listdir(path)
158 for filename in filenames:
159 if not (filename.endswith(".pyx") or filename.endswith(".py")):
161 if filename.startswith('.'): continue # certain emacs backup files
162 if context == 'pyregr' and not filename.startswith('test_'):
164 module = os.path.splitext(filename)[0]
165 fqmodule = "%s.%s" % (context, module)
166 if not [ 1 for match in self.selectors
167 if match(fqmodule) ]:
169 if self.exclude_selectors:
170 if [1 for match in self.exclude_selectors if match(fqmodule)]:
172 if context in TEST_RUN_DIRS:
173 if module.startswith("test_"):
174 test_class = CythonUnitTestCase
176 test_class = CythonRunTestCase
178 test_class = CythonCompileTestCase
179 for test in self.build_tests(test_class, path, workdir,
180 module, expect_errors):
184 def build_tests(self, test_class, path, workdir, module, expect_errors):
186 if 'cpp' in module and 'cpp' in self.languages:
189 languages = self.languages[:1]
191 languages = self.languages
192 if 'cpp' in module and 'c' in languages:
193 languages = list(languages)
194 languages.remove('c')
195 tests = [ self.build_test(test_class, path, workdir, module,
196 language, expect_errors)
197 for language in languages ]
200 def build_test(self, test_class, path, workdir, module,
201 language, expect_errors):
202 workdir = os.path.join(workdir, language)
203 if not os.path.exists(workdir):
205 return test_class(path, workdir, module,
207 expect_errors=expect_errors,
208 annotate=self.annotate,
209 cleanup_workdir=self.cleanup_workdir,
210 cleanup_sharedlibs=self.cleanup_sharedlibs,
211 cython_only=self.cython_only,
214 class CythonCompileTestCase(unittest.TestCase):
215 def __init__(self, test_directory, workdir, module, language='c',
216 expect_errors=False, annotate=False, cleanup_workdir=True,
217 cleanup_sharedlibs=True, cython_only=False, fork=True):
218 self.test_directory = test_directory
219 self.workdir = workdir
221 self.language = language
222 self.expect_errors = expect_errors
223 self.annotate = annotate
224 self.cleanup_workdir = cleanup_workdir
225 self.cleanup_sharedlibs = cleanup_sharedlibs
226 self.cython_only = cython_only
228 unittest.TestCase.__init__(self)
230 def shortDescription(self):
231 return "compiling (%s) %s" % (self.language, self.module)
234 if self.workdir not in sys.path:
235 sys.path.insert(0, self.workdir)
239 sys.path.remove(self.workdir)
243 del sys.modules[self.module]
246 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
247 cleanup_lib_files = self.cleanup_sharedlibs
248 if os.path.exists(self.workdir):
249 for rmfile in os.listdir(self.workdir):
250 if not cleanup_c_files:
251 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
253 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
255 if self.annotate and rmfile.endswith(".html"):
258 rmfile = os.path.join(self.workdir, rmfile)
259 if os.path.isdir(rmfile):
260 shutil.rmtree(rmfile, ignore_errors=True)
266 os.makedirs(self.workdir)
269 self.runCompileTest()
271 def runCompileTest(self):
272 self.compile(self.test_directory, self.module, self.workdir,
273 self.test_directory, self.expect_errors, self.annotate)
275 def find_module_source_file(self, source_file):
276 if not os.path.exists(source_file):
277 source_file = source_file[:-1]
280 def build_target_filename(self, module_name):
281 target = '%s.%s' % (module_name, self.language)
284 def copy_related_files(self, test_directory, target_directory, module_name):
285 is_related = re.compile('%s_.*[.].*' % module_name).match
286 for filename in os.listdir(test_directory):
287 if is_related(filename):
288 shutil.copy(os.path.join(test_directory, filename),
291 def find_source_files(self, workdir, module_name):
292 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
293 return [self.build_target_filename(module_name)] + [
294 filename for filename in os.listdir(workdir)
295 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
297 def split_source_and_output(self, test_directory, module, workdir):
298 source_file = os.path.join(test_directory, module) + '.pyx'
299 source_and_output = codecs.open(
300 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
301 out = codecs.open(os.path.join(workdir, module + '.pyx'),
303 for line in source_and_output:
305 if line.startswith("_ERRORS"):
311 geterrors = out.geterrors
312 except AttributeError:
317 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
318 include_dirs = INCLUDE_DIRS[:]
320 include_dirs.append(incdir)
321 source = self.find_module_source_file(
322 os.path.join(test_directory, module + '.pyx'))
323 target = os.path.join(targetdir, self.build_target_filename(module))
324 options = CompilationOptions(
325 pyrex_default_options,
326 include_path = include_dirs,
327 output_file = target,
329 use_listing_file = False,
330 cplus = self.language == 'cpp',
331 generate_pxi = False,
332 # evaluate_tree_assertions = True,
333 evaluate_tree_assertions = False,
335 cython_compile(source, options=options,
336 full_module_name=module)
338 def run_distutils(self, test_directory, module, workdir, incdir):
342 build_extension = build_ext(distutils_distro)
343 build_extension.include_dirs = INCLUDE_DIRS[:]
345 build_extension.include_dirs.append(incdir)
346 build_extension.finalize_options()
347 ext_include_dirs = []
348 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
350 ext_include_dirs += get_additional_include_dirs()
351 self.copy_related_files(test_directory, workdir, module)
352 extension = Extension(
354 sources = self.find_source_files(workdir, module),
355 include_dirs = ext_include_dirs,
356 extra_compile_args = CFLAGS,
358 if self.language == 'cpp':
359 extension.language = 'c++'
360 build_extension.extensions = [extension]
361 build_extension.build_temp = workdir
362 build_extension.build_lib = workdir
363 build_extension.run()
367 def compile(self, test_directory, module, workdir, incdir,
368 expect_errors, annotate):
369 expected_errors = errors = ()
371 expected_errors = self.split_source_and_output(
372 test_directory, module, workdir)
373 test_directory = workdir
376 old_stderr = sys.stderr
378 sys.stderr = ErrorWriter()
379 self.run_cython(test_directory, module, workdir, incdir, annotate)
380 errors = sys.stderr.geterrors()
382 sys.stderr = old_stderr
384 if errors or expected_errors:
386 for expected, error in zip(expected_errors, errors):
387 self.assertEquals(expected, error)
388 if len(errors) < len(expected_errors):
389 expected_error = expected_errors[len(errors)]
390 self.assertEquals(expected_error, None)
391 elif len(errors) > len(expected_errors):
392 unexpected_error = errors[len(expected_errors)]
393 self.assertEquals(None, unexpected_error)
394 except AssertionError:
395 print("\n=== Expected errors: ===")
396 print('\n'.join(expected_errors))
397 print("\n\n=== Got errors: ===")
398 print('\n'.join(errors))
402 if not self.cython_only:
403 self.run_distutils(test_directory, module, workdir, incdir)
405 class CythonRunTestCase(CythonCompileTestCase):
406 def shortDescription(self):
407 return "compiling (%s) and running %s" % (self.language, self.module)
409 def run(self, result=None):
411 result = self.defaultTestResult()
412 result.startTest(self)
415 self.runCompileTest()
416 if not self.cython_only:
417 self.run_doctests(self.module, result)
419 result.addError(self, sys.exc_info())
420 result.stopTest(self)
426 def run_doctests(self, module_name, result):
427 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
428 doctest.DocTestSuite(module_name).run(result)
432 # fork to make sure we do not keep the tested module loaded
433 result_handle, result_file = tempfile.mkstemp()
434 os.close(result_handle)
442 partial_result = PartialTestResult(result)
443 tests = doctest.DocTestSuite(module_name)
444 tests.run(partial_result)
448 # importing failed, try to fake a test class
450 failureException=sys.exc_info()[1],
451 _shortDescription=self.shortDescription(),
453 partial_result.addError(tests, sys.exc_info())
455 output = open(result_file, 'wb')
456 pickle.dump(partial_result.data(), output)
459 traceback.print_exc()
463 os._exit(result_code)
466 cid, result_code = os.waitpid(child_id, 0)
467 # os.waitpid returns the child's result code in the
468 # upper byte of result_code, and the signal it was
469 # killed by in the lower byte
470 if result_code & 255:
471 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
472 (module_name, result_code & 255))
473 result_code = result_code >> 8
474 if result_code in (0,1):
475 input = open(result_file, 'rb')
477 PartialTestResult.join_results(result, pickle.load(input))
481 raise Exception("Tests in module '%s' exited with status %d" %
482 (module_name, result_code))
484 try: os.unlink(result_file)
488 is_private_field = re.compile('^_[^_]').match
490 class _FakeClass(object):
491 def __init__(self, **kwargs):
492 self._shortDescription = kwargs.get('module_name')
493 self.__dict__.update(kwargs)
494 def shortDescription(self):
495 return self._shortDescription
497 try: # Py2.7+ and Py3.2+
498 from unittest.runner import _TextTestResult
500 from unittest import _TextTestResult
502 class PartialTestResult(_TextTestResult):
503 def __init__(self, base_result):
504 _TextTestResult.__init__(
505 self, self._StringIO(), True,
506 base_result.dots + base_result.showAll*2)
508 def strip_error_results(self, results):
509 for test_case, error in results:
510 for attr_name in filter(is_private_field, dir(test_case)):
511 if attr_name == '_dt_test':
512 test_case._dt_test = _FakeClass(
513 name=test_case._dt_test.name)
514 elif attr_name != '_shortDescription':
515 setattr(test_case, attr_name, None)
518 self.strip_error_results(self.failures)
519 self.strip_error_results(self.errors)
520 return (self.failures, self.errors, self.testsRun,
521 self.stream.getvalue())
523 def join_results(result, data):
524 """Static method for merging the result back into the main
527 failures, errors, tests_run, output = data
529 result.stream.write(output)
530 result.errors.extend(errors)
531 result.failures.extend(failures)
532 result.testsRun += tests_run
534 join_results = staticmethod(join_results)
536 class _StringIO(StringIO):
537 def writeln(self, line):
538 self.write("%s\n" % line)
541 class CythonUnitTestCase(CythonCompileTestCase):
542 def shortDescription(self):
543 return "compiling (%s) tests in %s" % (self.language, self.module)
545 def run(self, result=None):
547 result = self.defaultTestResult()
548 result.startTest(self)
551 self.runCompileTest()
552 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
554 result.addError(self, sys.exc_info())
555 result.stopTest(self)
561 def collect_unittests(path, module_prefix, suite, selectors):
562 def file_matches(filename):
563 return filename.startswith("Test") and filename.endswith(".py")
565 def package_matches(dirname):
566 return dirname == "Tests"
568 loader = unittest.TestLoader()
572 for dirpath, dirnames, filenames in os.walk(path):
573 if dirpath != path and "__init__.py" not in filenames:
574 skipped_dirs.append(dirpath + os.path.sep)
577 for dir in skipped_dirs:
578 if dirpath.startswith(dir):
582 parentname = os.path.split(dirpath)[-1]
583 if package_matches(parentname):
586 filepath = os.path.join(dirpath, f)[:-len(".py")]
587 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
588 if not [ 1 for match in selectors if match(modulename) ]:
590 module = __import__(modulename)
591 for x in modulename.split('.')[1:]:
592 module = getattr(module, x)
593 suite.addTests([loader.loadTestsFromModule(module)])
595 def collect_doctests(path, module_prefix, suite, selectors):
596 def package_matches(dirname):
597 return dirname not in ("Mac", "Distutils", "Plex")
598 def file_matches(filename):
599 return (filename.endswith(".py") and not ('~' in filename
600 or '#' in filename or filename.startswith('.')))
601 import doctest, types
602 for dirpath, dirnames, filenames in os.walk(path):
603 parentname = os.path.split(dirpath)[-1]
604 if package_matches(parentname):
607 if not f.endswith('.py'): continue
608 filepath = os.path.join(dirpath, f)[:-len(".py")]
609 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
610 if not [ 1 for match in selectors if match(modulename) ]:
612 module = __import__(modulename)
613 for x in modulename.split('.')[1:]:
614 module = getattr(module, x)
615 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
617 suite.addTest(doctest.DocTestSuite(module))
618 except ValueError: # no tests
621 # TODO: Support cython_freeze needed here as well.
622 # TODO: Windows support.
624 class EmbedTest(unittest.TestCase):
626 working_dir = "Demos/embed"
629 self.old_dir = os.getcwd()
630 os.chdir(self.working_dir)
632 "make PYTHON='%s' clean > /dev/null" % sys.executable)
637 "make PYTHON='%s' clean > /dev/null" % sys.executable)
640 os.chdir(self.old_dir)
642 def test_embed(self):
643 self.assert_(os.system(
644 "make PYTHON='%s' test > make.output" % sys.executable) == 0)
646 os.remove('make.output')
650 class MissingDependencyExcluder:
651 def __init__(self, deps):
652 # deps: { module name : matcher func }
653 self.exclude_matchers = []
654 for mod, matcher in deps.items():
658 self.exclude_matchers.append(matcher)
659 self.tests_missing_deps = []
660 def __call__(self, testname):
661 for matcher in self.exclude_matchers:
662 if matcher(testname):
663 self.tests_missing_deps.append(testname)
667 class VersionDependencyExcluder:
668 def __init__(self, deps):
669 # deps: { version : matcher func }
670 from sys import version_info
671 self.exclude_matchers = []
672 for ver, (compare, matcher) in deps.items():
673 if compare(version_info, ver):
674 self.exclude_matchers.append(matcher)
675 self.tests_missing_deps = []
676 def __call__(self, testname):
677 for matcher in self.exclude_matchers:
678 if matcher(testname):
679 self.tests_missing_deps.append(testname)
683 class FileListExcluder:
685 def __init__(self, list_file):
687 for line in open(list_file).readlines():
689 if line and line[0] != '#':
690 self.excludes[line.split()[0]] = True
692 def __call__(self, testname):
693 return testname in self.excludes or testname.split('.')[-1] in self.excludes
695 def refactor_for_py3(distdir, cy3_dir):
696 # need to convert Cython sources first
697 import lib2to3.refactor
698 from distutils.util import copydir_run_2to3
699 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
700 if fix.split('fix_')[-1] not in ('next',)
702 if not os.path.exists(cy3_dir):
704 import distutils.log as dlog
705 dlog.set_threshold(dlog.DEBUG)
706 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
710 recursive-exclude Cython *
711 recursive-include Cython *.py *.pyx *.pxd
713 sys.path.insert(0, cy3_dir)
716 if __name__ == '__main__':
717 from optparse import OptionParser
718 parser = OptionParser()
719 parser.add_option("--no-cleanup", dest="cleanup_workdir",
720 action="store_false", default=True,
721 help="do not delete the generated C files (allows passing --no-cython on next run)")
722 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
723 action="store_false", default=True,
724 help="do not delete the generated shared libary files (allows manual module experimentation)")
725 parser.add_option("--no-cython", dest="with_cython",
726 action="store_false", default=True,
727 help="do not run the Cython compiler, only the C compiler")
728 parser.add_option("--no-c", dest="use_c",
729 action="store_false", default=True,
730 help="do not test C compilation")
731 parser.add_option("--no-cpp", dest="use_cpp",
732 action="store_false", default=True,
733 help="do not test C++ compilation")
734 parser.add_option("--no-unit", dest="unittests",
735 action="store_false", default=True,
736 help="do not run the unit tests")
737 parser.add_option("--no-doctest", dest="doctests",
738 action="store_false", default=True,
739 help="do not run the doctests")
740 parser.add_option("--no-file", dest="filetests",
741 action="store_false", default=True,
742 help="do not run the file based tests")
743 parser.add_option("--no-pyregr", dest="pyregr",
744 action="store_false", default=True,
745 help="do not run the regression tests of CPython in tests/pyregr/")
746 parser.add_option("--cython-only", dest="cython_only",
747 action="store_true", default=False,
748 help="only compile pyx to c, do not run C compiler or run the tests")
749 parser.add_option("--no-refnanny", dest="with_refnanny",
750 action="store_false", default=True,
751 help="do not regression test reference counting")
752 parser.add_option("--no-fork", dest="fork",
753 action="store_false", default=True,
754 help="do not fork to run tests")
755 parser.add_option("--sys-pyregr", dest="system_pyregr",
756 action="store_true", default=False,
757 help="run the regression tests of the CPython installation")
758 parser.add_option("-x", "--exclude", dest="exclude",
759 action="append", metavar="PATTERN",
760 help="exclude tests matching the PATTERN")
761 parser.add_option("-C", "--coverage", dest="coverage",
762 action="store_true", default=False,
763 help="collect source coverage data for the Compiler")
764 parser.add_option("--coverage-xml", dest="coverage_xml",
765 action="store_true", default=False,
766 help="collect source coverage data for the Compiler in XML format")
767 parser.add_option("-A", "--annotate", dest="annotate_source",
768 action="store_true", default=True,
769 help="generate annotated HTML versions of the test source files")
770 parser.add_option("--no-annotate", dest="annotate_source",
771 action="store_false",
772 help="do not generate annotated HTML versions of the test source files")
773 parser.add_option("-v", "--verbose", dest="verbosity",
774 action="count", default=0,
775 help="display test progress, pass twice to print test names")
776 parser.add_option("-T", "--ticket", dest="tickets",
778 help="a bug ticket number to run the respective test in 'tests/*'")
779 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
780 help="write test results in XML to directory DIR")
781 parser.add_option("--exit-ok", dest="exit_ok", default=False,
783 help="exit without error code even on test failures")
785 options, cmd_args = parser.parse_args()
787 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
788 ROOTDIR = os.path.join(DISTDIR, 'tests')
789 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
791 if sys.version_info[0] >= 3:
792 options.doctests = False
793 if options.with_cython:
795 # try if Cython is installed in a Py3 version
796 import Cython.Compiler.Main
798 cy_modules = [ name for name in sys.modules
799 if name == 'Cython' or name.startswith('Cython.') ]
800 for name in cy_modules:
801 del sys.modules[name]
802 # hasn't been refactored yet - do it now
803 cy3_dir = os.path.join(WORKDIR, 'Cy3')
804 if sys.version_info >= (3,1):
805 refactor_for_py3(DISTDIR, cy3_dir)
806 elif os.path.isdir(cy3_dir):
807 sys.path.insert(0, cy3_dir)
809 options.with_cython = False
811 WITH_CYTHON = options.with_cython
813 if options.coverage or options.coverage_xml:
815 options.coverage = options.coverage_xml = False
817 from coverage import coverage as _coverage
818 coverage = _coverage(branch=True)
823 from Cython.Compiler.Main import \
824 CompilationOptions, \
825 default_options as pyrex_default_options, \
826 compile as cython_compile
827 from Cython.Compiler import Errors
828 Errors.LEVEL = 0 # show all warnings
829 from Cython.Compiler import Options
830 Options.generate_cleanup_code = 3 # complete cleanup code
831 from Cython.Compiler import DebugFlags
832 DebugFlags.debug_temp_code_comments = 1
835 UNITTEST_MODULE = "Cython"
836 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
838 if os.path.exists(WORKDIR):
839 for path in os.listdir(WORKDIR):
840 if path in ("support", "Cy3"): continue
841 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
842 if not os.path.exists(WORKDIR):
846 from Cython.Compiler.Version import version
847 sys.stderr.write("Running tests against Cython %s\n" % version)
849 sys.stderr.write("Running tests without Cython.\n")
850 sys.stderr.write("Python %s\n" % sys.version)
851 sys.stderr.write("\n")
853 if options.with_refnanny:
854 from pyximport.pyxbuild import pyx_to_dll
855 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
857 pyxbuild_dir=os.path.join(WORKDIR, "support"))
858 sys.path.insert(0, os.path.split(libpath)[0])
859 CFLAGS.append("-DCYTHON_REFNANNY=1")
861 if options.xml_output_dir and options.fork:
862 # doesn't currently work together
863 sys.stderr.write("Disabling forked testing to support XML test output\n")
868 for ticket_number in options.tickets:
870 cmd_args.append('.*T%s$' % ticket_number)
872 for selector in cmd_args:
873 if selector.startswith('bugs'):
877 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
879 selectors = [ lambda x:True ]
881 # Chech which external modules are not present and exclude tests
882 # which depends on them (by prefix)
884 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
885 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
886 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
889 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
892 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
894 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
895 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
899 languages.append('c')
901 languages.append('cpp')
903 test_suite = unittest.TestSuite()
905 if options.unittests:
906 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
909 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
911 if options.filetests and languages:
912 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
913 options.annotate_source, options.cleanup_workdir,
914 options.cleanup_sharedlibs, options.pyregr,
915 options.cython_only, languages, test_bugs,
917 test_suite.addTest(filetests.build_suite())
919 if options.system_pyregr and languages:
920 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
921 options.annotate_source, options.cleanup_workdir,
922 options.cleanup_sharedlibs, True,
923 options.cython_only, languages, test_bugs,
926 filetests.handle_directory(
927 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
930 if options.xml_output_dir:
931 from Cython.Tests.xmlrunner import XMLTestRunner
932 test_runner = XMLTestRunner(output=options.xml_output_dir,
933 verbose=options.verbosity > 0)
935 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
937 result = test_runner.run(test_suite)
939 if options.coverage or options.coverage_xml:
941 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
942 modules = [ module for name, module in sys.modules.items()
943 if module is not None and
944 name.startswith('Cython.Compiler.') and
945 name[len('Cython.Compiler.'):] not in ignored_modules ]
947 coverage.report(modules, show_missing=0)
948 if options.coverage_xml:
949 coverage.xml_report(modules, outfile="coverage-report.xml")
951 if missing_dep_excluder.tests_missing_deps:
952 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
953 for test in missing_dep_excluder.tests_missing_deps:
954 sys.stderr.write(" %s\n" % test)
956 if options.with_refnanny:
958 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
963 sys.exit(not result.wasSuccessful())