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 if not [ 1 for match in self.selectors if match(filename) ]:
168 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
170 if not (filename.endswith(".pyx") or filename.endswith(".py")):
172 if filename.startswith('.'): continue # certain emacs backup files
173 if context == 'pyregr' and not filename.startswith('test_'):
175 module = os.path.splitext(filename)[0]
176 fqmodule = "%s.%s" % (context, module)
177 if not [ 1 for match in self.selectors
178 if match(fqmodule) ]:
180 if self.exclude_selectors:
181 if [1 for match in self.exclude_selectors if match(fqmodule)]:
183 if context in TEST_RUN_DIRS:
184 if module.startswith("test_"):
185 test_class = CythonUnitTestCase
187 test_class = CythonRunTestCase
189 test_class = CythonCompileTestCase
190 for test in self.build_tests(test_class, path, workdir,
191 module, expect_errors):
195 def build_tests(self, test_class, path, workdir, module, expect_errors):
197 if 'cpp' in module and 'cpp' in self.languages:
200 languages = self.languages[:1]
202 languages = self.languages
203 if 'cpp' in module and 'c' in languages:
204 languages = list(languages)
205 languages.remove('c')
206 tests = [ self.build_test(test_class, path, workdir, module,
207 language, expect_errors)
208 for language in languages ]
211 def build_test(self, test_class, path, workdir, module,
212 language, expect_errors):
213 workdir = os.path.join(workdir, language)
214 if not os.path.exists(workdir):
216 return test_class(path, workdir, module,
218 expect_errors=expect_errors,
219 annotate=self.annotate,
220 cleanup_workdir=self.cleanup_workdir,
221 cleanup_sharedlibs=self.cleanup_sharedlibs,
222 cython_only=self.cython_only,
225 class CythonCompileTestCase(unittest.TestCase):
226 def __init__(self, test_directory, workdir, module, language='c',
227 expect_errors=False, annotate=False, cleanup_workdir=True,
228 cleanup_sharedlibs=True, cython_only=False, fork=True):
229 self.test_directory = test_directory
230 self.workdir = workdir
232 self.language = language
233 self.expect_errors = expect_errors
234 self.annotate = annotate
235 self.cleanup_workdir = cleanup_workdir
236 self.cleanup_sharedlibs = cleanup_sharedlibs
237 self.cython_only = cython_only
239 unittest.TestCase.__init__(self)
241 def shortDescription(self):
242 return "compiling (%s) %s" % (self.language, self.module)
245 if self.workdir not in sys.path:
246 sys.path.insert(0, self.workdir)
250 sys.path.remove(self.workdir)
254 del sys.modules[self.module]
257 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
258 cleanup_lib_files = self.cleanup_sharedlibs
259 if os.path.exists(self.workdir):
260 for rmfile in os.listdir(self.workdir):
261 if not cleanup_c_files:
262 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
264 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
266 if self.annotate and rmfile.endswith(".html"):
269 rmfile = os.path.join(self.workdir, rmfile)
270 if os.path.isdir(rmfile):
271 shutil.rmtree(rmfile, ignore_errors=True)
277 os.makedirs(self.workdir)
280 self.runCompileTest()
282 def runCompileTest(self):
283 self.compile(self.test_directory, self.module, self.workdir,
284 self.test_directory, self.expect_errors, self.annotate)
286 def find_module_source_file(self, source_file):
287 if not os.path.exists(source_file):
288 source_file = source_file[:-1]
291 def build_target_filename(self, module_name):
292 target = '%s.%s' % (module_name, self.language)
295 def copy_related_files(self, test_directory, target_directory, module_name):
296 is_related = re.compile('%s_.*[.].*' % module_name).match
297 for filename in os.listdir(test_directory):
298 if is_related(filename):
299 shutil.copy(os.path.join(test_directory, filename),
302 def find_source_files(self, workdir, module_name):
303 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
304 return [self.build_target_filename(module_name)] + [
305 filename for filename in os.listdir(workdir)
306 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
308 def split_source_and_output(self, test_directory, module, workdir):
309 source_file = os.path.join(test_directory, module) + '.pyx'
310 source_and_output = codecs.open(
311 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
312 out = codecs.open(os.path.join(workdir, module + '.pyx'),
314 for line in source_and_output:
316 if line.startswith("_ERRORS"):
322 geterrors = out.geterrors
323 except AttributeError:
328 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
329 include_dirs = INCLUDE_DIRS[:]
331 include_dirs.append(incdir)
332 source = self.find_module_source_file(
333 os.path.join(test_directory, module + '.pyx'))
334 target = os.path.join(targetdir, self.build_target_filename(module))
335 options = CompilationOptions(
336 pyrex_default_options,
337 include_path = include_dirs,
338 output_file = target,
340 use_listing_file = False,
341 cplus = self.language == 'cpp',
342 generate_pxi = False,
343 evaluate_tree_assertions = True,
345 cython_compile(source, options=options,
346 full_module_name=module)
348 def run_distutils(self, test_directory, module, workdir, incdir):
352 build_extension = build_ext(distutils_distro)
353 build_extension.include_dirs = INCLUDE_DIRS[:]
355 build_extension.include_dirs.append(incdir)
356 build_extension.finalize_options()
357 ext_include_dirs = []
358 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
360 ext_include_dirs += get_additional_include_dirs()
361 self.copy_related_files(test_directory, workdir, module)
362 extension = Extension(
364 sources = self.find_source_files(workdir, module),
365 include_dirs = ext_include_dirs,
366 extra_compile_args = CFLAGS,
368 if self.language == 'cpp':
369 extension.language = 'c++'
370 build_extension.extensions = [extension]
371 build_extension.build_temp = workdir
372 build_extension.build_lib = workdir
373 build_extension.run()
377 def compile(self, test_directory, module, workdir, incdir,
378 expect_errors, annotate):
379 expected_errors = errors = ()
381 expected_errors = self.split_source_and_output(
382 test_directory, module, workdir)
383 test_directory = workdir
386 old_stderr = sys.stderr
388 sys.stderr = ErrorWriter()
389 self.run_cython(test_directory, module, workdir, incdir, annotate)
390 errors = sys.stderr.geterrors()
392 sys.stderr = old_stderr
394 if errors or expected_errors:
396 for expected, error in zip(expected_errors, errors):
397 self.assertEquals(expected, error)
398 if len(errors) < len(expected_errors):
399 expected_error = expected_errors[len(errors)]
400 self.assertEquals(expected_error, None)
401 elif len(errors) > len(expected_errors):
402 unexpected_error = errors[len(expected_errors)]
403 self.assertEquals(None, unexpected_error)
404 except AssertionError:
405 print("\n=== Expected errors: ===")
406 print('\n'.join(expected_errors))
407 print("\n\n=== Got errors: ===")
408 print('\n'.join(errors))
412 if not self.cython_only:
413 self.run_distutils(test_directory, module, workdir, incdir)
415 class CythonRunTestCase(CythonCompileTestCase):
416 def shortDescription(self):
417 return "compiling (%s) and running %s" % (self.language, self.module)
419 def run(self, result=None):
421 result = self.defaultTestResult()
422 result.startTest(self)
425 self.runCompileTest()
426 if not self.cython_only:
427 self.run_doctests(self.module, result)
429 result.addError(self, sys.exc_info())
430 result.stopTest(self)
436 def run_doctests(self, module_name, result):
437 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
438 doctest.DocTestSuite(module_name).run(result)
442 # fork to make sure we do not keep the tested module loaded
443 result_handle, result_file = tempfile.mkstemp()
444 os.close(result_handle)
452 partial_result = PartialTestResult(result)
453 tests = doctest.DocTestSuite(module_name)
454 tests.run(partial_result)
458 # importing failed, try to fake a test class
460 failureException=sys.exc_info()[1],
461 _shortDescription=self.shortDescription(),
463 partial_result.addError(tests, sys.exc_info())
465 output = open(result_file, 'wb')
466 pickle.dump(partial_result.data(), output)
469 traceback.print_exc()
473 os._exit(result_code)
476 cid, result_code = os.waitpid(child_id, 0)
477 # os.waitpid returns the child's result code in the
478 # upper byte of result_code, and the signal it was
479 # killed by in the lower byte
480 if result_code & 255:
481 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
482 (module_name, result_code & 255))
483 result_code = result_code >> 8
484 if result_code in (0,1):
485 input = open(result_file, 'rb')
487 PartialTestResult.join_results(result, pickle.load(input))
491 raise Exception("Tests in module '%s' exited with status %d" %
492 (module_name, result_code))
494 try: os.unlink(result_file)
498 is_private_field = re.compile('^_[^_]').match
500 class _FakeClass(object):
501 def __init__(self, **kwargs):
502 self._shortDescription = kwargs.get('module_name')
503 self.__dict__.update(kwargs)
504 def shortDescription(self):
505 return self._shortDescription
507 try: # Py2.7+ and Py3.2+
508 from unittest.runner import _TextTestResult
510 from unittest import _TextTestResult
512 class PartialTestResult(_TextTestResult):
513 def __init__(self, base_result):
514 _TextTestResult.__init__(
515 self, self._StringIO(), True,
516 base_result.dots + base_result.showAll*2)
518 def strip_error_results(self, results):
519 for test_case, error in results:
520 for attr_name in filter(is_private_field, dir(test_case)):
521 if attr_name == '_dt_test':
522 test_case._dt_test = _FakeClass(
523 name=test_case._dt_test.name)
524 elif attr_name != '_shortDescription':
525 setattr(test_case, attr_name, None)
528 self.strip_error_results(self.failures)
529 self.strip_error_results(self.errors)
530 return (self.failures, self.errors, self.testsRun,
531 self.stream.getvalue())
533 def join_results(result, data):
534 """Static method for merging the result back into the main
537 failures, errors, tests_run, output = data
539 result.stream.write(output)
540 result.errors.extend(errors)
541 result.failures.extend(failures)
542 result.testsRun += tests_run
544 join_results = staticmethod(join_results)
546 class _StringIO(StringIO):
547 def writeln(self, line):
548 self.write("%s\n" % line)
551 class CythonUnitTestCase(CythonCompileTestCase):
552 def shortDescription(self):
553 return "compiling (%s) tests in %s" % (self.language, self.module)
555 def run(self, result=None):
557 result = self.defaultTestResult()
558 result.startTest(self)
561 self.runCompileTest()
562 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
564 result.addError(self, sys.exc_info())
565 result.stopTest(self)
571 def collect_unittests(path, module_prefix, suite, selectors):
572 def file_matches(filename):
573 return filename.startswith("Test") and filename.endswith(".py")
575 def package_matches(dirname):
576 return dirname == "Tests"
578 loader = unittest.TestLoader()
582 for dirpath, dirnames, filenames in os.walk(path):
583 if dirpath != path and "__init__.py" not in filenames:
584 skipped_dirs.append(dirpath + os.path.sep)
587 for dir in skipped_dirs:
588 if dirpath.startswith(dir):
592 parentname = os.path.split(dirpath)[-1]
593 if package_matches(parentname):
596 filepath = os.path.join(dirpath, f)[:-len(".py")]
597 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
598 if not [ 1 for match in selectors if match(modulename) ]:
600 module = __import__(modulename)
601 for x in modulename.split('.')[1:]:
602 module = getattr(module, x)
603 suite.addTests([loader.loadTestsFromModule(module)])
605 def collect_doctests(path, module_prefix, suite, selectors):
606 def package_matches(dirname):
607 return dirname not in ("Mac", "Distutils", "Plex")
608 def file_matches(filename):
609 return (filename.endswith(".py") and not ('~' in filename
610 or '#' in filename or filename.startswith('.')))
611 import doctest, types
612 for dirpath, dirnames, filenames in os.walk(path):
613 parentname = os.path.split(dirpath)[-1]
614 if package_matches(parentname):
617 if not f.endswith('.py'): continue
618 filepath = os.path.join(dirpath, f)[:-len(".py")]
619 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
620 if not [ 1 for match in selectors if match(modulename) ]:
622 module = __import__(modulename)
623 for x in modulename.split('.')[1:]:
624 module = getattr(module, x)
625 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
627 suite.addTest(doctest.DocTestSuite(module))
628 except ValueError: # no tests
632 class EndToEndTest(unittest.TestCase):
634 This is a test of build/*.srctree files, where srctree defines a full
635 directory structure and its header gives a list of commands to run.
637 cython_root = os.path.dirname(os.path.abspath(__file__))
639 def __init__(self, treefile, workdir, cleanup_workdir=True):
640 self.treefile = treefile
641 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
642 self.cleanup_workdir = cleanup_workdir
643 cython_syspath = self.cython_root
644 for path in sys.path[::-1]:
645 if path.startswith(self.cython_root):
646 # Py3 installation and refnanny build prepend their
647 # fixed paths to sys.path => prefer that over the
649 cython_syspath = path + os.pathsep + cython_syspath
650 self.cython_syspath = cython_syspath
651 unittest.TestCase.__init__(self)
653 def shortDescription(self):
654 return "End-to-end %s" % self.treefile
657 from Cython.TestUtils import unpack_source_tree
658 _, self.commands = unpack_source_tree(os.path.join('tests', 'build', self.treefile), self.workdir)
659 self.old_dir = os.getcwd()
660 os.chdir(self.workdir)
661 if self.workdir not in sys.path:
662 sys.path.insert(0, self.workdir)
665 if self.cleanup_workdir:
666 shutil.rmtree(self.workdir)
667 os.chdir(self.old_dir)
670 commands = (self.commands
671 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
672 .replace("PYTHON", sys.executable))
673 old_path = os.environ.get('PYTHONPATH')
675 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + (old_path or '')
676 print(os.environ['PYTHONPATH'])
677 self.assertEqual(0, os.system(commands))
680 os.environ['PYTHONPATH'] = old_path
682 del os.environ['PYTHONPATH']
685 # TODO: Support cython_freeze needed here as well.
686 # TODO: Windows support.
688 class EmbedTest(unittest.TestCase):
690 working_dir = "Demos/embed"
693 self.old_dir = os.getcwd()
694 os.chdir(self.working_dir)
696 "make PYTHON='%s' clean > /dev/null" % sys.executable)
701 "make PYTHON='%s' clean > /dev/null" % sys.executable)
704 os.chdir(self.old_dir)
706 def test_embed(self):
707 from distutils import sysconfig
708 libname = sysconfig.get_config_var('LIBRARY')
709 libdir = sysconfig.get_config_var('LIBDIR')
710 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
711 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
712 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
713 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
714 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
715 # report the error for the original directory
716 libdir = sysconfig.get_config_var('LIBDIR')
717 self.assert_(os.system(
718 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
720 os.remove('make.output')
724 class MissingDependencyExcluder:
725 def __init__(self, deps):
726 # deps: { module name : matcher func }
727 self.exclude_matchers = []
728 for mod, matcher in deps.items():
732 self.exclude_matchers.append(matcher)
733 self.tests_missing_deps = []
734 def __call__(self, testname):
735 for matcher in self.exclude_matchers:
736 if matcher(testname):
737 self.tests_missing_deps.append(testname)
741 class VersionDependencyExcluder:
742 def __init__(self, deps):
743 # deps: { version : matcher func }
744 from sys import version_info
745 self.exclude_matchers = []
746 for ver, (compare, matcher) in deps.items():
747 if compare(version_info, ver):
748 self.exclude_matchers.append(matcher)
749 self.tests_missing_deps = []
750 def __call__(self, testname):
751 for matcher in self.exclude_matchers:
752 if matcher(testname):
753 self.tests_missing_deps.append(testname)
757 class FileListExcluder:
759 def __init__(self, list_file):
761 for line in open(list_file).readlines():
763 if line and line[0] != '#':
764 self.excludes[line.split()[0]] = True
766 def __call__(self, testname):
767 return testname in self.excludes or testname.split('.')[-1] in self.excludes
769 def refactor_for_py3(distdir, cy3_dir):
770 # need to convert Cython sources first
771 import lib2to3.refactor
772 from distutils.util import copydir_run_2to3
773 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
774 if fix.split('fix_')[-1] not in ('next',)
776 if not os.path.exists(cy3_dir):
778 import distutils.log as dlog
779 dlog.set_threshold(dlog.INFO)
780 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
784 recursive-exclude Cython *
785 recursive-include Cython *.py *.pyx *.pxd
787 sys.path.insert(0, cy3_dir)
790 if __name__ == '__main__':
791 from optparse import OptionParser
792 parser = OptionParser()
793 parser.add_option("--no-cleanup", dest="cleanup_workdir",
794 action="store_false", default=True,
795 help="do not delete the generated C files (allows passing --no-cython on next run)")
796 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
797 action="store_false", default=True,
798 help="do not delete the generated shared libary files (allows manual module experimentation)")
799 parser.add_option("--no-cython", dest="with_cython",
800 action="store_false", default=True,
801 help="do not run the Cython compiler, only the C compiler")
802 parser.add_option("--no-c", dest="use_c",
803 action="store_false", default=True,
804 help="do not test C compilation")
805 parser.add_option("--no-cpp", dest="use_cpp",
806 action="store_false", default=True,
807 help="do not test C++ compilation")
808 parser.add_option("--no-unit", dest="unittests",
809 action="store_false", default=True,
810 help="do not run the unit tests")
811 parser.add_option("--no-doctest", dest="doctests",
812 action="store_false", default=True,
813 help="do not run the doctests")
814 parser.add_option("--no-file", dest="filetests",
815 action="store_false", default=True,
816 help="do not run the file based tests")
817 parser.add_option("--no-pyregr", dest="pyregr",
818 action="store_false", default=True,
819 help="do not run the regression tests of CPython in tests/pyregr/")
820 parser.add_option("--cython-only", dest="cython_only",
821 action="store_true", default=False,
822 help="only compile pyx to c, do not run C compiler or run the tests")
823 parser.add_option("--no-refnanny", dest="with_refnanny",
824 action="store_false", default=True,
825 help="do not regression test reference counting")
826 parser.add_option("--no-fork", dest="fork",
827 action="store_false", default=True,
828 help="do not fork to run tests")
829 parser.add_option("--sys-pyregr", dest="system_pyregr",
830 action="store_true", default=False,
831 help="run the regression tests of the CPython installation")
832 parser.add_option("-x", "--exclude", dest="exclude",
833 action="append", metavar="PATTERN",
834 help="exclude tests matching the PATTERN")
835 parser.add_option("-C", "--coverage", dest="coverage",
836 action="store_true", default=False,
837 help="collect source coverage data for the Compiler")
838 parser.add_option("--coverage-xml", dest="coverage_xml",
839 action="store_true", default=False,
840 help="collect source coverage data for the Compiler in XML format")
841 parser.add_option("-A", "--annotate", dest="annotate_source",
842 action="store_true", default=True,
843 help="generate annotated HTML versions of the test source files")
844 parser.add_option("--no-annotate", dest="annotate_source",
845 action="store_false",
846 help="do not generate annotated HTML versions of the test source files")
847 parser.add_option("-v", "--verbose", dest="verbosity",
848 action="count", default=0,
849 help="display test progress, pass twice to print test names")
850 parser.add_option("-T", "--ticket", dest="tickets",
852 help="a bug ticket number to run the respective test in 'tests/*'")
853 parser.add_option("-3", dest="language_level",
854 action="store_const", const=3, default=2,
855 help="set language level to Python 3 (useful for running the CPython regression tests)'")
856 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
857 help="write test results in XML to directory DIR")
858 parser.add_option("--exit-ok", dest="exit_ok", default=False,
860 help="exit without error code even on test failures")
862 options, cmd_args = parser.parse_args()
864 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
865 ROOTDIR = os.path.join(DISTDIR, 'tests')
866 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
868 if sys.version_info[0] >= 3:
869 options.doctests = False
870 if options.with_cython:
872 # try if Cython is installed in a Py3 version
873 import Cython.Compiler.Main
875 # back out anything the import process loaded, then
876 # 2to3 the Cython sources to make them re-importable
877 cy_modules = [ name for name in sys.modules
878 if name == 'Cython' or name.startswith('Cython.') ]
879 for name in cy_modules:
880 del sys.modules[name]
881 # hasn't been refactored yet - do it now
882 cy3_dir = os.path.join(WORKDIR, 'Cy3')
883 if sys.version_info >= (3,1):
884 refactor_for_py3(DISTDIR, cy3_dir)
885 elif os.path.isdir(cy3_dir):
886 sys.path.insert(0, cy3_dir)
888 options.with_cython = False
890 WITH_CYTHON = options.with_cython
892 if options.coverage or options.coverage_xml:
894 options.coverage = options.coverage_xml = False
896 from coverage import coverage as _coverage
897 coverage = _coverage(branch=True)
902 from Cython.Compiler.Main import \
903 CompilationOptions, \
904 default_options as pyrex_default_options, \
905 compile as cython_compile
906 from Cython.Compiler import Errors
907 Errors.LEVEL = 0 # show all warnings
908 from Cython.Compiler import Options
909 Options.generate_cleanup_code = 3 # complete cleanup code
910 from Cython.Compiler import DebugFlags
911 DebugFlags.debug_temp_code_comments = 1
914 UNITTEST_MODULE = "Cython"
915 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
917 if os.path.exists(WORKDIR):
918 for path in os.listdir(WORKDIR):
919 if path in ("support", "Cy3"): continue
920 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
921 if not os.path.exists(WORKDIR):
924 sys.stderr.write("Python %s\n" % sys.version)
925 sys.stderr.write("\n")
927 from Cython.Compiler.Version import version
928 sys.stderr.write("Running tests against Cython %s\n" % version)
930 sys.stderr.write("Running tests without Cython.\n")
932 if options.with_refnanny:
933 from pyximport.pyxbuild import pyx_to_dll
934 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
936 pyxbuild_dir=os.path.join(WORKDIR, "support"))
937 sys.path.insert(0, os.path.split(libpath)[0])
938 CFLAGS.append("-DCYTHON_REFNANNY=1")
940 if options.xml_output_dir and options.fork:
941 # doesn't currently work together
942 sys.stderr.write("Disabling forked testing to support XML test output\n")
945 if WITH_CYTHON and options.language_level == 3:
946 sys.stderr.write("Using Cython language level 3.\n")
947 from Cython.Compiler import Options
948 Options.directive_defaults['language_level'] = 3
950 sys.stderr.write("\n")
954 for ticket_number in options.tickets:
956 cmd_args.append('.*T%s$' % ticket_number)
958 for selector in cmd_args:
959 if selector.startswith('bugs'):
963 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
965 selectors = [ lambda x:True ]
967 # Chech which external modules are not present and exclude tests
968 # which depends on them (by prefix)
970 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
971 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
972 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
975 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
978 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
980 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
981 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
985 languages.append('c')
987 languages.append('cpp')
989 test_suite = unittest.TestSuite()
991 if options.unittests:
992 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
995 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
997 if options.filetests and languages:
998 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
999 options.annotate_source, options.cleanup_workdir,
1000 options.cleanup_sharedlibs, options.pyregr,
1001 options.cython_only, languages, test_bugs,
1003 test_suite.addTest(filetests.build_suite())
1005 if options.system_pyregr and languages:
1006 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1007 options.annotate_source, options.cleanup_workdir,
1008 options.cleanup_sharedlibs, True,
1009 options.cython_only, languages, test_bugs,
1012 filetests.handle_directory(
1013 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1016 if options.xml_output_dir:
1017 from Cython.Tests.xmlrunner import XMLTestRunner
1018 test_runner = XMLTestRunner(output=options.xml_output_dir,
1019 verbose=options.verbosity > 0)
1021 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1023 result = test_runner.run(test_suite)
1025 if options.coverage or options.coverage_xml:
1027 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1028 modules = [ module for name, module in sys.modules.items()
1029 if module is not None and
1030 name.startswith('Cython.Compiler.') and
1031 name[len('Cython.Compiler.'):] not in ignored_modules ]
1032 if options.coverage:
1033 coverage.report(modules, show_missing=0)
1034 if options.coverage_xml:
1035 coverage.xml_report(modules, outfile="coverage-report.xml")
1037 if missing_dep_excluder.tests_missing_deps:
1038 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1039 for test in missing_dep_excluder.tests_missing_deps:
1040 sys.stderr.write(" %s\n" % test)
1042 if options.with_refnanny:
1044 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1049 sys.exit(not result.wasSuccessful())