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 (2,4) : (operator.le, lambda x: x in ['run.extern_builtins_T258'
53 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
54 'compile.extsetslice',
55 'compile.extdelslice']),
58 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
59 CFLAGS = os.getenv('CFLAGS', '').split()
61 class build_ext(_build_ext):
62 def build_extension(self, ext):
63 if ext.language == 'c++':
65 try: # Py2.7+ & Py3.2+
66 compiler_obj = self.compiler_obj
67 except AttributeError:
68 compiler_obj = self.compiler
69 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
72 _build_ext.build_extension(self, ext)
74 class ErrorWriter(object):
75 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
78 self.write = self.output.append
80 def _collect(self, collect_errors, collect_warnings):
81 s = ''.join(self.output)
83 for line in s.split('\n'):
84 match = self.match_error(line)
86 is_warning, line, column, message = match.groups()
87 if (is_warning and collect_warnings) or \
88 (not is_warning and collect_errors):
89 result.append( (int(line), int(column), message.strip()) )
91 return [ "%d:%d: %s" % values for values in result ]
94 return self._collect(True, False)
96 def getwarnings(self):
97 return self._collect(False, True)
100 return self._collect(True, True)
102 class TestBuilder(object):
103 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
104 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
105 languages, test_bugs, fork):
106 self.rootdir = rootdir
107 self.workdir = workdir
108 self.selectors = selectors
109 self.exclude_selectors = exclude_selectors
110 self.annotate = annotate
111 self.cleanup_workdir = cleanup_workdir
112 self.cleanup_sharedlibs = cleanup_sharedlibs
113 self.with_pyregr = with_pyregr
114 self.cython_only = cython_only
115 self.languages = languages
116 self.test_bugs = test_bugs
119 def build_suite(self):
120 suite = unittest.TestSuite()
121 test_dirs = TEST_DIRS
122 filenames = os.listdir(self.rootdir)
124 for filename in filenames:
125 if not WITH_CYTHON and filename == "errors":
126 # we won't get any errors without running Cython
128 path = os.path.join(self.rootdir, filename)
129 if os.path.isdir(path) and filename in test_dirs:
130 if filename == 'pyregr' and not self.with_pyregr:
133 self.handle_directory(path, filename))
134 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
135 # Non-Windows makefile, can't run Cython under Py3.
136 if [1 for selector in self.selectors if selector("embedded")]:
137 suite.addTest(unittest.makeSuite(EmbedTest))
140 def handle_directory(self, path, context):
141 workdir = os.path.join(self.workdir, context)
142 if not os.path.exists(workdir):
145 expect_errors = (context == 'errors')
146 suite = unittest.TestSuite()
147 filenames = os.listdir(path)
149 for filename in filenames:
150 if not (filename.endswith(".pyx") or filename.endswith(".py")):
152 if filename.startswith('.'): continue # certain emacs backup files
153 if context == 'pyregr' and not filename.startswith('test_'):
155 module = os.path.splitext(filename)[0]
156 fqmodule = "%s.%s" % (context, module)
157 if not [ 1 for match in self.selectors
158 if match(fqmodule) ]:
160 if self.exclude_selectors:
161 if [1 for match in self.exclude_selectors if match(fqmodule)]:
163 if context in TEST_RUN_DIRS:
164 if module.startswith("test_"):
165 test_class = CythonUnitTestCase
167 test_class = CythonRunTestCase
169 test_class = CythonCompileTestCase
170 for test in self.build_tests(test_class, path, workdir,
171 module, expect_errors):
175 def build_tests(self, test_class, path, workdir, module, expect_errors):
177 languages = self.languages[:1]
179 languages = self.languages
180 if 'cpp' in module and 'c' in languages:
181 languages = list(languages)
182 languages.remove('c')
183 tests = [ self.build_test(test_class, path, workdir, module,
184 language, expect_errors)
185 for language in languages ]
188 def build_test(self, test_class, path, workdir, module,
189 language, expect_errors):
190 workdir = os.path.join(workdir, language)
191 if not os.path.exists(workdir):
193 return test_class(path, workdir, module,
195 expect_errors=expect_errors,
196 annotate=self.annotate,
197 cleanup_workdir=self.cleanup_workdir,
198 cleanup_sharedlibs=self.cleanup_sharedlibs,
199 cython_only=self.cython_only,
202 class CythonCompileTestCase(unittest.TestCase):
203 def __init__(self, test_directory, workdir, module, language='c',
204 expect_errors=False, annotate=False, cleanup_workdir=True,
205 cleanup_sharedlibs=True, cython_only=False, fork=True):
206 self.test_directory = test_directory
207 self.workdir = workdir
209 self.language = language
210 self.expect_errors = expect_errors
211 self.annotate = annotate
212 self.cleanup_workdir = cleanup_workdir
213 self.cleanup_sharedlibs = cleanup_sharedlibs
214 self.cython_only = cython_only
216 unittest.TestCase.__init__(self)
218 def shortDescription(self):
219 return "compiling (%s) %s" % (self.language, self.module)
222 if self.workdir not in sys.path:
223 sys.path.insert(0, self.workdir)
227 sys.path.remove(self.workdir)
231 del sys.modules[self.module]
234 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
235 cleanup_lib_files = self.cleanup_sharedlibs
236 if os.path.exists(self.workdir):
237 for rmfile in os.listdir(self.workdir):
238 if not cleanup_c_files:
239 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
241 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
243 if self.annotate and rmfile.endswith(".html"):
246 rmfile = os.path.join(self.workdir, rmfile)
247 if os.path.isdir(rmfile):
248 shutil.rmtree(rmfile, ignore_errors=True)
254 os.makedirs(self.workdir)
257 self.runCompileTest()
259 def runCompileTest(self):
260 self.compile(self.test_directory, self.module, self.workdir,
261 self.test_directory, self.expect_errors, self.annotate)
263 def find_module_source_file(self, source_file):
264 if not os.path.exists(source_file):
265 source_file = source_file[:-1]
268 def build_target_filename(self, module_name):
269 target = '%s.%s' % (module_name, self.language)
272 def copy_related_files(self, test_directory, target_directory, module_name):
273 is_related = re.compile('%s_.*[.].*' % module_name).match
274 for filename in os.listdir(test_directory):
275 if is_related(filename):
276 shutil.copy(os.path.join(test_directory, filename),
279 def find_source_files(self, workdir, module_name):
280 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
281 return [self.build_target_filename(module_name)] + [
282 filename for filename in os.listdir(workdir)
283 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
285 def split_source_and_output(self, test_directory, module, workdir):
286 source_file = os.path.join(test_directory, module) + '.pyx'
287 source_and_output = codecs.open(
288 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
289 out = codecs.open(os.path.join(workdir, module + '.pyx'),
291 for line in source_and_output:
293 if line.startswith("_ERRORS"):
299 geterrors = out.geterrors
300 except AttributeError:
305 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
306 include_dirs = INCLUDE_DIRS[:]
308 include_dirs.append(incdir)
309 source = self.find_module_source_file(
310 os.path.join(test_directory, module + '.pyx'))
311 target = os.path.join(targetdir, self.build_target_filename(module))
312 options = CompilationOptions(
313 pyrex_default_options,
314 include_path = include_dirs,
315 output_file = target,
317 use_listing_file = False,
318 cplus = self.language == 'cpp',
319 generate_pxi = False,
320 evaluate_tree_assertions = True,
322 cython_compile(source, options=options,
323 full_module_name=module)
325 def run_distutils(self, test_directory, module, workdir, incdir):
329 build_extension = build_ext(distutils_distro)
330 build_extension.include_dirs = INCLUDE_DIRS[:]
332 build_extension.include_dirs.append(incdir)
333 build_extension.finalize_options()
334 ext_include_dirs = []
335 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
337 ext_include_dirs += get_additional_include_dirs()
338 self.copy_related_files(test_directory, workdir, module)
339 extension = Extension(
341 sources = self.find_source_files(workdir, module),
342 include_dirs = ext_include_dirs,
343 extra_compile_args = CFLAGS,
345 if self.language == 'cpp':
346 extension.language = 'c++'
347 build_extension.extensions = [extension]
348 build_extension.build_temp = workdir
349 build_extension.build_lib = workdir
350 build_extension.run()
354 def compile(self, test_directory, module, workdir, incdir,
355 expect_errors, annotate):
356 expected_errors = errors = ()
358 expected_errors = self.split_source_and_output(
359 test_directory, module, workdir)
360 test_directory = workdir
363 old_stderr = sys.stderr
365 sys.stderr = ErrorWriter()
366 self.run_cython(test_directory, module, workdir, incdir, annotate)
367 errors = sys.stderr.geterrors()
369 sys.stderr = old_stderr
371 if errors or expected_errors:
373 for expected, error in zip(expected_errors, errors):
374 self.assertEquals(expected, error)
375 if len(errors) < len(expected_errors):
376 expected_error = expected_errors[len(errors)]
377 self.assertEquals(expected_error, None)
378 elif len(errors) > len(expected_errors):
379 unexpected_error = errors[len(expected_errors)]
380 self.assertEquals(None, unexpected_error)
381 except AssertionError:
382 print("\n=== Expected errors: ===")
383 print('\n'.join(expected_errors))
384 print("\n\n=== Got errors: ===")
385 print('\n'.join(errors))
389 if not self.cython_only:
390 self.run_distutils(test_directory, module, workdir, incdir)
392 class CythonRunTestCase(CythonCompileTestCase):
393 def shortDescription(self):
394 return "compiling (%s) and running %s" % (self.language, self.module)
396 def run(self, result=None):
398 result = self.defaultTestResult()
399 result.startTest(self)
402 self.runCompileTest()
403 if not self.cython_only:
404 self.run_doctests(self.module, result)
406 result.addError(self, sys.exc_info())
407 result.stopTest(self)
413 def run_doctests(self, module_name, result):
414 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
415 doctest.DocTestSuite(module_name).run(result)
419 # fork to make sure we do not keep the tested module loaded
420 result_handle, result_file = tempfile.mkstemp()
421 os.close(result_handle)
429 partial_result = PartialTestResult(result)
430 tests = doctest.DocTestSuite(module_name)
431 tests.run(partial_result)
435 # importing failed, try to fake a test class
437 failureException=None,
438 shortDescription = self.shortDescription,
439 **{module_name: None})
440 partial_result.addError(tests, sys.exc_info())
442 output = open(result_file, 'wb')
443 pickle.dump(partial_result.data(), output)
446 traceback.print_exc()
450 os._exit(result_code)
453 cid, result_code = os.waitpid(child_id, 0)
454 if result_code in (0,1):
455 input = open(result_file, 'rb')
457 PartialTestResult.join_results(result, pickle.load(input))
461 raise Exception("Tests in module '%s' exited with status %d" %
462 (module_name, result_code >> 8))
464 try: os.unlink(result_file)
468 is_private_field = re.compile('^_[^_]').match
470 class _FakeClass(object):
471 def __init__(self, **kwargs):
472 self._shortDescription = kwargs.get('module_name')
473 self.__dict__.update(kwargs)
474 def shortDescription(self):
475 return self._shortDescription
477 try: # Py2.7+ and Py3.2+
478 from unittest.runner import _TextTestResult
480 from unittest import _TextTestResult
482 class PartialTestResult(_TextTestResult):
483 def __init__(self, base_result):
484 _TextTestResult.__init__(
485 self, self._StringIO(), True,
486 base_result.dots + base_result.showAll*2)
488 def strip_error_results(self, results):
489 for test_case, error in results:
490 for attr_name in filter(is_private_field, dir(test_case)):
491 if attr_name == '_dt_test':
492 test_case._dt_test = _FakeClass(
493 name=test_case._dt_test.name)
495 setattr(test_case, attr_name, None)
498 self.strip_error_results(self.failures)
499 self.strip_error_results(self.errors)
500 return (self.failures, self.errors, self.testsRun,
501 self.stream.getvalue())
503 def join_results(result, data):
504 """Static method for merging the result back into the main
507 errors, failures, tests_run, output = data
509 result.stream.write(output)
510 result.errors.extend(errors)
511 result.failures.extend(failures)
512 result.testsRun += tests_run
514 join_results = staticmethod(join_results)
516 class _StringIO(StringIO):
517 def writeln(self, line):
518 self.write("%s\n" % line)
521 class CythonUnitTestCase(CythonCompileTestCase):
522 def shortDescription(self):
523 return "compiling (%s) tests in %s" % (self.language, self.module)
525 def run(self, result=None):
527 result = self.defaultTestResult()
528 result.startTest(self)
531 self.runCompileTest()
532 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
534 result.addError(self, sys.exc_info())
535 result.stopTest(self)
541 def collect_unittests(path, module_prefix, suite, selectors):
542 def file_matches(filename):
543 return filename.startswith("Test") and filename.endswith(".py")
545 def package_matches(dirname):
546 return dirname == "Tests"
548 loader = unittest.TestLoader()
552 for dirpath, dirnames, filenames in os.walk(path):
553 if dirpath != path and "__init__.py" not in filenames:
554 skipped_dirs.append(dirpath + os.path.sep)
557 for dir in skipped_dirs:
558 if dirpath.startswith(dir):
562 parentname = os.path.split(dirpath)[-1]
563 if package_matches(parentname):
566 filepath = os.path.join(dirpath, f)[:-len(".py")]
567 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
568 if not [ 1 for match in selectors if match(modulename) ]:
570 module = __import__(modulename)
571 for x in modulename.split('.')[1:]:
572 module = getattr(module, x)
573 suite.addTests([loader.loadTestsFromModule(module)])
575 def collect_doctests(path, module_prefix, suite, selectors):
576 def package_matches(dirname):
577 return dirname not in ("Mac", "Distutils", "Plex")
578 def file_matches(filename):
579 return (filename.endswith(".py") and not ('~' in filename
580 or '#' in filename or filename.startswith('.')))
581 import doctest, types
582 for dirpath, dirnames, filenames in os.walk(path):
583 parentname = os.path.split(dirpath)[-1]
584 if package_matches(parentname):
587 if not f.endswith('.py'): continue
588 filepath = os.path.join(dirpath, f)[:-len(".py")]
589 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
590 if not [ 1 for match in selectors if match(modulename) ]:
592 module = __import__(modulename)
593 for x in modulename.split('.')[1:]:
594 module = getattr(module, x)
595 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
597 suite.addTest(doctest.DocTestSuite(module))
598 except ValueError: # no tests
601 # TODO: Support cython_freeze needed here as well.
602 # TODO: Windows support.
604 class EmbedTest(unittest.TestCase):
606 working_dir = "Demos/embed"
609 self.old_dir = os.getcwd()
610 os.chdir(self.working_dir)
611 os.system("make clean > /dev/null")
615 os.system("make clean > /dev/null")
618 os.chdir(self.old_dir)
620 def test_embed(self):
621 self.assert_(os.system("make test > make.output") == 0)
623 class MissingDependencyExcluder:
624 def __init__(self, deps):
625 # deps: { module name : matcher func }
626 self.exclude_matchers = []
627 for mod, matcher in deps.items():
631 self.exclude_matchers.append(matcher)
632 self.tests_missing_deps = []
633 def __call__(self, testname):
634 for matcher in self.exclude_matchers:
635 if matcher(testname):
636 self.tests_missing_deps.append(testname)
640 class VersionDependencyExcluder:
641 def __init__(self, deps):
642 # deps: { version : matcher func }
643 from sys import version_info
644 self.exclude_matchers = []
645 for ver, (compare, matcher) in deps.items():
646 if compare(version_info, ver):
647 self.exclude_matchers.append(matcher)
648 self.tests_missing_deps = []
649 def __call__(self, testname):
650 for matcher in self.exclude_matchers:
651 if matcher(testname):
652 self.tests_missing_deps.append(testname)
656 class FileListExcluder:
658 def __init__(self, list_file):
660 for line in open(list_file).readlines():
662 if line and line[0] != '#':
663 self.excludes[line.split()[0]] = True
665 def __call__(self, testname):
666 return testname in self.excludes or testname.split('.')[-1] in self.excludes
668 if __name__ == '__main__':
669 from optparse import OptionParser
670 parser = OptionParser()
671 parser.add_option("--no-cleanup", dest="cleanup_workdir",
672 action="store_false", default=True,
673 help="do not delete the generated C files (allows passing --no-cython on next run)")
674 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
675 action="store_false", default=True,
676 help="do not delete the generated shared libary files (allows manual module experimentation)")
677 parser.add_option("--no-cython", dest="with_cython",
678 action="store_false", default=True,
679 help="do not run the Cython compiler, only the C compiler")
680 parser.add_option("--no-c", dest="use_c",
681 action="store_false", default=True,
682 help="do not test C compilation")
683 parser.add_option("--no-cpp", dest="use_cpp",
684 action="store_false", default=True,
685 help="do not test C++ compilation")
686 parser.add_option("--no-unit", dest="unittests",
687 action="store_false", default=True,
688 help="do not run the unit tests")
689 parser.add_option("--no-doctest", dest="doctests",
690 action="store_false", default=True,
691 help="do not run the doctests")
692 parser.add_option("--no-file", dest="filetests",
693 action="store_false", default=True,
694 help="do not run the file based tests")
695 parser.add_option("--no-pyregr", dest="pyregr",
696 action="store_false", default=True,
697 help="do not run the regression tests of CPython in tests/pyregr/")
698 parser.add_option("--cython-only", dest="cython_only",
699 action="store_true", default=False,
700 help="only compile pyx to c, do not run C compiler or run the tests")
701 parser.add_option("--no-refnanny", dest="with_refnanny",
702 action="store_false", default=True,
703 help="do not regression test reference counting")
704 parser.add_option("--no-fork", dest="fork",
705 action="store_false", default=True,
706 help="do not fork to run tests")
707 parser.add_option("--sys-pyregr", dest="system_pyregr",
708 action="store_true", default=False,
709 help="run the regression tests of the CPython installation")
710 parser.add_option("-x", "--exclude", dest="exclude",
711 action="append", metavar="PATTERN",
712 help="exclude tests matching the PATTERN")
713 parser.add_option("-C", "--coverage", dest="coverage",
714 action="store_true", default=False,
715 help="collect source coverage data for the Compiler")
716 parser.add_option("-A", "--annotate", dest="annotate_source",
717 action="store_true", default=True,
718 help="generate annotated HTML versions of the test source files")
719 parser.add_option("--no-annotate", dest="annotate_source",
720 action="store_false",
721 help="do not generate annotated HTML versions of the test source files")
722 parser.add_option("-v", "--verbose", dest="verbosity",
723 action="count", default=0,
724 help="display test progress, pass twice to print test names")
725 parser.add_option("-T", "--ticket", dest="tickets",
727 help="a bug ticket number to run the respective test in 'tests/bugs'")
729 options, cmd_args = parser.parse_args()
731 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
732 ROOTDIR = os.path.join(DISTDIR, 'tests')
733 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
735 if sys.version_info >= (3,1):
736 options.doctests = False
737 options.unittests = False
738 options.pyregr = False
739 if options.with_cython:
740 # need to convert Cython sources first
741 import lib2to3.refactor
742 from distutils.util import copydir_run_2to3
743 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
744 if fix.split('fix_')[-1] not in ('next',)
746 cy3_dir = os.path.join(WORKDIR, 'Cy3')
747 if not os.path.exists(cy3_dir):
749 import distutils.log as dlog
750 dlog.set_threshold(dlog.DEBUG)
751 copydir_run_2to3(DISTDIR, cy3_dir, fixer_names=fixers,
755 recursive-exclude Cython *
756 recursive-include Cython *.py *.pyx *.pxd
758 sys.path.insert(0, cy3_dir)
759 elif sys.version_info[0] >= 3:
760 # make sure we do not import (or run) Cython itself (unless
761 # 2to3 was already run)
762 cy3_dir = os.path.join(WORKDIR, 'Cy3')
763 if os.path.isdir(cy3_dir):
764 sys.path.insert(0, cy3_dir)
766 options.with_cython = False
767 options.doctests = False
768 options.unittests = False
769 options.pyregr = False
776 WITH_CYTHON = options.with_cython
779 from Cython.Compiler.Main import \
780 CompilationOptions, \
781 default_options as pyrex_default_options, \
782 compile as cython_compile
783 from Cython.Compiler import Errors
784 Errors.LEVEL = 0 # show all warnings
785 from Cython.Compiler import Options
786 Options.generate_cleanup_code = 3 # complete cleanup code
787 from Cython.Compiler import DebugFlags
788 DebugFlags.debug_temp_code_comments = 1
791 UNITTEST_MODULE = "Cython"
792 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
794 if os.path.exists(WORKDIR):
795 for path in os.listdir(WORKDIR):
796 if path in ("support", "Cy3"): continue
797 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
798 if not os.path.exists(WORKDIR):
802 from Cython.Compiler.Version import version
803 sys.stderr.write("Running tests against Cython %s\n" % version)
805 sys.stderr.write("Running tests without Cython.\n")
806 sys.stderr.write("Python %s\n" % sys.version)
807 sys.stderr.write("\n")
809 if options.with_refnanny:
810 from pyximport.pyxbuild import pyx_to_dll
811 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
813 pyxbuild_dir=os.path.join(WORKDIR, "support"))
814 sys.path.insert(0, os.path.split(libpath)[0])
815 CFLAGS.append("-DCYTHON_REFNANNY=1")
819 for ticket_number in options.tickets:
821 cmd_args.append('.*T%s$' % ticket_number)
823 for selector in cmd_args:
824 if selector.startswith('bugs'):
828 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
830 selectors = [ lambda x:True ]
832 # Chech which external modules are not present and exclude tests
833 # which depends on them (by prefix)
835 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
836 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
837 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
840 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
843 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
845 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
846 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
850 languages.append('c')
852 languages.append('cpp')
854 test_suite = unittest.TestSuite()
856 if options.unittests:
857 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
860 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
862 if options.filetests and languages:
863 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
864 options.annotate_source, options.cleanup_workdir,
865 options.cleanup_sharedlibs, options.pyregr,
866 options.cython_only, languages, test_bugs,
868 test_suite.addTest(filetests.build_suite())
870 if options.system_pyregr and languages:
871 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
872 options.annotate_source, options.cleanup_workdir,
873 options.cleanup_sharedlibs, True,
874 options.cython_only, languages, test_bugs,
877 filetests.handle_directory(
878 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
881 result = unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
885 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
886 modules = [ module for name, module in sys.modules.items()
887 if module is not None and
888 name.startswith('Cython.Compiler.') and
889 name[len('Cython.Compiler.'):] not in ignored_modules ]
890 coverage.report(modules, show_missing=0)
892 if missing_dep_excluder.tests_missing_deps:
893 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
894 for test in missing_dep_excluder.tests_missing_deps:
895 sys.stderr.write(" %s\n" % test)
897 if options.with_refnanny:
899 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
901 sys.exit(not result.wasSuccessful())