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'
61 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
62 'compile.extsetslice',
63 'compile.extdelslice']),
66 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
67 CFLAGS = os.getenv('CFLAGS', '').split()
69 class build_ext(_build_ext):
70 def build_extension(self, ext):
71 if ext.language == 'c++':
73 try: # Py2.7+ & Py3.2+
74 compiler_obj = self.compiler_obj
75 except AttributeError:
76 compiler_obj = self.compiler
77 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
80 _build_ext.build_extension(self, ext)
82 class ErrorWriter(object):
83 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
86 self.write = self.output.append
88 def _collect(self, collect_errors, collect_warnings):
89 s = ''.join(self.output)
91 for line in s.split('\n'):
92 match = self.match_error(line)
94 is_warning, line, column, message = match.groups()
95 if (is_warning and collect_warnings) or \
96 (not is_warning and collect_errors):
97 result.append( (int(line), int(column), message.strip()) )
99 return [ "%d:%d: %s" % values for values in result ]
102 return self._collect(True, False)
104 def getwarnings(self):
105 return self._collect(False, True)
108 return self._collect(True, True)
110 class TestBuilder(object):
111 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
112 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
113 languages, test_bugs, fork):
114 self.rootdir = rootdir
115 self.workdir = workdir
116 self.selectors = selectors
117 self.exclude_selectors = exclude_selectors
118 self.annotate = annotate
119 self.cleanup_workdir = cleanup_workdir
120 self.cleanup_sharedlibs = cleanup_sharedlibs
121 self.with_pyregr = with_pyregr
122 self.cython_only = cython_only
123 self.languages = languages
124 self.test_bugs = test_bugs
127 def build_suite(self):
128 suite = unittest.TestSuite()
129 test_dirs = TEST_DIRS
130 filenames = os.listdir(self.rootdir)
132 for filename in filenames:
133 if not WITH_CYTHON and filename == "errors":
134 # we won't get any errors without running Cython
136 path = os.path.join(self.rootdir, filename)
137 if os.path.isdir(path) and filename in test_dirs:
138 if filename == 'pyregr' and not self.with_pyregr:
141 self.handle_directory(path, filename))
142 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
143 # Non-Windows makefile, can't run Cython under Py3.
144 if [1 for selector in self.selectors if selector("embedded")]:
145 suite.addTest(unittest.makeSuite(EmbedTest))
148 def handle_directory(self, path, context):
149 workdir = os.path.join(self.workdir, context)
150 if not os.path.exists(workdir):
153 expect_errors = (context == 'errors')
154 suite = unittest.TestSuite()
155 filenames = os.listdir(path)
157 for filename in filenames:
158 if not (filename.endswith(".pyx") or filename.endswith(".py")):
160 if filename.startswith('.'): continue # certain emacs backup files
161 if context == 'pyregr' and not filename.startswith('test_'):
163 module = os.path.splitext(filename)[0]
164 fqmodule = "%s.%s" % (context, module)
165 if not [ 1 for match in self.selectors
166 if match(fqmodule) ]:
168 if self.exclude_selectors:
169 if [1 for match in self.exclude_selectors if match(fqmodule)]:
171 if context in TEST_RUN_DIRS:
172 if module.startswith("test_"):
173 test_class = CythonUnitTestCase
175 test_class = CythonRunTestCase
177 test_class = CythonCompileTestCase
178 for test in self.build_tests(test_class, path, workdir,
179 module, expect_errors):
183 def build_tests(self, test_class, path, workdir, module, expect_errors):
185 if 'cpp' in module and 'cpp' in self.languages:
188 languages = self.languages[:1]
190 languages = self.languages
191 if 'cpp' in module and 'c' in languages:
192 languages = list(languages)
193 languages.remove('c')
194 tests = [ self.build_test(test_class, path, workdir, module,
195 language, expect_errors)
196 for language in languages ]
199 def build_test(self, test_class, path, workdir, module,
200 language, expect_errors):
201 workdir = os.path.join(workdir, language)
202 if not os.path.exists(workdir):
204 return test_class(path, workdir, module,
206 expect_errors=expect_errors,
207 annotate=self.annotate,
208 cleanup_workdir=self.cleanup_workdir,
209 cleanup_sharedlibs=self.cleanup_sharedlibs,
210 cython_only=self.cython_only,
213 class CythonCompileTestCase(unittest.TestCase):
214 def __init__(self, test_directory, workdir, module, language='c',
215 expect_errors=False, annotate=False, cleanup_workdir=True,
216 cleanup_sharedlibs=True, cython_only=False, fork=True):
217 self.test_directory = test_directory
218 self.workdir = workdir
220 self.language = language
221 self.expect_errors = expect_errors
222 self.annotate = annotate
223 self.cleanup_workdir = cleanup_workdir
224 self.cleanup_sharedlibs = cleanup_sharedlibs
225 self.cython_only = cython_only
227 unittest.TestCase.__init__(self)
229 def shortDescription(self):
230 return "compiling (%s) %s" % (self.language, self.module)
233 if self.workdir not in sys.path:
234 sys.path.insert(0, self.workdir)
238 sys.path.remove(self.workdir)
242 del sys.modules[self.module]
245 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
246 cleanup_lib_files = self.cleanup_sharedlibs
247 if os.path.exists(self.workdir):
248 for rmfile in os.listdir(self.workdir):
249 if not cleanup_c_files:
250 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
252 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
254 if self.annotate and rmfile.endswith(".html"):
257 rmfile = os.path.join(self.workdir, rmfile)
258 if os.path.isdir(rmfile):
259 shutil.rmtree(rmfile, ignore_errors=True)
265 os.makedirs(self.workdir)
268 self.runCompileTest()
270 def runCompileTest(self):
271 self.compile(self.test_directory, self.module, self.workdir,
272 self.test_directory, self.expect_errors, self.annotate)
274 def find_module_source_file(self, source_file):
275 if not os.path.exists(source_file):
276 source_file = source_file[:-1]
279 def build_target_filename(self, module_name):
280 target = '%s.%s' % (module_name, self.language)
283 def copy_related_files(self, test_directory, target_directory, module_name):
284 is_related = re.compile('%s_.*[.].*' % module_name).match
285 for filename in os.listdir(test_directory):
286 if is_related(filename):
287 shutil.copy(os.path.join(test_directory, filename),
290 def find_source_files(self, workdir, module_name):
291 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
292 return [self.build_target_filename(module_name)] + [
293 filename for filename in os.listdir(workdir)
294 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
296 def split_source_and_output(self, test_directory, module, workdir):
297 source_file = os.path.join(test_directory, module) + '.pyx'
298 source_and_output = codecs.open(
299 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
300 out = codecs.open(os.path.join(workdir, module + '.pyx'),
302 for line in source_and_output:
304 if line.startswith("_ERRORS"):
310 geterrors = out.geterrors
311 except AttributeError:
316 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
317 include_dirs = INCLUDE_DIRS[:]
319 include_dirs.append(incdir)
320 source = self.find_module_source_file(
321 os.path.join(test_directory, module + '.pyx'))
322 target = os.path.join(targetdir, self.build_target_filename(module))
323 options = CompilationOptions(
324 pyrex_default_options,
325 include_path = include_dirs,
326 output_file = target,
328 use_listing_file = False,
329 cplus = self.language == 'cpp',
330 generate_pxi = False,
331 evaluate_tree_assertions = True,
333 cython_compile(source, options=options,
334 full_module_name=module)
336 def run_distutils(self, test_directory, module, workdir, incdir):
340 build_extension = build_ext(distutils_distro)
341 build_extension.include_dirs = INCLUDE_DIRS[:]
343 build_extension.include_dirs.append(incdir)
344 build_extension.finalize_options()
345 ext_include_dirs = []
346 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
348 ext_include_dirs += get_additional_include_dirs()
349 self.copy_related_files(test_directory, workdir, module)
350 extension = Extension(
352 sources = self.find_source_files(workdir, module),
353 include_dirs = ext_include_dirs,
354 extra_compile_args = CFLAGS,
356 if self.language == 'cpp':
357 extension.language = 'c++'
358 build_extension.extensions = [extension]
359 build_extension.build_temp = workdir
360 build_extension.build_lib = workdir
361 build_extension.run()
365 def compile(self, test_directory, module, workdir, incdir,
366 expect_errors, annotate):
367 expected_errors = errors = ()
369 expected_errors = self.split_source_and_output(
370 test_directory, module, workdir)
371 test_directory = workdir
374 old_stderr = sys.stderr
376 sys.stderr = ErrorWriter()
377 self.run_cython(test_directory, module, workdir, incdir, annotate)
378 errors = sys.stderr.geterrors()
380 sys.stderr = old_stderr
382 if errors or expected_errors:
384 for expected, error in zip(expected_errors, errors):
385 self.assertEquals(expected, error)
386 if len(errors) < len(expected_errors):
387 expected_error = expected_errors[len(errors)]
388 self.assertEquals(expected_error, None)
389 elif len(errors) > len(expected_errors):
390 unexpected_error = errors[len(expected_errors)]
391 self.assertEquals(None, unexpected_error)
392 except AssertionError:
393 print("\n=== Expected errors: ===")
394 print('\n'.join(expected_errors))
395 print("\n\n=== Got errors: ===")
396 print('\n'.join(errors))
400 if not self.cython_only:
401 self.run_distutils(test_directory, module, workdir, incdir)
403 class CythonRunTestCase(CythonCompileTestCase):
404 def shortDescription(self):
405 return "compiling (%s) and running %s" % (self.language, self.module)
407 def run(self, result=None):
409 result = self.defaultTestResult()
410 result.startTest(self)
413 self.runCompileTest()
414 if not self.cython_only:
415 self.run_doctests(self.module, result)
417 result.addError(self, sys.exc_info())
418 result.stopTest(self)
424 def run_doctests(self, module_name, result):
425 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
426 doctest.DocTestSuite(module_name).run(result)
430 # fork to make sure we do not keep the tested module loaded
431 result_handle, result_file = tempfile.mkstemp()
432 os.close(result_handle)
440 partial_result = PartialTestResult(result)
441 tests = doctest.DocTestSuite(module_name)
442 tests.run(partial_result)
446 # importing failed, try to fake a test class
448 failureException=sys.exc_info()[1],
449 _shortDescription=self.shortDescription(),
451 partial_result.addError(tests, sys.exc_info())
453 output = open(result_file, 'wb')
454 pickle.dump(partial_result.data(), output)
457 traceback.print_exc()
461 os._exit(result_code)
464 cid, result_code = os.waitpid(child_id, 0)
465 # os.waitpid returns the child's result code in the
466 # upper byte of result_code, and the signal it was
467 # killed by in the lower byte
468 if result_code & 255:
469 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
470 (module_name, result_code & 255))
471 result_code = result_code >> 8
472 if result_code in (0,1):
473 input = open(result_file, 'rb')
475 PartialTestResult.join_results(result, pickle.load(input))
479 raise Exception("Tests in module '%s' exited with status %d" %
480 (module_name, result_code))
482 try: os.unlink(result_file)
486 is_private_field = re.compile('^_[^_]').match
488 class _FakeClass(object):
489 def __init__(self, **kwargs):
490 self._shortDescription = kwargs.get('module_name')
491 self.__dict__.update(kwargs)
492 def shortDescription(self):
493 return self._shortDescription
495 try: # Py2.7+ and Py3.2+
496 from unittest.runner import _TextTestResult
498 from unittest import _TextTestResult
500 class PartialTestResult(_TextTestResult):
501 def __init__(self, base_result):
502 _TextTestResult.__init__(
503 self, self._StringIO(), True,
504 base_result.dots + base_result.showAll*2)
506 def strip_error_results(self, results):
507 for test_case, error in results:
508 for attr_name in filter(is_private_field, dir(test_case)):
509 if attr_name == '_dt_test':
510 test_case._dt_test = _FakeClass(
511 name=test_case._dt_test.name)
512 elif attr_name != '_shortDescription':
513 setattr(test_case, attr_name, None)
516 self.strip_error_results(self.failures)
517 self.strip_error_results(self.errors)
518 return (self.failures, self.errors, self.testsRun,
519 self.stream.getvalue())
521 def join_results(result, data):
522 """Static method for merging the result back into the main
525 failures, errors, tests_run, output = data
527 result.stream.write(output)
528 result.errors.extend(errors)
529 result.failures.extend(failures)
530 result.testsRun += tests_run
532 join_results = staticmethod(join_results)
534 class _StringIO(StringIO):
535 def writeln(self, line):
536 self.write("%s\n" % line)
539 class CythonUnitTestCase(CythonCompileTestCase):
540 def shortDescription(self):
541 return "compiling (%s) tests in %s" % (self.language, self.module)
543 def run(self, result=None):
545 result = self.defaultTestResult()
546 result.startTest(self)
549 self.runCompileTest()
550 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
552 result.addError(self, sys.exc_info())
553 result.stopTest(self)
559 def collect_unittests(path, module_prefix, suite, selectors):
560 def file_matches(filename):
561 return filename.startswith("Test") and filename.endswith(".py")
563 def package_matches(dirname):
564 return dirname == "Tests"
566 loader = unittest.TestLoader()
570 for dirpath, dirnames, filenames in os.walk(path):
571 if dirpath != path and "__init__.py" not in filenames:
572 skipped_dirs.append(dirpath + os.path.sep)
575 for dir in skipped_dirs:
576 if dirpath.startswith(dir):
580 parentname = os.path.split(dirpath)[-1]
581 if package_matches(parentname):
584 filepath = os.path.join(dirpath, f)[:-len(".py")]
585 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
586 if not [ 1 for match in selectors if match(modulename) ]:
588 module = __import__(modulename)
589 for x in modulename.split('.')[1:]:
590 module = getattr(module, x)
591 suite.addTests([loader.loadTestsFromModule(module)])
593 def collect_doctests(path, module_prefix, suite, selectors):
594 def package_matches(dirname):
595 return dirname not in ("Mac", "Distutils", "Plex")
596 def file_matches(filename):
597 return (filename.endswith(".py") and not ('~' in filename
598 or '#' in filename or filename.startswith('.')))
599 import doctest, types
600 for dirpath, dirnames, filenames in os.walk(path):
601 parentname = os.path.split(dirpath)[-1]
602 if package_matches(parentname):
605 if not f.endswith('.py'): continue
606 filepath = os.path.join(dirpath, f)[:-len(".py")]
607 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
608 if not [ 1 for match in selectors if match(modulename) ]:
610 module = __import__(modulename)
611 for x in modulename.split('.')[1:]:
612 module = getattr(module, x)
613 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
615 suite.addTest(doctest.DocTestSuite(module))
616 except ValueError: # no tests
619 # TODO: Support cython_freeze needed here as well.
620 # TODO: Windows support.
622 class EmbedTest(unittest.TestCase):
624 working_dir = "Demos/embed"
627 self.old_dir = os.getcwd()
628 os.chdir(self.working_dir)
630 "make PYTHON='%s' clean > /dev/null" % sys.executable)
635 "make PYTHON='%s' clean > /dev/null" % sys.executable)
638 os.chdir(self.old_dir)
640 def test_embed(self):
641 self.assert_(os.system(
642 "make PYTHON='%s' test > make.output" % sys.executable) == 0)
644 os.remove('make.output')
648 class MissingDependencyExcluder:
649 def __init__(self, deps):
650 # deps: { module name : matcher func }
651 self.exclude_matchers = []
652 for mod, matcher in deps.items():
656 self.exclude_matchers.append(matcher)
657 self.tests_missing_deps = []
658 def __call__(self, testname):
659 for matcher in self.exclude_matchers:
660 if matcher(testname):
661 self.tests_missing_deps.append(testname)
665 class VersionDependencyExcluder:
666 def __init__(self, deps):
667 # deps: { version : matcher func }
668 from sys import version_info
669 self.exclude_matchers = []
670 for ver, (compare, matcher) in deps.items():
671 if compare(version_info, ver):
672 self.exclude_matchers.append(matcher)
673 self.tests_missing_deps = []
674 def __call__(self, testname):
675 for matcher in self.exclude_matchers:
676 if matcher(testname):
677 self.tests_missing_deps.append(testname)
681 class FileListExcluder:
683 def __init__(self, list_file):
685 for line in open(list_file).readlines():
687 if line and line[0] != '#':
688 self.excludes[line.split()[0]] = True
690 def __call__(self, testname):
691 return testname in self.excludes or testname.split('.')[-1] in self.excludes
693 def refactor_for_py3(distdir, cy3_dir):
694 # need to convert Cython sources first
695 import lib2to3.refactor
696 from distutils.util import copydir_run_2to3
697 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
698 if fix.split('fix_')[-1] not in ('next',)
700 if not os.path.exists(cy3_dir):
702 import distutils.log as dlog
703 dlog.set_threshold(dlog.DEBUG)
704 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
708 recursive-exclude Cython *
709 recursive-include Cython *.py *.pyx *.pxd
711 sys.path.insert(0, cy3_dir)
714 if __name__ == '__main__':
715 from optparse import OptionParser
716 parser = OptionParser()
717 parser.add_option("--no-cleanup", dest="cleanup_workdir",
718 action="store_false", default=True,
719 help="do not delete the generated C files (allows passing --no-cython on next run)")
720 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
721 action="store_false", default=True,
722 help="do not delete the generated shared libary files (allows manual module experimentation)")
723 parser.add_option("--no-cython", dest="with_cython",
724 action="store_false", default=True,
725 help="do not run the Cython compiler, only the C compiler")
726 parser.add_option("--no-c", dest="use_c",
727 action="store_false", default=True,
728 help="do not test C compilation")
729 parser.add_option("--no-cpp", dest="use_cpp",
730 action="store_false", default=True,
731 help="do not test C++ compilation")
732 parser.add_option("--no-unit", dest="unittests",
733 action="store_false", default=True,
734 help="do not run the unit tests")
735 parser.add_option("--no-doctest", dest="doctests",
736 action="store_false", default=True,
737 help="do not run the doctests")
738 parser.add_option("--no-file", dest="filetests",
739 action="store_false", default=True,
740 help="do not run the file based tests")
741 parser.add_option("--no-pyregr", dest="pyregr",
742 action="store_false", default=True,
743 help="do not run the regression tests of CPython in tests/pyregr/")
744 parser.add_option("--cython-only", dest="cython_only",
745 action="store_true", default=False,
746 help="only compile pyx to c, do not run C compiler or run the tests")
747 parser.add_option("--no-refnanny", dest="with_refnanny",
748 action="store_false", default=True,
749 help="do not regression test reference counting")
750 parser.add_option("--no-fork", dest="fork",
751 action="store_false", default=True,
752 help="do not fork to run tests")
753 parser.add_option("--sys-pyregr", dest="system_pyregr",
754 action="store_true", default=False,
755 help="run the regression tests of the CPython installation")
756 parser.add_option("-x", "--exclude", dest="exclude",
757 action="append", metavar="PATTERN",
758 help="exclude tests matching the PATTERN")
759 parser.add_option("-C", "--coverage", dest="coverage",
760 action="store_true", default=False,
761 help="collect source coverage data for the Compiler")
762 parser.add_option("--coverage-xml", dest="coverage_xml",
763 action="store_true", default=False,
764 help="collect source coverage data for the Compiler in XML format")
765 parser.add_option("-A", "--annotate", dest="annotate_source",
766 action="store_true", default=True,
767 help="generate annotated HTML versions of the test source files")
768 parser.add_option("--no-annotate", dest="annotate_source",
769 action="store_false",
770 help="do not generate annotated HTML versions of the test source files")
771 parser.add_option("-v", "--verbose", dest="verbosity",
772 action="count", default=0,
773 help="display test progress, pass twice to print test names")
774 parser.add_option("-T", "--ticket", dest="tickets",
776 help="a bug ticket number to run the respective test in 'tests/*'")
777 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
778 help="write test results in XML to directory DIR")
779 parser.add_option("--exit-ok", dest="exit_ok", default=False,
781 help="exit without error code even on test failures")
783 options, cmd_args = parser.parse_args()
785 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
786 ROOTDIR = os.path.join(DISTDIR, 'tests')
787 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
789 if sys.version_info[0] >= 3:
790 options.doctests = False
791 if options.with_cython:
793 # try if Cython is installed in a Py3 version
794 import Cython.Compiler.Main
796 cy_modules = [ name for name in sys.modules
797 if name == 'Cython' or name.startswith('Cython.') ]
798 for name in cy_modules:
799 del sys.modules[name]
800 # hasn't been refactored yet - do it now
801 cy3_dir = os.path.join(WORKDIR, 'Cy3')
802 if sys.version_info >= (3,1):
803 refactor_for_py3(DISTDIR, cy3_dir)
804 elif os.path.isdir(cy3_dir):
805 sys.path.insert(0, cy3_dir)
807 options.with_cython = False
809 WITH_CYTHON = options.with_cython
811 if options.coverage or options.coverage_xml:
813 options.coverage = options.coverage_xml = False
815 from coverage import coverage as _coverage
816 coverage = _coverage(branch=True)
821 from Cython.Compiler.Main import \
822 CompilationOptions, \
823 default_options as pyrex_default_options, \
824 compile as cython_compile
825 from Cython.Compiler import Errors
826 Errors.LEVEL = 0 # show all warnings
827 from Cython.Compiler import Options
828 Options.generate_cleanup_code = 3 # complete cleanup code
829 from Cython.Compiler import DebugFlags
830 DebugFlags.debug_temp_code_comments = 1
833 UNITTEST_MODULE = "Cython"
834 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
836 if os.path.exists(WORKDIR):
837 for path in os.listdir(WORKDIR):
838 if path in ("support", "Cy3"): continue
839 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
840 if not os.path.exists(WORKDIR):
844 from Cython.Compiler.Version import version
845 sys.stderr.write("Running tests against Cython %s\n" % version)
847 sys.stderr.write("Running tests without Cython.\n")
848 sys.stderr.write("Python %s\n" % sys.version)
849 sys.stderr.write("\n")
851 if options.with_refnanny:
852 from pyximport.pyxbuild import pyx_to_dll
853 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
855 pyxbuild_dir=os.path.join(WORKDIR, "support"))
856 sys.path.insert(0, os.path.split(libpath)[0])
857 CFLAGS.append("-DCYTHON_REFNANNY=1")
859 if options.xml_output_dir and options.fork:
860 # doesn't currently work together
861 sys.stderr.write("Disabling forked testing to support XML test output\n")
866 for ticket_number in options.tickets:
868 cmd_args.append('.*T%s$' % ticket_number)
870 for selector in cmd_args:
871 if selector.startswith('bugs'):
875 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
877 selectors = [ lambda x:True ]
879 # Chech which external modules are not present and exclude tests
880 # which depends on them (by prefix)
882 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
883 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
884 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
887 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
890 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
892 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
893 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
897 languages.append('c')
899 languages.append('cpp')
901 test_suite = unittest.TestSuite()
903 if options.unittests:
904 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
907 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
909 if options.filetests and languages:
910 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
911 options.annotate_source, options.cleanup_workdir,
912 options.cleanup_sharedlibs, options.pyregr,
913 options.cython_only, languages, test_bugs,
915 test_suite.addTest(filetests.build_suite())
917 if options.system_pyregr and languages:
918 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
919 options.annotate_source, options.cleanup_workdir,
920 options.cleanup_sharedlibs, True,
921 options.cython_only, languages, test_bugs,
924 filetests.handle_directory(
925 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
928 if options.xml_output_dir:
929 from Cython.Tests.xmlrunner import XMLTestRunner
930 test_runner = XMLTestRunner(output=options.xml_output_dir,
931 verbose=options.verbosity > 0)
933 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
935 result = test_runner.run(test_suite)
937 if options.coverage or options.coverage_xml:
939 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
940 modules = [ module for name, module in sys.modules.items()
941 if module is not None and
942 name.startswith('Cython.Compiler.') and
943 name[len('Cython.Compiler.'):] not in ignored_modules ]
945 coverage.report(modules, show_missing=0)
946 if options.coverage_xml:
947 coverage.xml_report(modules, outfile="coverage-report.xml")
949 if missing_dep_excluder.tests_missing_deps:
950 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
951 for test in missing_dep_excluder.tests_missing_deps:
952 sys.stderr.write(" %s\n" % test)
954 if options.with_refnanny:
956 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
961 sys.exit(not result.wasSuccessful())