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', 'build']
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 # The next line should start (3,); but this is a dictionary, so
63 # we can only have one (3,) key. Since 2.7 is supposed to be the
64 # last 2.x release, things would have to change drastically for this
66 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
67 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
68 'compile.extsetslice',
69 'compile.extdelslice',
70 'run.special_methods_T561_py2']),
73 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
74 CFLAGS = os.getenv('CFLAGS', '').split()
76 class build_ext(_build_ext):
77 def build_extension(self, ext):
78 if ext.language == 'c++':
80 try: # Py2.7+ & Py3.2+
81 compiler_obj = self.compiler_obj
82 except AttributeError:
83 compiler_obj = self.compiler
84 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
87 _build_ext.build_extension(self, ext)
89 class ErrorWriter(object):
90 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
93 self.write = self.output.append
95 def _collect(self, collect_errors, collect_warnings):
96 s = ''.join(self.output)
98 for line in s.split('\n'):
99 match = self.match_error(line)
101 is_warning, line, column, message = match.groups()
102 if (is_warning and collect_warnings) or \
103 (not is_warning and collect_errors):
104 result.append( (int(line), int(column), message.strip()) )
106 return [ "%d:%d: %s" % values for values in result ]
109 return self._collect(True, False)
111 def getwarnings(self):
112 return self._collect(False, True)
115 return self._collect(True, True)
117 class TestBuilder(object):
118 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
119 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
120 languages, test_bugs, fork):
121 self.rootdir = rootdir
122 self.workdir = workdir
123 self.selectors = selectors
124 self.exclude_selectors = exclude_selectors
125 self.annotate = annotate
126 self.cleanup_workdir = cleanup_workdir
127 self.cleanup_sharedlibs = cleanup_sharedlibs
128 self.with_pyregr = with_pyregr
129 self.cython_only = cython_only
130 self.languages = languages
131 self.test_bugs = test_bugs
134 def build_suite(self):
135 suite = unittest.TestSuite()
136 test_dirs = TEST_DIRS
137 filenames = os.listdir(self.rootdir)
139 for filename in filenames:
140 if not WITH_CYTHON and filename == "errors":
141 # we won't get any errors without running Cython
143 path = os.path.join(self.rootdir, filename)
144 if os.path.isdir(path) and filename in test_dirs:
145 if filename == 'pyregr' and not self.with_pyregr:
148 self.handle_directory(path, filename))
149 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
150 # Non-Windows makefile, can't run Cython under Py3.
151 if [1 for selector in self.selectors if selector("embedded")]:
152 suite.addTest(unittest.makeSuite(EmbedTest))
155 def handle_directory(self, path, context):
156 workdir = os.path.join(self.workdir, context)
157 if not os.path.exists(workdir):
160 expect_errors = (context == 'errors')
161 suite = unittest.TestSuite()
162 filenames = os.listdir(path)
164 for filename in filenames:
165 if context == "build" and filename.endswith(".srctree"):
166 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
168 if not (filename.endswith(".pyx") or filename.endswith(".py")):
170 if filename.startswith('.'): continue # certain emacs backup files
171 if context == 'pyregr' and not filename.startswith('test_'):
173 module = os.path.splitext(filename)[0]
174 fqmodule = "%s.%s" % (context, module)
175 if not [ 1 for match in self.selectors
176 if match(fqmodule) ]:
178 if self.exclude_selectors:
179 if [1 for match in self.exclude_selectors if match(fqmodule)]:
181 if context in TEST_RUN_DIRS:
182 if module.startswith("test_"):
183 test_class = CythonUnitTestCase
185 test_class = CythonRunTestCase
187 test_class = CythonCompileTestCase
188 for test in self.build_tests(test_class, path, workdir,
189 module, expect_errors):
193 def build_tests(self, test_class, path, workdir, module, expect_errors):
195 if 'cpp' in module and 'cpp' in self.languages:
198 languages = self.languages[:1]
200 languages = self.languages
201 if 'cpp' in module and 'c' in languages:
202 languages = list(languages)
203 languages.remove('c')
204 tests = [ self.build_test(test_class, path, workdir, module,
205 language, expect_errors)
206 for language in languages ]
209 def build_test(self, test_class, path, workdir, module,
210 language, expect_errors):
211 workdir = os.path.join(workdir, language)
212 if not os.path.exists(workdir):
214 return test_class(path, workdir, module,
216 expect_errors=expect_errors,
217 annotate=self.annotate,
218 cleanup_workdir=self.cleanup_workdir,
219 cleanup_sharedlibs=self.cleanup_sharedlibs,
220 cython_only=self.cython_only,
223 class CythonCompileTestCase(unittest.TestCase):
224 def __init__(self, test_directory, workdir, module, language='c',
225 expect_errors=False, annotate=False, cleanup_workdir=True,
226 cleanup_sharedlibs=True, cython_only=False, fork=True):
227 self.test_directory = test_directory
228 self.workdir = workdir
230 self.language = language
231 self.expect_errors = expect_errors
232 self.annotate = annotate
233 self.cleanup_workdir = cleanup_workdir
234 self.cleanup_sharedlibs = cleanup_sharedlibs
235 self.cython_only = cython_only
237 unittest.TestCase.__init__(self)
239 def shortDescription(self):
240 return "compiling (%s) %s" % (self.language, self.module)
243 if self.workdir not in sys.path:
244 sys.path.insert(0, self.workdir)
248 sys.path.remove(self.workdir)
252 del sys.modules[self.module]
255 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
256 cleanup_lib_files = self.cleanup_sharedlibs
257 if os.path.exists(self.workdir):
258 for rmfile in os.listdir(self.workdir):
259 if not cleanup_c_files:
260 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
262 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
264 if self.annotate and rmfile.endswith(".html"):
267 rmfile = os.path.join(self.workdir, rmfile)
268 if os.path.isdir(rmfile):
269 shutil.rmtree(rmfile, ignore_errors=True)
275 os.makedirs(self.workdir)
278 self.runCompileTest()
280 def runCompileTest(self):
281 self.compile(self.test_directory, self.module, self.workdir,
282 self.test_directory, self.expect_errors, self.annotate)
284 def find_module_source_file(self, source_file):
285 if not os.path.exists(source_file):
286 source_file = source_file[:-1]
289 def build_target_filename(self, module_name):
290 target = '%s.%s' % (module_name, self.language)
293 def copy_related_files(self, test_directory, target_directory, module_name):
294 is_related = re.compile('%s_.*[.].*' % module_name).match
295 for filename in os.listdir(test_directory):
296 if is_related(filename):
297 shutil.copy(os.path.join(test_directory, filename),
300 def find_source_files(self, workdir, module_name):
301 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
302 return [self.build_target_filename(module_name)] + [
303 filename for filename in os.listdir(workdir)
304 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
306 def split_source_and_output(self, test_directory, module, workdir):
307 source_file = os.path.join(test_directory, module) + '.pyx'
308 source_and_output = codecs.open(
309 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
310 out = codecs.open(os.path.join(workdir, module + '.pyx'),
312 for line in source_and_output:
314 if line.startswith("_ERRORS"):
320 geterrors = out.geterrors
321 except AttributeError:
326 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
327 include_dirs = INCLUDE_DIRS[:]
329 include_dirs.append(incdir)
330 source = self.find_module_source_file(
331 os.path.join(test_directory, module + '.pyx'))
332 target = os.path.join(targetdir, self.build_target_filename(module))
333 options = CompilationOptions(
334 pyrex_default_options,
335 include_path = include_dirs,
336 output_file = target,
338 use_listing_file = False,
339 cplus = self.language == 'cpp',
340 generate_pxi = False,
341 evaluate_tree_assertions = True,
343 cython_compile(source, options=options,
344 full_module_name=module)
346 def run_distutils(self, test_directory, module, workdir, incdir):
350 build_extension = build_ext(distutils_distro)
351 build_extension.include_dirs = INCLUDE_DIRS[:]
353 build_extension.include_dirs.append(incdir)
354 build_extension.finalize_options()
355 ext_include_dirs = []
356 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
358 ext_include_dirs += get_additional_include_dirs()
359 self.copy_related_files(test_directory, workdir, module)
360 extension = Extension(
362 sources = self.find_source_files(workdir, module),
363 include_dirs = ext_include_dirs,
364 extra_compile_args = CFLAGS,
366 if self.language == 'cpp':
367 extension.language = 'c++'
368 build_extension.extensions = [extension]
369 build_extension.build_temp = workdir
370 build_extension.build_lib = workdir
371 build_extension.run()
375 def compile(self, test_directory, module, workdir, incdir,
376 expect_errors, annotate):
377 expected_errors = errors = ()
379 expected_errors = self.split_source_and_output(
380 test_directory, module, workdir)
381 test_directory = workdir
384 old_stderr = sys.stderr
386 sys.stderr = ErrorWriter()
387 self.run_cython(test_directory, module, workdir, incdir, annotate)
388 errors = sys.stderr.geterrors()
390 sys.stderr = old_stderr
392 if errors or expected_errors:
394 for expected, error in zip(expected_errors, errors):
395 self.assertEquals(expected, error)
396 if len(errors) < len(expected_errors):
397 expected_error = expected_errors[len(errors)]
398 self.assertEquals(expected_error, None)
399 elif len(errors) > len(expected_errors):
400 unexpected_error = errors[len(expected_errors)]
401 self.assertEquals(None, unexpected_error)
402 except AssertionError:
403 print("\n=== Expected errors: ===")
404 print('\n'.join(expected_errors))
405 print("\n\n=== Got errors: ===")
406 print('\n'.join(errors))
410 if not self.cython_only:
411 self.run_distutils(test_directory, module, workdir, incdir)
413 class CythonRunTestCase(CythonCompileTestCase):
414 def shortDescription(self):
415 return "compiling (%s) and running %s" % (self.language, self.module)
417 def run(self, result=None):
419 result = self.defaultTestResult()
420 result.startTest(self)
423 self.runCompileTest()
424 if not self.cython_only:
425 self.run_doctests(self.module, result)
427 result.addError(self, sys.exc_info())
428 result.stopTest(self)
434 def run_doctests(self, module_name, result):
435 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
436 doctest.DocTestSuite(module_name).run(result)
440 # fork to make sure we do not keep the tested module loaded
441 result_handle, result_file = tempfile.mkstemp()
442 os.close(result_handle)
450 partial_result = PartialTestResult(result)
451 tests = doctest.DocTestSuite(module_name)
452 tests.run(partial_result)
456 # importing failed, try to fake a test class
458 failureException=sys.exc_info()[1],
459 _shortDescription=self.shortDescription(),
461 partial_result.addError(tests, sys.exc_info())
463 output = open(result_file, 'wb')
464 pickle.dump(partial_result.data(), output)
467 traceback.print_exc()
471 os._exit(result_code)
474 cid, result_code = os.waitpid(child_id, 0)
475 # os.waitpid returns the child's result code in the
476 # upper byte of result_code, and the signal it was
477 # killed by in the lower byte
478 if result_code & 255:
479 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
480 (module_name, result_code & 255))
481 result_code = result_code >> 8
482 if result_code in (0,1):
483 input = open(result_file, 'rb')
485 PartialTestResult.join_results(result, pickle.load(input))
489 raise Exception("Tests in module '%s' exited with status %d" %
490 (module_name, result_code))
492 try: os.unlink(result_file)
496 is_private_field = re.compile('^_[^_]').match
498 class _FakeClass(object):
499 def __init__(self, **kwargs):
500 self._shortDescription = kwargs.get('module_name')
501 self.__dict__.update(kwargs)
502 def shortDescription(self):
503 return self._shortDescription
505 try: # Py2.7+ and Py3.2+
506 from unittest.runner import _TextTestResult
508 from unittest import _TextTestResult
510 class PartialTestResult(_TextTestResult):
511 def __init__(self, base_result):
512 _TextTestResult.__init__(
513 self, self._StringIO(), True,
514 base_result.dots + base_result.showAll*2)
516 def strip_error_results(self, results):
517 for test_case, error in results:
518 for attr_name in filter(is_private_field, dir(test_case)):
519 if attr_name == '_dt_test':
520 test_case._dt_test = _FakeClass(
521 name=test_case._dt_test.name)
522 elif attr_name != '_shortDescription':
523 setattr(test_case, attr_name, None)
526 self.strip_error_results(self.failures)
527 self.strip_error_results(self.errors)
528 return (self.failures, self.errors, self.testsRun,
529 self.stream.getvalue())
531 def join_results(result, data):
532 """Static method for merging the result back into the main
535 failures, errors, tests_run, output = data
537 result.stream.write(output)
538 result.errors.extend(errors)
539 result.failures.extend(failures)
540 result.testsRun += tests_run
542 join_results = staticmethod(join_results)
544 class _StringIO(StringIO):
545 def writeln(self, line):
546 self.write("%s\n" % line)
549 class CythonUnitTestCase(CythonCompileTestCase):
550 def shortDescription(self):
551 return "compiling (%s) tests in %s" % (self.language, self.module)
553 def run(self, result=None):
555 result = self.defaultTestResult()
556 result.startTest(self)
559 self.runCompileTest()
560 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
562 result.addError(self, sys.exc_info())
563 result.stopTest(self)
569 def collect_unittests(path, module_prefix, suite, selectors):
570 def file_matches(filename):
571 return filename.startswith("Test") and filename.endswith(".py")
573 def package_matches(dirname):
574 return dirname == "Tests"
576 loader = unittest.TestLoader()
580 for dirpath, dirnames, filenames in os.walk(path):
581 if dirpath != path and "__init__.py" not in filenames:
582 skipped_dirs.append(dirpath + os.path.sep)
585 for dir in skipped_dirs:
586 if dirpath.startswith(dir):
590 parentname = os.path.split(dirpath)[-1]
591 if package_matches(parentname):
594 filepath = os.path.join(dirpath, f)[:-len(".py")]
595 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
596 if not [ 1 for match in selectors if match(modulename) ]:
598 module = __import__(modulename)
599 for x in modulename.split('.')[1:]:
600 module = getattr(module, x)
601 suite.addTests([loader.loadTestsFromModule(module)])
603 def collect_doctests(path, module_prefix, suite, selectors):
604 def package_matches(dirname):
605 return dirname not in ("Mac", "Distutils", "Plex")
606 def file_matches(filename):
607 return (filename.endswith(".py") and not ('~' in filename
608 or '#' in filename or filename.startswith('.')))
609 import doctest, types
610 for dirpath, dirnames, filenames in os.walk(path):
611 parentname = os.path.split(dirpath)[-1]
612 if package_matches(parentname):
615 if not f.endswith('.py'): continue
616 filepath = os.path.join(dirpath, f)[:-len(".py")]
617 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
618 if not [ 1 for match in selectors if match(modulename) ]:
620 module = __import__(modulename)
621 for x in modulename.split('.')[1:]:
622 module = getattr(module, x)
623 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
625 suite.addTest(doctest.DocTestSuite(module))
626 except ValueError: # no tests
630 class EndToEndTest(unittest.TestCase):
632 This is a test of build/*.srctree files, where srctree defines a full
633 directory structure and its header gives a list of commands to run.
635 def __init__(self, treefile, workdir, cleanup_workdir=True):
636 self.treefile = treefile
637 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
638 self.cleanup_workdir = cleanup_workdir
639 unittest.TestCase.__init__(self)
641 def shortDescription(self):
642 return "End-to-end %s" % self.treefile
645 from Cython.TestUtils import unpack_source_tree
646 _, self.commands = unpack_source_tree(os.path.join('tests', 'build', self.treefile), self.workdir)
647 self.old_dir = os.getcwd()
648 if not os.path.exists(self.workdir):
649 os.makedirs(self.workdir)
650 os.chdir(self.workdir)
651 if self.workdir not in sys.path:
652 sys.path.insert(0, self.workdir)
656 sys.path.remove(self.workdir)
659 if self.cleanup_workdir:
660 shutil.rmtree(self.workdir)
661 os.chdir(self.old_dir)
664 commands = (self.commands
665 .replace("CYTHON", "PYTHON %s" % os.path.join(self.old_dir, 'cython.py'))
666 .replace("PYTHON", sys.executable))
667 self.assertEqual(0, os.system(commands))
670 # TODO: Support cython_freeze needed here as well.
671 # TODO: Windows support.
673 class EmbedTest(unittest.TestCase):
675 working_dir = "Demos/embed"
678 self.old_dir = os.getcwd()
679 os.chdir(self.working_dir)
681 "make PYTHON='%s' clean > /dev/null" % sys.executable)
686 "make PYTHON='%s' clean > /dev/null" % sys.executable)
689 os.chdir(self.old_dir)
691 def test_embed(self):
692 from distutils import sysconfig
693 libname = sysconfig.get_config_var('LIBRARY')
694 libdir = sysconfig.get_config_var('LIBDIR')
695 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
696 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
697 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
698 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
699 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
700 # report the error for the original directory
701 libdir = sysconfig.get_config_var('LIBDIR')
702 self.assert_(os.system(
703 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
705 os.remove('make.output')
709 class MissingDependencyExcluder:
710 def __init__(self, deps):
711 # deps: { module name : matcher func }
712 self.exclude_matchers = []
713 for mod, matcher in deps.items():
717 self.exclude_matchers.append(matcher)
718 self.tests_missing_deps = []
719 def __call__(self, testname):
720 for matcher in self.exclude_matchers:
721 if matcher(testname):
722 self.tests_missing_deps.append(testname)
726 class VersionDependencyExcluder:
727 def __init__(self, deps):
728 # deps: { version : matcher func }
729 from sys import version_info
730 self.exclude_matchers = []
731 for ver, (compare, matcher) in deps.items():
732 if compare(version_info, ver):
733 self.exclude_matchers.append(matcher)
734 self.tests_missing_deps = []
735 def __call__(self, testname):
736 for matcher in self.exclude_matchers:
737 if matcher(testname):
738 self.tests_missing_deps.append(testname)
742 class FileListExcluder:
744 def __init__(self, list_file):
746 for line in open(list_file).readlines():
748 if line and line[0] != '#':
749 self.excludes[line.split()[0]] = True
751 def __call__(self, testname):
752 return testname in self.excludes or testname.split('.')[-1] in self.excludes
754 def refactor_for_py3(distdir, cy3_dir):
755 # need to convert Cython sources first
756 import lib2to3.refactor
757 from distutils.util import copydir_run_2to3
758 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
759 if fix.split('fix_')[-1] not in ('next',)
761 if not os.path.exists(cy3_dir):
763 import distutils.log as dlog
764 dlog.set_threshold(dlog.INFO)
765 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
769 recursive-exclude Cython *
770 recursive-include Cython *.py *.pyx *.pxd
772 sys.path.insert(0, cy3_dir)
775 if __name__ == '__main__':
776 from optparse import OptionParser
777 parser = OptionParser()
778 parser.add_option("--no-cleanup", dest="cleanup_workdir",
779 action="store_false", default=True,
780 help="do not delete the generated C files (allows passing --no-cython on next run)")
781 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
782 action="store_false", default=True,
783 help="do not delete the generated shared libary files (allows manual module experimentation)")
784 parser.add_option("--no-cython", dest="with_cython",
785 action="store_false", default=True,
786 help="do not run the Cython compiler, only the C compiler")
787 parser.add_option("--no-c", dest="use_c",
788 action="store_false", default=True,
789 help="do not test C compilation")
790 parser.add_option("--no-cpp", dest="use_cpp",
791 action="store_false", default=True,
792 help="do not test C++ compilation")
793 parser.add_option("--no-unit", dest="unittests",
794 action="store_false", default=True,
795 help="do not run the unit tests")
796 parser.add_option("--no-doctest", dest="doctests",
797 action="store_false", default=True,
798 help="do not run the doctests")
799 parser.add_option("--no-file", dest="filetests",
800 action="store_false", default=True,
801 help="do not run the file based tests")
802 parser.add_option("--no-pyregr", dest="pyregr",
803 action="store_false", default=True,
804 help="do not run the regression tests of CPython in tests/pyregr/")
805 parser.add_option("--cython-only", dest="cython_only",
806 action="store_true", default=False,
807 help="only compile pyx to c, do not run C compiler or run the tests")
808 parser.add_option("--no-refnanny", dest="with_refnanny",
809 action="store_false", default=True,
810 help="do not regression test reference counting")
811 parser.add_option("--no-fork", dest="fork",
812 action="store_false", default=True,
813 help="do not fork to run tests")
814 parser.add_option("--sys-pyregr", dest="system_pyregr",
815 action="store_true", default=False,
816 help="run the regression tests of the CPython installation")
817 parser.add_option("-x", "--exclude", dest="exclude",
818 action="append", metavar="PATTERN",
819 help="exclude tests matching the PATTERN")
820 parser.add_option("-C", "--coverage", dest="coverage",
821 action="store_true", default=False,
822 help="collect source coverage data for the Compiler")
823 parser.add_option("--coverage-xml", dest="coverage_xml",
824 action="store_true", default=False,
825 help="collect source coverage data for the Compiler in XML format")
826 parser.add_option("-A", "--annotate", dest="annotate_source",
827 action="store_true", default=True,
828 help="generate annotated HTML versions of the test source files")
829 parser.add_option("--no-annotate", dest="annotate_source",
830 action="store_false",
831 help="do not generate annotated HTML versions of the test source files")
832 parser.add_option("-v", "--verbose", dest="verbosity",
833 action="count", default=0,
834 help="display test progress, pass twice to print test names")
835 parser.add_option("-T", "--ticket", dest="tickets",
837 help="a bug ticket number to run the respective test in 'tests/*'")
838 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
839 help="write test results in XML to directory DIR")
840 parser.add_option("--exit-ok", dest="exit_ok", default=False,
842 help="exit without error code even on test failures")
844 options, cmd_args = parser.parse_args()
846 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
847 ROOTDIR = os.path.join(DISTDIR, 'tests')
848 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
850 if sys.version_info[0] >= 3:
851 options.doctests = False
852 if options.with_cython:
854 # try if Cython is installed in a Py3 version
855 import Cython.Compiler.Main
857 cy_modules = [ name for name in sys.modules
858 if name == 'Cython' or name.startswith('Cython.') ]
859 for name in cy_modules:
860 del sys.modules[name]
861 # hasn't been refactored yet - do it now
862 cy3_dir = os.path.join(WORKDIR, 'Cy3')
863 if sys.version_info >= (3,1):
864 refactor_for_py3(DISTDIR, cy3_dir)
865 elif os.path.isdir(cy3_dir):
866 sys.path.insert(0, cy3_dir)
868 options.with_cython = False
870 WITH_CYTHON = options.with_cython
872 if options.coverage or options.coverage_xml:
874 options.coverage = options.coverage_xml = False
876 from coverage import coverage as _coverage
877 coverage = _coverage(branch=True)
882 from Cython.Compiler.Main import \
883 CompilationOptions, \
884 default_options as pyrex_default_options, \
885 compile as cython_compile
886 from Cython.Compiler import Errors
887 Errors.LEVEL = 0 # show all warnings
888 from Cython.Compiler import Options
889 Options.generate_cleanup_code = 3 # complete cleanup code
890 from Cython.Compiler import DebugFlags
891 DebugFlags.debug_temp_code_comments = 1
894 UNITTEST_MODULE = "Cython"
895 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
897 if os.path.exists(WORKDIR):
898 for path in os.listdir(WORKDIR):
899 if path in ("support", "Cy3"): continue
900 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
901 if not os.path.exists(WORKDIR):
905 from Cython.Compiler.Version import version
906 sys.stderr.write("Running tests against Cython %s\n" % version)
908 sys.stderr.write("Running tests without Cython.\n")
909 sys.stderr.write("Python %s\n" % sys.version)
910 sys.stderr.write("\n")
912 if options.with_refnanny:
913 from pyximport.pyxbuild import pyx_to_dll
914 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
916 pyxbuild_dir=os.path.join(WORKDIR, "support"))
917 sys.path.insert(0, os.path.split(libpath)[0])
918 CFLAGS.append("-DCYTHON_REFNANNY=1")
920 if options.xml_output_dir and options.fork:
921 # doesn't currently work together
922 sys.stderr.write("Disabling forked testing to support XML test output\n")
927 for ticket_number in options.tickets:
929 cmd_args.append('.*T%s$' % ticket_number)
931 for selector in cmd_args:
932 if selector.startswith('bugs'):
936 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
938 selectors = [ lambda x:True ]
940 # Chech which external modules are not present and exclude tests
941 # which depends on them (by prefix)
943 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
944 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
945 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
948 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
951 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
953 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
954 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
958 languages.append('c')
960 languages.append('cpp')
962 test_suite = unittest.TestSuite()
964 if options.unittests:
965 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
968 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
970 if options.filetests and languages:
971 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
972 options.annotate_source, options.cleanup_workdir,
973 options.cleanup_sharedlibs, options.pyregr,
974 options.cython_only, languages, test_bugs,
976 test_suite.addTest(filetests.build_suite())
978 if options.system_pyregr and languages:
979 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
980 options.annotate_source, options.cleanup_workdir,
981 options.cleanup_sharedlibs, True,
982 options.cython_only, languages, test_bugs,
985 filetests.handle_directory(
986 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
989 if options.xml_output_dir:
990 from Cython.Tests.xmlrunner import XMLTestRunner
991 test_runner = XMLTestRunner(output=options.xml_output_dir,
992 verbose=options.verbosity > 0)
994 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
996 result = test_runner.run(test_suite)
998 if options.coverage or options.coverage_xml:
1000 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1001 modules = [ module for name, module in sys.modules.items()
1002 if module is not None and
1003 name.startswith('Cython.Compiler.') and
1004 name[len('Cython.Compiler.'):] not in ignored_modules ]
1005 if options.coverage:
1006 coverage.report(modules, show_missing=0)
1007 if options.coverage_xml:
1008 coverage.xml_report(modules, outfile="coverage-report.xml")
1010 if missing_dep_excluder.tests_missing_deps:
1011 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1012 for test in missing_dep_excluder.tests_missing_deps:
1013 sys.stderr.write(" %s\n" % test)
1015 if options.with_refnanny:
1017 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1022 sys.exit(not result.wasSuccessful())