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,
334 cython_compile(source, options=options,
335 full_module_name=module)
337 def run_distutils(self, test_directory, module, workdir, incdir):
341 build_extension = build_ext(distutils_distro)
342 build_extension.include_dirs = INCLUDE_DIRS[:]
344 build_extension.include_dirs.append(incdir)
345 build_extension.finalize_options()
346 ext_include_dirs = []
347 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
349 ext_include_dirs += get_additional_include_dirs()
350 self.copy_related_files(test_directory, workdir, module)
351 extension = Extension(
353 sources = self.find_source_files(workdir, module),
354 include_dirs = ext_include_dirs,
355 extra_compile_args = CFLAGS,
357 if self.language == 'cpp':
358 extension.language = 'c++'
359 build_extension.extensions = [extension]
360 build_extension.build_temp = workdir
361 build_extension.build_lib = workdir
362 build_extension.run()
366 def compile(self, test_directory, module, workdir, incdir,
367 expect_errors, annotate):
368 expected_errors = errors = ()
370 expected_errors = self.split_source_and_output(
371 test_directory, module, workdir)
372 test_directory = workdir
375 old_stderr = sys.stderr
377 sys.stderr = ErrorWriter()
378 self.run_cython(test_directory, module, workdir, incdir, annotate)
379 errors = sys.stderr.geterrors()
381 sys.stderr = old_stderr
383 if errors or expected_errors:
385 for expected, error in zip(expected_errors, errors):
386 self.assertEquals(expected, error)
387 if len(errors) < len(expected_errors):
388 expected_error = expected_errors[len(errors)]
389 self.assertEquals(expected_error, None)
390 elif len(errors) > len(expected_errors):
391 unexpected_error = errors[len(expected_errors)]
392 self.assertEquals(None, unexpected_error)
393 except AssertionError:
394 print("\n=== Expected errors: ===")
395 print('\n'.join(expected_errors))
396 print("\n\n=== Got errors: ===")
397 print('\n'.join(errors))
401 if not self.cython_only:
402 self.run_distutils(test_directory, module, workdir, incdir)
404 class CythonRunTestCase(CythonCompileTestCase):
405 def shortDescription(self):
406 return "compiling (%s) and running %s" % (self.language, self.module)
408 def run(self, result=None):
410 result = self.defaultTestResult()
411 result.startTest(self)
414 self.runCompileTest()
415 if not self.cython_only:
416 self.run_doctests(self.module, result)
418 result.addError(self, sys.exc_info())
419 result.stopTest(self)
425 def run_doctests(self, module_name, result):
426 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
427 doctest.DocTestSuite(module_name).run(result)
431 # fork to make sure we do not keep the tested module loaded
432 result_handle, result_file = tempfile.mkstemp()
433 os.close(result_handle)
441 partial_result = PartialTestResult(result)
442 tests = doctest.DocTestSuite(module_name)
443 tests.run(partial_result)
447 # importing failed, try to fake a test class
449 failureException=sys.exc_info()[1],
450 _shortDescription=self.shortDescription(),
452 partial_result.addError(tests, sys.exc_info())
454 output = open(result_file, 'wb')
455 pickle.dump(partial_result.data(), output)
458 traceback.print_exc()
462 os._exit(result_code)
465 cid, result_code = os.waitpid(child_id, 0)
466 # os.waitpid returns the child's result code in the
467 # upper byte of result_code, and the signal it was
468 # killed by in the lower byte
469 if result_code & 255:
470 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
471 (module_name, result_code & 255))
472 result_code = result_code >> 8
473 if result_code in (0,1):
474 input = open(result_file, 'rb')
476 PartialTestResult.join_results(result, pickle.load(input))
480 raise Exception("Tests in module '%s' exited with status %d" %
481 (module_name, result_code))
483 try: os.unlink(result_file)
487 is_private_field = re.compile('^_[^_]').match
489 class _FakeClass(object):
490 def __init__(self, **kwargs):
491 self._shortDescription = kwargs.get('module_name')
492 self.__dict__.update(kwargs)
493 def shortDescription(self):
494 return self._shortDescription
496 try: # Py2.7+ and Py3.2+
497 from unittest.runner import _TextTestResult
499 from unittest import _TextTestResult
501 class PartialTestResult(_TextTestResult):
502 def __init__(self, base_result):
503 _TextTestResult.__init__(
504 self, self._StringIO(), True,
505 base_result.dots + base_result.showAll*2)
507 def strip_error_results(self, results):
508 for test_case, error in results:
509 for attr_name in filter(is_private_field, dir(test_case)):
510 if attr_name == '_dt_test':
511 test_case._dt_test = _FakeClass(
512 name=test_case._dt_test.name)
513 elif attr_name != '_shortDescription':
514 setattr(test_case, attr_name, None)
517 self.strip_error_results(self.failures)
518 self.strip_error_results(self.errors)
519 return (self.failures, self.errors, self.testsRun,
520 self.stream.getvalue())
522 def join_results(result, data):
523 """Static method for merging the result back into the main
526 failures, errors, tests_run, output = data
528 result.stream.write(output)
529 result.errors.extend(errors)
530 result.failures.extend(failures)
531 result.testsRun += tests_run
533 join_results = staticmethod(join_results)
535 class _StringIO(StringIO):
536 def writeln(self, line):
537 self.write("%s\n" % line)
540 class CythonUnitTestCase(CythonCompileTestCase):
541 def shortDescription(self):
542 return "compiling (%s) tests in %s" % (self.language, self.module)
544 def run(self, result=None):
546 result = self.defaultTestResult()
547 result.startTest(self)
550 self.runCompileTest()
551 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
553 result.addError(self, sys.exc_info())
554 result.stopTest(self)
560 def collect_unittests(path, module_prefix, suite, selectors):
561 def file_matches(filename):
562 return filename.startswith("Test") and filename.endswith(".py")
564 def package_matches(dirname):
565 return dirname == "Tests"
567 loader = unittest.TestLoader()
571 for dirpath, dirnames, filenames in os.walk(path):
572 if dirpath != path and "__init__.py" not in filenames:
573 skipped_dirs.append(dirpath + os.path.sep)
576 for dir in skipped_dirs:
577 if dirpath.startswith(dir):
581 parentname = os.path.split(dirpath)[-1]
582 if package_matches(parentname):
585 filepath = os.path.join(dirpath, f)[:-len(".py")]
586 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
587 if not [ 1 for match in selectors if match(modulename) ]:
589 module = __import__(modulename)
590 for x in modulename.split('.')[1:]:
591 module = getattr(module, x)
592 suite.addTests([loader.loadTestsFromModule(module)])
594 def collect_doctests(path, module_prefix, suite, selectors):
595 def package_matches(dirname):
596 return dirname not in ("Mac", "Distutils", "Plex")
597 def file_matches(filename):
598 return (filename.endswith(".py") and not ('~' in filename
599 or '#' in filename or filename.startswith('.')))
600 import doctest, types
601 for dirpath, dirnames, filenames in os.walk(path):
602 parentname = os.path.split(dirpath)[-1]
603 if package_matches(parentname):
606 if not f.endswith('.py'): continue
607 filepath = os.path.join(dirpath, f)[:-len(".py")]
608 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
609 if not [ 1 for match in selectors if match(modulename) ]:
611 module = __import__(modulename)
612 for x in modulename.split('.')[1:]:
613 module = getattr(module, x)
614 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
616 suite.addTest(doctest.DocTestSuite(module))
617 except ValueError: # no tests
620 # TODO: Support cython_freeze needed here as well.
621 # TODO: Windows support.
623 class EmbedTest(unittest.TestCase):
625 working_dir = "Demos/embed"
628 self.old_dir = os.getcwd()
629 os.chdir(self.working_dir)
631 "make PYTHON='%s' clean > /dev/null" % sys.executable)
636 "make PYTHON='%s' clean > /dev/null" % sys.executable)
639 os.chdir(self.old_dir)
641 def test_embed(self):
642 self.assert_(os.system(
643 "make PYTHON='%s' test > make.output" % sys.executable) == 0)
645 os.remove('make.output')
649 class MissingDependencyExcluder:
650 def __init__(self, deps):
651 # deps: { module name : matcher func }
652 self.exclude_matchers = []
653 for mod, matcher in deps.items():
657 self.exclude_matchers.append(matcher)
658 self.tests_missing_deps = []
659 def __call__(self, testname):
660 for matcher in self.exclude_matchers:
661 if matcher(testname):
662 self.tests_missing_deps.append(testname)
666 class VersionDependencyExcluder:
667 def __init__(self, deps):
668 # deps: { version : matcher func }
669 from sys import version_info
670 self.exclude_matchers = []
671 for ver, (compare, matcher) in deps.items():
672 if compare(version_info, ver):
673 self.exclude_matchers.append(matcher)
674 self.tests_missing_deps = []
675 def __call__(self, testname):
676 for matcher in self.exclude_matchers:
677 if matcher(testname):
678 self.tests_missing_deps.append(testname)
682 class FileListExcluder:
684 def __init__(self, list_file):
686 for line in open(list_file).readlines():
688 if line and line[0] != '#':
689 self.excludes[line.split()[0]] = True
691 def __call__(self, testname):
692 return testname in self.excludes or testname.split('.')[-1] in self.excludes
694 def refactor_for_py3(distdir, cy3_dir):
695 # need to convert Cython sources first
696 import lib2to3.refactor
697 from distutils.util import copydir_run_2to3
698 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
699 if fix.split('fix_')[-1] not in ('next',)
701 if not os.path.exists(cy3_dir):
703 import distutils.log as dlog
704 dlog.set_threshold(dlog.DEBUG)
705 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
709 recursive-exclude Cython *
710 recursive-include Cython *.py *.pyx *.pxd
712 sys.path.insert(0, cy3_dir)
715 if __name__ == '__main__':
716 from optparse import OptionParser
717 parser = OptionParser()
718 parser.add_option("--no-cleanup", dest="cleanup_workdir",
719 action="store_false", default=True,
720 help="do not delete the generated C files (allows passing --no-cython on next run)")
721 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
722 action="store_false", default=True,
723 help="do not delete the generated shared libary files (allows manual module experimentation)")
724 parser.add_option("--no-cython", dest="with_cython",
725 action="store_false", default=True,
726 help="do not run the Cython compiler, only the C compiler")
727 parser.add_option("--no-c", dest="use_c",
728 action="store_false", default=True,
729 help="do not test C compilation")
730 parser.add_option("--no-cpp", dest="use_cpp",
731 action="store_false", default=True,
732 help="do not test C++ compilation")
733 parser.add_option("--no-unit", dest="unittests",
734 action="store_false", default=True,
735 help="do not run the unit tests")
736 parser.add_option("--no-doctest", dest="doctests",
737 action="store_false", default=True,
738 help="do not run the doctests")
739 parser.add_option("--no-file", dest="filetests",
740 action="store_false", default=True,
741 help="do not run the file based tests")
742 parser.add_option("--no-pyregr", dest="pyregr",
743 action="store_false", default=True,
744 help="do not run the regression tests of CPython in tests/pyregr/")
745 parser.add_option("--cython-only", dest="cython_only",
746 action="store_true", default=False,
747 help="only compile pyx to c, do not run C compiler or run the tests")
748 parser.add_option("--no-refnanny", dest="with_refnanny",
749 action="store_false", default=True,
750 help="do not regression test reference counting")
751 parser.add_option("--no-fork", dest="fork",
752 action="store_false", default=True,
753 help="do not fork to run tests")
754 parser.add_option("--sys-pyregr", dest="system_pyregr",
755 action="store_true", default=False,
756 help="run the regression tests of the CPython installation")
757 parser.add_option("-x", "--exclude", dest="exclude",
758 action="append", metavar="PATTERN",
759 help="exclude tests matching the PATTERN")
760 parser.add_option("-C", "--coverage", dest="coverage",
761 action="store_true", default=False,
762 help="collect source coverage data for the Compiler")
763 parser.add_option("--coverage-xml", dest="coverage_xml",
764 action="store_true", default=False,
765 help="collect source coverage data for the Compiler in XML format")
766 parser.add_option("-A", "--annotate", dest="annotate_source",
767 action="store_true", default=True,
768 help="generate annotated HTML versions of the test source files")
769 parser.add_option("--no-annotate", dest="annotate_source",
770 action="store_false",
771 help="do not generate annotated HTML versions of the test source files")
772 parser.add_option("-v", "--verbose", dest="verbosity",
773 action="count", default=0,
774 help="display test progress, pass twice to print test names")
775 parser.add_option("-T", "--ticket", dest="tickets",
777 help="a bug ticket number to run the respective test in 'tests/*'")
778 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
779 help="write test results in XML to directory DIR")
780 parser.add_option("--exit-ok", dest="exit_ok", default=False,
782 help="exit without error code even on test failures")
784 options, cmd_args = parser.parse_args()
786 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
787 ROOTDIR = os.path.join(DISTDIR, 'tests')
788 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
790 if sys.version_info[0] >= 3:
791 options.doctests = False
792 if options.with_cython:
794 # try if Cython is installed in a Py3 version
795 import Cython.Compiler.Main
797 cy_modules = [ name for name in sys.modules
798 if name == 'Cython' or name.startswith('Cython.') ]
799 for name in cy_modules:
800 del sys.modules[name]
801 # hasn't been refactored yet - do it now
802 cy3_dir = os.path.join(WORKDIR, 'Cy3')
803 if sys.version_info >= (3,1):
804 refactor_for_py3(DISTDIR, cy3_dir)
805 elif os.path.isdir(cy3_dir):
806 sys.path.insert(0, cy3_dir)
808 options.with_cython = False
810 WITH_CYTHON = options.with_cython
812 if options.coverage or options.coverage_xml:
814 options.coverage = options.coverage_xml = False
816 from coverage import coverage as _coverage
817 coverage = _coverage(branch=True)
822 from Cython.Compiler.Main import \
823 CompilationOptions, \
824 default_options as pyrex_default_options, \
825 compile as cython_compile
826 from Cython.Compiler import Errors
827 Errors.LEVEL = 0 # show all warnings
828 from Cython.Compiler import Options
829 Options.generate_cleanup_code = 3 # complete cleanup code
830 from Cython.Compiler import DebugFlags
831 DebugFlags.debug_temp_code_comments = 1
834 UNITTEST_MODULE = "Cython"
835 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
837 if os.path.exists(WORKDIR):
838 for path in os.listdir(WORKDIR):
839 if path in ("support", "Cy3"): continue
840 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
841 if not os.path.exists(WORKDIR):
845 from Cython.Compiler.Version import version
846 sys.stderr.write("Running tests against Cython %s\n" % version)
848 sys.stderr.write("Running tests without Cython.\n")
849 sys.stderr.write("Python %s\n" % sys.version)
850 sys.stderr.write("\n")
852 if options.with_refnanny:
853 from pyximport.pyxbuild import pyx_to_dll
854 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
856 pyxbuild_dir=os.path.join(WORKDIR, "support"))
857 sys.path.insert(0, os.path.split(libpath)[0])
858 CFLAGS.append("-DCYTHON_REFNANNY=1")
860 if options.xml_output_dir and options.fork:
861 # doesn't currently work together
862 sys.stderr.write("Disabling forked testing to support XML test output\n")
867 for ticket_number in options.tickets:
869 cmd_args.append('.*T%s$' % ticket_number)
871 for selector in cmd_args:
872 if selector.startswith('bugs'):
876 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
878 selectors = [ lambda x:True ]
880 # Chech which external modules are not present and exclude tests
881 # which depends on them (by prefix)
883 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
884 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
885 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
888 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
891 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
893 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
894 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
898 languages.append('c')
900 languages.append('cpp')
902 test_suite = unittest.TestSuite()
904 if options.unittests:
905 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
908 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
910 if options.filetests and languages:
911 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
912 options.annotate_source, options.cleanup_workdir,
913 options.cleanup_sharedlibs, options.pyregr,
914 options.cython_only, languages, test_bugs,
916 test_suite.addTest(filetests.build_suite())
918 if options.system_pyregr and languages:
919 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
920 options.annotate_source, options.cleanup_workdir,
921 options.cleanup_sharedlibs, True,
922 options.cython_only, languages, test_bugs,
925 filetests.handle_directory(
926 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
929 if options.xml_output_dir:
930 from Cython.Tests.xmlrunner import XMLTestRunner
931 test_runner = XMLTestRunner(output=options.xml_output_dir,
932 verbose=options.verbosity > 0)
934 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
936 result = test_runner.run(test_suite)
938 if options.coverage or options.coverage_xml:
940 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
941 modules = [ module for name, module in sys.modules.items()
942 if module is not None and
943 name.startswith('Cython.Compiler.') and
944 name[len('Cython.Compiler.'):] not in ignored_modules ]
946 coverage.report(modules, show_missing=0)
947 if options.coverage_xml:
948 coverage.xml_report(modules, outfile="coverage-report.xml")
950 if missing_dep_excluder.tests_missing_deps:
951 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
952 for test in missing_dep_excluder.tests_missing_deps:
953 sys.stderr.write(" %s\n" % test)
955 if options.with_refnanny:
957 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
962 sys.exit(not result.wasSuccessful())