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 languages = self.languages[:1]
183 languages = self.languages
184 if 'cpp' in module and 'c' in languages:
185 languages = list(languages)
186 languages.remove('c')
187 tests = [ self.build_test(test_class, path, workdir, module,
188 language, expect_errors)
189 for language in languages ]
192 def build_test(self, test_class, path, workdir, module,
193 language, expect_errors):
194 workdir = os.path.join(workdir, language)
195 if not os.path.exists(workdir):
197 return test_class(path, workdir, module,
199 expect_errors=expect_errors,
200 annotate=self.annotate,
201 cleanup_workdir=self.cleanup_workdir,
202 cleanup_sharedlibs=self.cleanup_sharedlibs,
203 cython_only=self.cython_only,
206 class CythonCompileTestCase(unittest.TestCase):
207 def __init__(self, test_directory, workdir, module, language='c',
208 expect_errors=False, annotate=False, cleanup_workdir=True,
209 cleanup_sharedlibs=True, cython_only=False, fork=True):
210 self.test_directory = test_directory
211 self.workdir = workdir
213 self.language = language
214 self.expect_errors = expect_errors
215 self.annotate = annotate
216 self.cleanup_workdir = cleanup_workdir
217 self.cleanup_sharedlibs = cleanup_sharedlibs
218 self.cython_only = cython_only
220 unittest.TestCase.__init__(self)
222 def shortDescription(self):
223 return "compiling (%s) %s" % (self.language, self.module)
226 if self.workdir not in sys.path:
227 sys.path.insert(0, self.workdir)
231 sys.path.remove(self.workdir)
235 del sys.modules[self.module]
238 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
239 cleanup_lib_files = self.cleanup_sharedlibs
240 if os.path.exists(self.workdir):
241 for rmfile in os.listdir(self.workdir):
242 if not cleanup_c_files:
243 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
245 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
247 if self.annotate and rmfile.endswith(".html"):
250 rmfile = os.path.join(self.workdir, rmfile)
251 if os.path.isdir(rmfile):
252 shutil.rmtree(rmfile, ignore_errors=True)
258 os.makedirs(self.workdir)
261 self.runCompileTest()
263 def runCompileTest(self):
264 self.compile(self.test_directory, self.module, self.workdir,
265 self.test_directory, self.expect_errors, self.annotate)
267 def find_module_source_file(self, source_file):
268 if not os.path.exists(source_file):
269 source_file = source_file[:-1]
272 def build_target_filename(self, module_name):
273 target = '%s.%s' % (module_name, self.language)
276 def copy_related_files(self, test_directory, target_directory, module_name):
277 is_related = re.compile('%s_.*[.].*' % module_name).match
278 for filename in os.listdir(test_directory):
279 if is_related(filename):
280 shutil.copy(os.path.join(test_directory, filename),
283 def find_source_files(self, workdir, module_name):
284 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
285 return [self.build_target_filename(module_name)] + [
286 filename for filename in os.listdir(workdir)
287 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
289 def split_source_and_output(self, test_directory, module, workdir):
290 source_file = os.path.join(test_directory, module) + '.pyx'
291 source_and_output = codecs.open(
292 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
293 out = codecs.open(os.path.join(workdir, module + '.pyx'),
295 for line in source_and_output:
297 if line.startswith("_ERRORS"):
303 geterrors = out.geterrors
304 except AttributeError:
309 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
310 include_dirs = INCLUDE_DIRS[:]
312 include_dirs.append(incdir)
313 source = self.find_module_source_file(
314 os.path.join(test_directory, module + '.pyx'))
315 target = os.path.join(targetdir, self.build_target_filename(module))
316 options = CompilationOptions(
317 pyrex_default_options,
318 include_path = include_dirs,
319 output_file = target,
321 use_listing_file = False,
322 cplus = self.language == 'cpp',
323 generate_pxi = False,
324 evaluate_tree_assertions = True,
326 cython_compile(source, options=options,
327 full_module_name=module)
329 def run_distutils(self, test_directory, module, workdir, incdir):
333 build_extension = build_ext(distutils_distro)
334 build_extension.include_dirs = INCLUDE_DIRS[:]
336 build_extension.include_dirs.append(incdir)
337 build_extension.finalize_options()
338 ext_include_dirs = []
339 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
341 ext_include_dirs += get_additional_include_dirs()
342 self.copy_related_files(test_directory, workdir, module)
343 extension = Extension(
345 sources = self.find_source_files(workdir, module),
346 include_dirs = ext_include_dirs,
347 extra_compile_args = CFLAGS,
349 if self.language == 'cpp':
350 extension.language = 'c++'
351 build_extension.extensions = [extension]
352 build_extension.build_temp = workdir
353 build_extension.build_lib = workdir
354 build_extension.run()
358 def compile(self, test_directory, module, workdir, incdir,
359 expect_errors, annotate):
360 expected_errors = errors = ()
362 expected_errors = self.split_source_and_output(
363 test_directory, module, workdir)
364 test_directory = workdir
367 old_stderr = sys.stderr
369 sys.stderr = ErrorWriter()
370 self.run_cython(test_directory, module, workdir, incdir, annotate)
371 errors = sys.stderr.geterrors()
373 sys.stderr = old_stderr
375 if errors or expected_errors:
377 for expected, error in zip(expected_errors, errors):
378 self.assertEquals(expected, error)
379 if len(errors) < len(expected_errors):
380 expected_error = expected_errors[len(errors)]
381 self.assertEquals(expected_error, None)
382 elif len(errors) > len(expected_errors):
383 unexpected_error = errors[len(expected_errors)]
384 self.assertEquals(None, unexpected_error)
385 except AssertionError:
386 print("\n=== Expected errors: ===")
387 print('\n'.join(expected_errors))
388 print("\n\n=== Got errors: ===")
389 print('\n'.join(errors))
393 if not self.cython_only:
394 self.run_distutils(test_directory, module, workdir, incdir)
396 class CythonRunTestCase(CythonCompileTestCase):
397 def shortDescription(self):
398 return "compiling (%s) and running %s" % (self.language, self.module)
400 def run(self, result=None):
402 result = self.defaultTestResult()
403 result.startTest(self)
406 self.runCompileTest()
407 if not self.cython_only:
408 self.run_doctests(self.module, result)
410 result.addError(self, sys.exc_info())
411 result.stopTest(self)
417 def run_doctests(self, module_name, result):
418 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
419 doctest.DocTestSuite(module_name).run(result)
423 # fork to make sure we do not keep the tested module loaded
424 result_handle, result_file = tempfile.mkstemp()
425 os.close(result_handle)
433 partial_result = PartialTestResult(result)
434 tests = doctest.DocTestSuite(module_name)
435 tests.run(partial_result)
439 # importing failed, try to fake a test class
441 failureException=sys.exc_info()[1],
442 _shortDescription=self.shortDescription(),
444 partial_result.addError(tests, sys.exc_info())
446 output = open(result_file, 'wb')
447 pickle.dump(partial_result.data(), output)
450 traceback.print_exc()
454 os._exit(result_code)
457 cid, result_code = os.waitpid(child_id, 0)
458 # os.waitpid returns the child's result code in the
459 # upper byte of result_code, and the signal it was
460 # killed by in the lower byte
461 if result_code & 255:
462 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
463 (module_name, result_code & 255))
464 result_code = result_code >> 8
465 if result_code in (0,1):
466 input = open(result_file, 'rb')
468 PartialTestResult.join_results(result, pickle.load(input))
472 raise Exception("Tests in module '%s' exited with status %d" %
473 (module_name, result_code))
475 try: os.unlink(result_file)
479 is_private_field = re.compile('^_[^_]').match
481 class _FakeClass(object):
482 def __init__(self, **kwargs):
483 self._shortDescription = kwargs.get('module_name')
484 self.__dict__.update(kwargs)
485 def shortDescription(self):
486 return self._shortDescription
488 try: # Py2.7+ and Py3.2+
489 from unittest.runner import _TextTestResult
491 from unittest import _TextTestResult
493 class PartialTestResult(_TextTestResult):
494 def __init__(self, base_result):
495 _TextTestResult.__init__(
496 self, self._StringIO(), True,
497 base_result.dots + base_result.showAll*2)
499 def strip_error_results(self, results):
500 for test_case, error in results:
501 for attr_name in filter(is_private_field, dir(test_case)):
502 if attr_name == '_dt_test':
503 test_case._dt_test = _FakeClass(
504 name=test_case._dt_test.name)
505 elif attr_name != '_shortDescription':
506 setattr(test_case, attr_name, None)
509 self.strip_error_results(self.failures)
510 self.strip_error_results(self.errors)
511 return (self.failures, self.errors, self.testsRun,
512 self.stream.getvalue())
514 def join_results(result, data):
515 """Static method for merging the result back into the main
518 failures, errors, tests_run, output = data
520 result.stream.write(output)
521 result.errors.extend(errors)
522 result.failures.extend(failures)
523 result.testsRun += tests_run
525 join_results = staticmethod(join_results)
527 class _StringIO(StringIO):
528 def writeln(self, line):
529 self.write("%s\n" % line)
532 class CythonUnitTestCase(CythonCompileTestCase):
533 def shortDescription(self):
534 return "compiling (%s) tests in %s" % (self.language, self.module)
536 def run(self, result=None):
538 result = self.defaultTestResult()
539 result.startTest(self)
542 self.runCompileTest()
543 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
545 result.addError(self, sys.exc_info())
546 result.stopTest(self)
552 def collect_unittests(path, module_prefix, suite, selectors):
553 def file_matches(filename):
554 return filename.startswith("Test") and filename.endswith(".py")
556 def package_matches(dirname):
557 return dirname == "Tests"
559 loader = unittest.TestLoader()
563 for dirpath, dirnames, filenames in os.walk(path):
564 if dirpath != path and "__init__.py" not in filenames:
565 skipped_dirs.append(dirpath + os.path.sep)
568 for dir in skipped_dirs:
569 if dirpath.startswith(dir):
573 parentname = os.path.split(dirpath)[-1]
574 if package_matches(parentname):
577 filepath = os.path.join(dirpath, f)[:-len(".py")]
578 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
579 if not [ 1 for match in selectors if match(modulename) ]:
581 module = __import__(modulename)
582 for x in modulename.split('.')[1:]:
583 module = getattr(module, x)
584 suite.addTests([loader.loadTestsFromModule(module)])
586 def collect_doctests(path, module_prefix, suite, selectors):
587 def package_matches(dirname):
588 return dirname not in ("Mac", "Distutils", "Plex")
589 def file_matches(filename):
590 return (filename.endswith(".py") and not ('~' in filename
591 or '#' in filename or filename.startswith('.')))
592 import doctest, types
593 for dirpath, dirnames, filenames in os.walk(path):
594 parentname = os.path.split(dirpath)[-1]
595 if package_matches(parentname):
598 if not f.endswith('.py'): continue
599 filepath = os.path.join(dirpath, f)[:-len(".py")]
600 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
601 if not [ 1 for match in selectors if match(modulename) ]:
603 module = __import__(modulename)
604 for x in modulename.split('.')[1:]:
605 module = getattr(module, x)
606 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
608 suite.addTest(doctest.DocTestSuite(module))
609 except ValueError: # no tests
612 # TODO: Support cython_freeze needed here as well.
613 # TODO: Windows support.
615 class EmbedTest(unittest.TestCase):
617 working_dir = "Demos/embed"
620 self.old_dir = os.getcwd()
621 os.chdir(self.working_dir)
623 "make PYTHON='%s' clean > /dev/null" % sys.executable)
628 "make PYTHON='%s' clean > /dev/null" % sys.executable)
631 os.chdir(self.old_dir)
633 def test_embed(self):
634 self.assert_(os.system(
635 "make PYTHON='%s' test > make.output" % sys.executable) == 0)
637 os.remove('make.output')
641 class MissingDependencyExcluder:
642 def __init__(self, deps):
643 # deps: { module name : matcher func }
644 self.exclude_matchers = []
645 for mod, matcher in deps.items():
649 self.exclude_matchers.append(matcher)
650 self.tests_missing_deps = []
651 def __call__(self, testname):
652 for matcher in self.exclude_matchers:
653 if matcher(testname):
654 self.tests_missing_deps.append(testname)
658 class VersionDependencyExcluder:
659 def __init__(self, deps):
660 # deps: { version : matcher func }
661 from sys import version_info
662 self.exclude_matchers = []
663 for ver, (compare, matcher) in deps.items():
664 if compare(version_info, ver):
665 self.exclude_matchers.append(matcher)
666 self.tests_missing_deps = []
667 def __call__(self, testname):
668 for matcher in self.exclude_matchers:
669 if matcher(testname):
670 self.tests_missing_deps.append(testname)
674 class FileListExcluder:
676 def __init__(self, list_file):
678 for line in open(list_file).readlines():
680 if line and line[0] != '#':
681 self.excludes[line.split()[0]] = True
683 def __call__(self, testname):
684 return testname in self.excludes or testname.split('.')[-1] in self.excludes
686 if __name__ == '__main__':
687 from optparse import OptionParser
688 parser = OptionParser()
689 parser.add_option("--no-cleanup", dest="cleanup_workdir",
690 action="store_false", default=True,
691 help="do not delete the generated C files (allows passing --no-cython on next run)")
692 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
693 action="store_false", default=True,
694 help="do not delete the generated shared libary files (allows manual module experimentation)")
695 parser.add_option("--no-cython", dest="with_cython",
696 action="store_false", default=True,
697 help="do not run the Cython compiler, only the C compiler")
698 parser.add_option("--no-c", dest="use_c",
699 action="store_false", default=True,
700 help="do not test C compilation")
701 parser.add_option("--no-cpp", dest="use_cpp",
702 action="store_false", default=True,
703 help="do not test C++ compilation")
704 parser.add_option("--no-unit", dest="unittests",
705 action="store_false", default=True,
706 help="do not run the unit tests")
707 parser.add_option("--no-doctest", dest="doctests",
708 action="store_false", default=True,
709 help="do not run the doctests")
710 parser.add_option("--no-file", dest="filetests",
711 action="store_false", default=True,
712 help="do not run the file based tests")
713 parser.add_option("--no-pyregr", dest="pyregr",
714 action="store_false", default=True,
715 help="do not run the regression tests of CPython in tests/pyregr/")
716 parser.add_option("--cython-only", dest="cython_only",
717 action="store_true", default=False,
718 help="only compile pyx to c, do not run C compiler or run the tests")
719 parser.add_option("--no-refnanny", dest="with_refnanny",
720 action="store_false", default=True,
721 help="do not regression test reference counting")
722 parser.add_option("--no-fork", dest="fork",
723 action="store_false", default=True,
724 help="do not fork to run tests")
725 parser.add_option("--sys-pyregr", dest="system_pyregr",
726 action="store_true", default=False,
727 help="run the regression tests of the CPython installation")
728 parser.add_option("-x", "--exclude", dest="exclude",
729 action="append", metavar="PATTERN",
730 help="exclude tests matching the PATTERN")
731 parser.add_option("-C", "--coverage", dest="coverage",
732 action="store_true", default=False,
733 help="collect source coverage data for the Compiler")
734 parser.add_option("-A", "--annotate", dest="annotate_source",
735 action="store_true", default=True,
736 help="generate annotated HTML versions of the test source files")
737 parser.add_option("--no-annotate", dest="annotate_source",
738 action="store_false",
739 help="do not generate annotated HTML versions of the test source files")
740 parser.add_option("-v", "--verbose", dest="verbosity",
741 action="count", default=0,
742 help="display test progress, pass twice to print test names")
743 parser.add_option("-T", "--ticket", dest="tickets",
745 help="a bug ticket number to run the respective test in 'tests/*'")
746 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
747 help="write test results in XML to directory DIR")
748 parser.add_option("--exit-ok", dest="exit_ok", default=False,
750 help="exit without error code even on test failures")
752 options, cmd_args = parser.parse_args()
754 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
755 ROOTDIR = os.path.join(DISTDIR, 'tests')
756 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
758 if sys.version_info >= (3,1):
759 options.doctests = False
760 options.unittests = False
761 options.pyregr = False
762 if options.with_cython:
763 # need to convert Cython sources first
764 import lib2to3.refactor
765 from distutils.util import copydir_run_2to3
766 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
767 if fix.split('fix_')[-1] not in ('next',)
769 cy3_dir = os.path.join(WORKDIR, 'Cy3')
770 if not os.path.exists(cy3_dir):
772 import distutils.log as dlog
773 dlog.set_threshold(dlog.DEBUG)
774 copydir_run_2to3(DISTDIR, cy3_dir, fixer_names=fixers,
778 recursive-exclude Cython *
779 recursive-include Cython *.py *.pyx *.pxd
781 sys.path.insert(0, cy3_dir)
782 elif sys.version_info[0] >= 3:
783 # make sure we do not import (or run) Cython itself (unless
784 # 2to3 was already run)
785 cy3_dir = os.path.join(WORKDIR, 'Cy3')
786 if os.path.isdir(cy3_dir):
787 sys.path.insert(0, cy3_dir)
789 options.with_cython = False
790 options.doctests = False
791 options.unittests = False
792 options.pyregr = False
799 WITH_CYTHON = options.with_cython
802 from Cython.Compiler.Main import \
803 CompilationOptions, \
804 default_options as pyrex_default_options, \
805 compile as cython_compile
806 from Cython.Compiler import Errors
807 Errors.LEVEL = 0 # show all warnings
808 from Cython.Compiler import Options
809 Options.generate_cleanup_code = 3 # complete cleanup code
810 from Cython.Compiler import DebugFlags
811 DebugFlags.debug_temp_code_comments = 1
814 UNITTEST_MODULE = "Cython"
815 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
817 if os.path.exists(WORKDIR):
818 for path in os.listdir(WORKDIR):
819 if path in ("support", "Cy3"): continue
820 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
821 if not os.path.exists(WORKDIR):
825 from Cython.Compiler.Version import version
826 sys.stderr.write("Running tests against Cython %s\n" % version)
828 sys.stderr.write("Running tests without Cython.\n")
829 sys.stderr.write("Python %s\n" % sys.version)
830 sys.stderr.write("\n")
832 if options.with_refnanny:
833 from pyximport.pyxbuild import pyx_to_dll
834 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
836 pyxbuild_dir=os.path.join(WORKDIR, "support"))
837 sys.path.insert(0, os.path.split(libpath)[0])
838 CFLAGS.append("-DCYTHON_REFNANNY=1")
842 for ticket_number in options.tickets:
844 cmd_args.append('.*T%s$' % ticket_number)
846 for selector in cmd_args:
847 if selector.startswith('bugs'):
851 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
853 selectors = [ lambda x:True ]
855 # Chech which external modules are not present and exclude tests
856 # which depends on them (by prefix)
858 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
859 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
860 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
863 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
866 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
868 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
869 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
873 languages.append('c')
875 languages.append('cpp')
877 test_suite = unittest.TestSuite()
879 if options.unittests:
880 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
883 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
885 if options.filetests and languages:
886 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
887 options.annotate_source, options.cleanup_workdir,
888 options.cleanup_sharedlibs, options.pyregr,
889 options.cython_only, languages, test_bugs,
891 test_suite.addTest(filetests.build_suite())
893 if options.system_pyregr and languages:
894 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
895 options.annotate_source, options.cleanup_workdir,
896 options.cleanup_sharedlibs, True,
897 options.cython_only, languages, test_bugs,
900 filetests.handle_directory(
901 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
904 if options.xml_output_dir:
905 from Cython.Tests.xmlrunner import XMLTestRunner
906 test_runner = XMLTestRunner(output=options.xml_output_dir,
907 verbose=options.verbosity > 0)
909 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
911 result = test_runner.run(test_suite)
915 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
916 modules = [ module for name, module in sys.modules.items()
917 if module is not None and
918 name.startswith('Cython.Compiler.') and
919 name[len('Cython.Compiler.'):] not in ignored_modules ]
920 coverage.report(modules, show_missing=0)
922 if missing_dep_excluder.tests_missing_deps:
923 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
924 for test in missing_dep_excluder.tests_missing_deps:
925 sys.stderr.write(" %s\n" % test)
927 if options.with_refnanny:
929 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
934 sys.exit(not result.wasSuccessful())