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
41 def get_numpy_include_dirs():
43 return [numpy.get_include()]
46 # test name matcher , callable returning list
47 (re.compile('numpy_.*').match, get_numpy_include_dirs),
51 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
52 # (2,4) : (operator.le, ...) excludes ... when PyVer <= 2.4.x
53 (2,4) : (operator.le, lambda x: x in ['run.extern_builtins_T258'
55 (2,6) : (operator.lt, lambda x: x in ['run.print_function'
57 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
58 'compile.extsetslice',
59 'compile.extdelslice']),
62 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
63 CFLAGS = os.getenv('CFLAGS', '').split()
65 class build_ext(_build_ext):
66 def build_extension(self, ext):
67 if ext.language == 'c++':
69 try: # Py2.7+ & Py3.2+
70 compiler_obj = self.compiler_obj
71 except AttributeError:
72 compiler_obj = self.compiler
73 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
76 _build_ext.build_extension(self, ext)
78 class ErrorWriter(object):
79 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
82 self.write = self.output.append
84 def _collect(self, collect_errors, collect_warnings):
85 s = ''.join(self.output)
87 for line in s.split('\n'):
88 match = self.match_error(line)
90 is_warning, line, column, message = match.groups()
91 if (is_warning and collect_warnings) or \
92 (not is_warning and collect_errors):
93 result.append( (int(line), int(column), message.strip()) )
95 return [ "%d:%d: %s" % values for values in result ]
98 return self._collect(True, False)
100 def getwarnings(self):
101 return self._collect(False, True)
104 return self._collect(True, True)
106 class TestBuilder(object):
107 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
108 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
109 languages, test_bugs, fork):
110 self.rootdir = rootdir
111 self.workdir = workdir
112 self.selectors = selectors
113 self.exclude_selectors = exclude_selectors
114 self.annotate = annotate
115 self.cleanup_workdir = cleanup_workdir
116 self.cleanup_sharedlibs = cleanup_sharedlibs
117 self.with_pyregr = with_pyregr
118 self.cython_only = cython_only
119 self.languages = languages
120 self.test_bugs = test_bugs
123 def build_suite(self):
124 suite = unittest.TestSuite()
125 test_dirs = TEST_DIRS
126 filenames = os.listdir(self.rootdir)
128 for filename in filenames:
129 if not WITH_CYTHON and filename == "errors":
130 # we won't get any errors without running Cython
132 path = os.path.join(self.rootdir, filename)
133 if os.path.isdir(path) and filename in test_dirs:
134 if filename == 'pyregr' and not self.with_pyregr:
137 self.handle_directory(path, filename))
138 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
139 # Non-Windows makefile, can't run Cython under Py3.
140 if [1 for selector in self.selectors if selector("embedded")]:
141 suite.addTest(unittest.makeSuite(EmbedTest))
144 def handle_directory(self, path, context):
145 workdir = os.path.join(self.workdir, context)
146 if not os.path.exists(workdir):
149 expect_errors = (context == 'errors')
150 suite = unittest.TestSuite()
151 filenames = os.listdir(path)
153 for filename in filenames:
154 if not (filename.endswith(".pyx") or filename.endswith(".py")):
156 if filename.startswith('.'): continue # certain emacs backup files
157 if context == 'pyregr' and not filename.startswith('test_'):
159 module = os.path.splitext(filename)[0]
160 fqmodule = "%s.%s" % (context, module)
161 if not [ 1 for match in self.selectors
162 if match(fqmodule) ]:
164 if self.exclude_selectors:
165 if [1 for match in self.exclude_selectors if match(fqmodule)]:
167 if context in TEST_RUN_DIRS:
168 if module.startswith("test_"):
169 test_class = CythonUnitTestCase
171 test_class = CythonRunTestCase
173 test_class = CythonCompileTestCase
174 for test in self.build_tests(test_class, path, workdir,
175 module, expect_errors):
179 def build_tests(self, test_class, path, workdir, module, expect_errors):
181 if 'cpp' in module and 'cpp' in self.languages:
184 languages = self.languages[:1]
186 languages = self.languages
187 if 'cpp' in module and 'c' in languages:
188 languages = list(languages)
189 languages.remove('c')
190 tests = [ self.build_test(test_class, path, workdir, module,
191 language, expect_errors)
192 for language in languages ]
195 def build_test(self, test_class, path, workdir, module,
196 language, expect_errors):
197 workdir = os.path.join(workdir, language)
198 if not os.path.exists(workdir):
200 return test_class(path, workdir, module,
202 expect_errors=expect_errors,
203 annotate=self.annotate,
204 cleanup_workdir=self.cleanup_workdir,
205 cleanup_sharedlibs=self.cleanup_sharedlibs,
206 cython_only=self.cython_only,
209 class CythonCompileTestCase(unittest.TestCase):
210 def __init__(self, test_directory, workdir, module, language='c',
211 expect_errors=False, annotate=False, cleanup_workdir=True,
212 cleanup_sharedlibs=True, cython_only=False, fork=True):
213 self.test_directory = test_directory
214 self.workdir = workdir
216 self.language = language
217 self.expect_errors = expect_errors
218 self.annotate = annotate
219 self.cleanup_workdir = cleanup_workdir
220 self.cleanup_sharedlibs = cleanup_sharedlibs
221 self.cython_only = cython_only
223 unittest.TestCase.__init__(self)
225 def shortDescription(self):
226 return "compiling (%s) %s" % (self.language, self.module)
229 if self.workdir not in sys.path:
230 sys.path.insert(0, self.workdir)
234 sys.path.remove(self.workdir)
238 del sys.modules[self.module]
241 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
242 cleanup_lib_files = self.cleanup_sharedlibs
243 if os.path.exists(self.workdir):
244 for rmfile in os.listdir(self.workdir):
245 if not cleanup_c_files:
246 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
248 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
250 if self.annotate and rmfile.endswith(".html"):
253 rmfile = os.path.join(self.workdir, rmfile)
254 if os.path.isdir(rmfile):
255 shutil.rmtree(rmfile, ignore_errors=True)
261 os.makedirs(self.workdir)
264 self.runCompileTest()
266 def runCompileTest(self):
267 self.compile(self.test_directory, self.module, self.workdir,
268 self.test_directory, self.expect_errors, self.annotate)
270 def find_module_source_file(self, source_file):
271 if not os.path.exists(source_file):
272 source_file = source_file[:-1]
275 def build_target_filename(self, module_name):
276 target = '%s.%s' % (module_name, self.language)
279 def copy_related_files(self, test_directory, target_directory, module_name):
280 is_related = re.compile('%s_.*[.].*' % module_name).match
281 for filename in os.listdir(test_directory):
282 if is_related(filename):
283 shutil.copy(os.path.join(test_directory, filename),
286 def find_source_files(self, workdir, module_name):
287 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
288 return [self.build_target_filename(module_name)] + [
289 filename for filename in os.listdir(workdir)
290 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
292 def split_source_and_output(self, test_directory, module, workdir):
293 source_file = os.path.join(test_directory, module) + '.pyx'
294 source_and_output = codecs.open(
295 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
296 out = codecs.open(os.path.join(workdir, module + '.pyx'),
298 for line in source_and_output:
300 if line.startswith("_ERRORS"):
306 geterrors = out.geterrors
307 except AttributeError:
312 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
313 include_dirs = INCLUDE_DIRS[:]
315 include_dirs.append(incdir)
316 source = self.find_module_source_file(
317 os.path.join(test_directory, module + '.pyx'))
318 target = os.path.join(targetdir, self.build_target_filename(module))
319 options = CompilationOptions(
320 pyrex_default_options,
321 include_path = include_dirs,
322 output_file = target,
324 use_listing_file = False,
325 cplus = self.language == 'cpp',
326 generate_pxi = False,
327 evaluate_tree_assertions = True,
329 cython_compile(source, options=options,
330 full_module_name=module)
332 def run_distutils(self, test_directory, module, workdir, incdir):
336 build_extension = build_ext(distutils_distro)
337 build_extension.include_dirs = INCLUDE_DIRS[:]
339 build_extension.include_dirs.append(incdir)
340 build_extension.finalize_options()
341 ext_include_dirs = []
342 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
344 ext_include_dirs += get_additional_include_dirs()
345 self.copy_related_files(test_directory, workdir, module)
346 extension = Extension(
348 sources = self.find_source_files(workdir, module),
349 include_dirs = ext_include_dirs,
350 extra_compile_args = CFLAGS,
352 if self.language == 'cpp':
353 extension.language = 'c++'
354 build_extension.extensions = [extension]
355 build_extension.build_temp = workdir
356 build_extension.build_lib = workdir
357 build_extension.run()
361 def compile(self, test_directory, module, workdir, incdir,
362 expect_errors, annotate):
363 expected_errors = errors = ()
365 expected_errors = self.split_source_and_output(
366 test_directory, module, workdir)
367 test_directory = workdir
370 old_stderr = sys.stderr
372 sys.stderr = ErrorWriter()
373 self.run_cython(test_directory, module, workdir, incdir, annotate)
374 errors = sys.stderr.geterrors()
376 sys.stderr = old_stderr
378 if errors or expected_errors:
380 for expected, error in zip(expected_errors, errors):
381 self.assertEquals(expected, error)
382 if len(errors) < len(expected_errors):
383 expected_error = expected_errors[len(errors)]
384 self.assertEquals(expected_error, None)
385 elif len(errors) > len(expected_errors):
386 unexpected_error = errors[len(expected_errors)]
387 self.assertEquals(None, unexpected_error)
388 except AssertionError:
389 print("\n=== Expected errors: ===")
390 print('\n'.join(expected_errors))
391 print("\n\n=== Got errors: ===")
392 print('\n'.join(errors))
396 if not self.cython_only:
397 self.run_distutils(test_directory, module, workdir, incdir)
399 class CythonRunTestCase(CythonCompileTestCase):
400 def shortDescription(self):
401 return "compiling (%s) and running %s" % (self.language, self.module)
403 def run(self, result=None):
405 result = self.defaultTestResult()
406 result.startTest(self)
409 self.runCompileTest()
410 if not self.cython_only:
411 self.run_doctests(self.module, result)
413 result.addError(self, sys.exc_info())
414 result.stopTest(self)
420 def run_doctests(self, module_name, result):
421 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
422 doctest.DocTestSuite(module_name).run(result)
426 # fork to make sure we do not keep the tested module loaded
427 result_handle, result_file = tempfile.mkstemp()
428 os.close(result_handle)
436 partial_result = PartialTestResult(result)
437 tests = doctest.DocTestSuite(module_name)
438 tests.run(partial_result)
442 # importing failed, try to fake a test class
444 failureException=sys.exc_info()[1],
445 _shortDescription=self.shortDescription(),
447 partial_result.addError(tests, sys.exc_info())
449 output = open(result_file, 'wb')
450 pickle.dump(partial_result.data(), output)
453 traceback.print_exc()
457 os._exit(result_code)
460 cid, result_code = os.waitpid(child_id, 0)
461 # os.waitpid returns the child's result code in the
462 # upper byte of result_code, and the signal it was
463 # killed by in the lower byte
464 if result_code & 255:
465 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
466 (module_name, result_code & 255))
467 result_code = result_code >> 8
468 if result_code in (0,1):
469 input = open(result_file, 'rb')
471 PartialTestResult.join_results(result, pickle.load(input))
475 raise Exception("Tests in module '%s' exited with status %d" %
476 (module_name, result_code))
478 try: os.unlink(result_file)
482 is_private_field = re.compile('^_[^_]').match
484 class _FakeClass(object):
485 def __init__(self, **kwargs):
486 self._shortDescription = kwargs.get('module_name')
487 self.__dict__.update(kwargs)
488 def shortDescription(self):
489 return self._shortDescription
491 try: # Py2.7+ and Py3.2+
492 from unittest.runner import _TextTestResult
494 from unittest import _TextTestResult
496 class PartialTestResult(_TextTestResult):
497 def __init__(self, base_result):
498 _TextTestResult.__init__(
499 self, self._StringIO(), True,
500 base_result.dots + base_result.showAll*2)
502 def strip_error_results(self, results):
503 for test_case, error in results:
504 for attr_name in filter(is_private_field, dir(test_case)):
505 if attr_name == '_dt_test':
506 test_case._dt_test = _FakeClass(
507 name=test_case._dt_test.name)
508 elif attr_name != '_shortDescription':
509 setattr(test_case, attr_name, None)
512 self.strip_error_results(self.failures)
513 self.strip_error_results(self.errors)
514 return (self.failures, self.errors, self.testsRun,
515 self.stream.getvalue())
517 def join_results(result, data):
518 """Static method for merging the result back into the main
521 failures, errors, tests_run, output = data
523 result.stream.write(output)
524 result.errors.extend(errors)
525 result.failures.extend(failures)
526 result.testsRun += tests_run
528 join_results = staticmethod(join_results)
530 class _StringIO(StringIO):
531 def writeln(self, line):
532 self.write("%s\n" % line)
535 class CythonUnitTestCase(CythonCompileTestCase):
536 def shortDescription(self):
537 return "compiling (%s) tests in %s" % (self.language, self.module)
539 def run(self, result=None):
541 result = self.defaultTestResult()
542 result.startTest(self)
545 self.runCompileTest()
546 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
548 result.addError(self, sys.exc_info())
549 result.stopTest(self)
555 def collect_unittests(path, module_prefix, suite, selectors):
556 def file_matches(filename):
557 return filename.startswith("Test") and filename.endswith(".py")
559 def package_matches(dirname):
560 return dirname == "Tests"
562 loader = unittest.TestLoader()
566 for dirpath, dirnames, filenames in os.walk(path):
567 if dirpath != path and "__init__.py" not in filenames:
568 skipped_dirs.append(dirpath + os.path.sep)
571 for dir in skipped_dirs:
572 if dirpath.startswith(dir):
576 parentname = os.path.split(dirpath)[-1]
577 if package_matches(parentname):
580 filepath = os.path.join(dirpath, f)[:-len(".py")]
581 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
582 if not [ 1 for match in selectors if match(modulename) ]:
584 module = __import__(modulename)
585 for x in modulename.split('.')[1:]:
586 module = getattr(module, x)
587 suite.addTests([loader.loadTestsFromModule(module)])
589 def collect_doctests(path, module_prefix, suite, selectors):
590 def package_matches(dirname):
591 return dirname not in ("Mac", "Distutils", "Plex")
592 def file_matches(filename):
593 return (filename.endswith(".py") and not ('~' in filename
594 or '#' in filename or filename.startswith('.')))
595 import doctest, types
596 for dirpath, dirnames, filenames in os.walk(path):
597 parentname = os.path.split(dirpath)[-1]
598 if package_matches(parentname):
601 if not f.endswith('.py'): continue
602 filepath = os.path.join(dirpath, f)[:-len(".py")]
603 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
604 if not [ 1 for match in selectors if match(modulename) ]:
606 module = __import__(modulename)
607 for x in modulename.split('.')[1:]:
608 module = getattr(module, x)
609 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
611 suite.addTest(doctest.DocTestSuite(module))
612 except ValueError: # no tests
615 # TODO: Support cython_freeze needed here as well.
616 # TODO: Windows support.
618 class EmbedTest(unittest.TestCase):
620 working_dir = "Demos/embed"
623 self.old_dir = os.getcwd()
624 os.chdir(self.working_dir)
626 "make PYTHON='%s' clean > /dev/null" % sys.executable)
631 "make PYTHON='%s' clean > /dev/null" % sys.executable)
634 os.chdir(self.old_dir)
636 def test_embed(self):
637 self.assert_(os.system(
638 "make PYTHON='%s' test > make.output" % sys.executable) == 0)
640 os.remove('make.output')
644 class MissingDependencyExcluder:
645 def __init__(self, deps):
646 # deps: { module name : matcher func }
647 self.exclude_matchers = []
648 for mod, matcher in deps.items():
652 self.exclude_matchers.append(matcher)
653 self.tests_missing_deps = []
654 def __call__(self, testname):
655 for matcher in self.exclude_matchers:
656 if matcher(testname):
657 self.tests_missing_deps.append(testname)
661 class VersionDependencyExcluder:
662 def __init__(self, deps):
663 # deps: { version : matcher func }
664 from sys import version_info
665 self.exclude_matchers = []
666 for ver, (compare, matcher) in deps.items():
667 if compare(version_info, ver):
668 self.exclude_matchers.append(matcher)
669 self.tests_missing_deps = []
670 def __call__(self, testname):
671 for matcher in self.exclude_matchers:
672 if matcher(testname):
673 self.tests_missing_deps.append(testname)
677 class FileListExcluder:
679 def __init__(self, list_file):
681 for line in open(list_file).readlines():
683 if line and line[0] != '#':
684 self.excludes[line.split()[0]] = True
686 def __call__(self, testname):
687 return testname in self.excludes or testname.split('.')[-1] in self.excludes
689 def refactor_for_py3(distdir, cy3_dir):
690 # need to convert Cython sources first
691 import lib2to3.refactor
692 from distutils.util import copydir_run_2to3
693 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
694 if fix.split('fix_')[-1] not in ('next',)
696 if not os.path.exists(cy3_dir):
698 import distutils.log as dlog
699 dlog.set_threshold(dlog.DEBUG)
700 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
704 recursive-exclude Cython *
705 recursive-include Cython *.py *.pyx *.pxd
707 sys.path.insert(0, cy3_dir)
710 if __name__ == '__main__':
711 from optparse import OptionParser
712 parser = OptionParser()
713 parser.add_option("--no-cleanup", dest="cleanup_workdir",
714 action="store_false", default=True,
715 help="do not delete the generated C files (allows passing --no-cython on next run)")
716 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
717 action="store_false", default=True,
718 help="do not delete the generated shared libary files (allows manual module experimentation)")
719 parser.add_option("--no-cython", dest="with_cython",
720 action="store_false", default=True,
721 help="do not run the Cython compiler, only the C compiler")
722 parser.add_option("--no-c", dest="use_c",
723 action="store_false", default=True,
724 help="do not test C compilation")
725 parser.add_option("--no-cpp", dest="use_cpp",
726 action="store_false", default=True,
727 help="do not test C++ compilation")
728 parser.add_option("--no-unit", dest="unittests",
729 action="store_false", default=True,
730 help="do not run the unit tests")
731 parser.add_option("--no-doctest", dest="doctests",
732 action="store_false", default=True,
733 help="do not run the doctests")
734 parser.add_option("--no-file", dest="filetests",
735 action="store_false", default=True,
736 help="do not run the file based tests")
737 parser.add_option("--no-pyregr", dest="pyregr",
738 action="store_false", default=True,
739 help="do not run the regression tests of CPython in tests/pyregr/")
740 parser.add_option("--cython-only", dest="cython_only",
741 action="store_true", default=False,
742 help="only compile pyx to c, do not run C compiler or run the tests")
743 parser.add_option("--no-refnanny", dest="with_refnanny",
744 action="store_false", default=True,
745 help="do not regression test reference counting")
746 parser.add_option("--no-fork", dest="fork",
747 action="store_false", default=True,
748 help="do not fork to run tests")
749 parser.add_option("--sys-pyregr", dest="system_pyregr",
750 action="store_true", default=False,
751 help="run the regression tests of the CPython installation")
752 parser.add_option("-x", "--exclude", dest="exclude",
753 action="append", metavar="PATTERN",
754 help="exclude tests matching the PATTERN")
755 parser.add_option("-C", "--coverage", dest="coverage",
756 action="store_true", default=False,
757 help="collect source coverage data for the Compiler")
758 parser.add_option("--coverage-xml", dest="coverage_xml",
759 action="store_true", default=False,
760 help="collect source coverage data for the Compiler in XML format")
761 parser.add_option("-A", "--annotate", dest="annotate_source",
762 action="store_true", default=True,
763 help="generate annotated HTML versions of the test source files")
764 parser.add_option("--no-annotate", dest="annotate_source",
765 action="store_false",
766 help="do not generate annotated HTML versions of the test source files")
767 parser.add_option("-v", "--verbose", dest="verbosity",
768 action="count", default=0,
769 help="display test progress, pass twice to print test names")
770 parser.add_option("-T", "--ticket", dest="tickets",
772 help="a bug ticket number to run the respective test in 'tests/*'")
773 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
774 help="write test results in XML to directory DIR")
775 parser.add_option("--exit-ok", dest="exit_ok", default=False,
777 help="exit without error code even on test failures")
779 options, cmd_args = parser.parse_args()
781 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
782 ROOTDIR = os.path.join(DISTDIR, 'tests')
783 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
785 if sys.version_info[0] >= 3:
786 options.doctests = False
787 options.pyregr = False
788 if options.with_cython:
790 # try if Cython is installed in a Py3 version
791 import Cython.Compiler.Main
793 cy_modules = [ name for name in sys.modules
794 if name == 'Cython' or name.startswith('Cython.') ]
795 for name in cy_modules:
796 del sys.modules[name]
797 # hasn't been refactored yet - do it now
798 cy3_dir = os.path.join(WORKDIR, 'Cy3')
799 if sys.version_info >= (3,1):
800 refactor_for_py3(DISTDIR, cy3_dir)
801 elif os.path.isdir(cy3_dir):
802 sys.path.insert(0, cy3_dir)
804 options.with_cython = False
806 WITH_CYTHON = options.with_cython
808 if options.coverage or options.coverage_xml:
810 options.coverage = False
812 from coverage import coverage as _coverage
813 coverage = _coverage()
818 from Cython.Compiler.Main import \
819 CompilationOptions, \
820 default_options as pyrex_default_options, \
821 compile as cython_compile
822 from Cython.Compiler import Errors
823 Errors.LEVEL = 0 # show all warnings
824 from Cython.Compiler import Options
825 Options.generate_cleanup_code = 3 # complete cleanup code
826 from Cython.Compiler import DebugFlags
827 DebugFlags.debug_temp_code_comments = 1
830 UNITTEST_MODULE = "Cython"
831 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
833 if os.path.exists(WORKDIR):
834 for path in os.listdir(WORKDIR):
835 if path in ("support", "Cy3"): continue
836 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
837 if not os.path.exists(WORKDIR):
841 from Cython.Compiler.Version import version
842 sys.stderr.write("Running tests against Cython %s\n" % version)
844 sys.stderr.write("Running tests without Cython.\n")
845 sys.stderr.write("Python %s\n" % sys.version)
846 sys.stderr.write("\n")
848 if options.with_refnanny:
849 from pyximport.pyxbuild import pyx_to_dll
850 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
852 pyxbuild_dir=os.path.join(WORKDIR, "support"))
853 sys.path.insert(0, os.path.split(libpath)[0])
854 CFLAGS.append("-DCYTHON_REFNANNY=1")
856 if options.xml_output_dir and options.fork:
857 # doesn't currently work together
858 sys.stderr.write("Disabling forked testing to support XML test output\n")
863 for ticket_number in options.tickets:
865 cmd_args.append('.*T%s$' % ticket_number)
867 for selector in cmd_args:
868 if selector.startswith('bugs'):
872 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
874 selectors = [ lambda x:True ]
876 # Chech which external modules are not present and exclude tests
877 # which depends on them (by prefix)
879 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
880 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
881 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
884 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
887 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
889 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
890 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
894 languages.append('c')
896 languages.append('cpp')
898 test_suite = unittest.TestSuite()
900 if options.unittests:
901 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
904 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
906 if options.filetests and languages:
907 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
908 options.annotate_source, options.cleanup_workdir,
909 options.cleanup_sharedlibs, options.pyregr,
910 options.cython_only, languages, test_bugs,
912 test_suite.addTest(filetests.build_suite())
914 if options.system_pyregr and languages:
915 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
916 options.annotate_source, options.cleanup_workdir,
917 options.cleanup_sharedlibs, True,
918 options.cython_only, languages, test_bugs,
921 filetests.handle_directory(
922 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
925 if options.xml_output_dir:
926 from Cython.Tests.xmlrunner import XMLTestRunner
927 test_runner = XMLTestRunner(output=options.xml_output_dir,
928 verbose=options.verbosity > 0)
930 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
932 result = test_runner.run(test_suite)
934 if options.coverage or options.coverage_xml:
936 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
937 modules = [ module for name, module in sys.modules.items()
938 if module is not None and
939 name.startswith('Cython.Compiler.') and
940 name[len('Cython.Compiler.'):] not in ignored_modules ]
942 coverage.report(modules, show_missing=0)
943 if options.coverage_xml:
944 coverage.xml_report(modules, outfile="coverage-report.xml")
946 if missing_dep_excluder.tests_missing_deps:
947 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
948 for test in missing_dep_excluder.tests_missing_deps:
949 sys.stderr.write(" %s\n" % test)
951 if options.with_refnanny:
953 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
958 sys.exit(not result.wasSuccessful())