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 def __init__(self, treefile, workdir, cleanup_workdir=True):
638 self.treefile = treefile
639 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
640 self.cleanup_workdir = cleanup_workdir
641 unittest.TestCase.__init__(self)
643 def shortDescription(self):
644 return "End-to-end %s" % self.treefile
647 from Cython.TestUtils import unpack_source_tree
648 _, self.commands = unpack_source_tree(os.path.join('tests', 'build', self.treefile), self.workdir)
649 self.old_dir = os.getcwd()
650 os.chdir(self.workdir)
651 if self.workdir not in sys.path:
652 sys.path.insert(0, self.workdir)
655 if self.cleanup_workdir:
656 shutil.rmtree(self.workdir)
657 os.chdir(self.old_dir)
660 # Assumes old_dir is root of the cython directory...
661 commands = (self.commands
662 .replace("CYTHON", "PYTHON %s" % os.path.join(self.old_dir, 'cython.py'))
663 .replace("PYTHON", sys.executable))
665 PYTHONPATH="%s%s$PYTHONPATH"
667 """ % (self.old_dir, os.pathsep, commands)
668 self.assertEqual(0, os.system(commands))
671 # TODO: Support cython_freeze needed here as well.
672 # TODO: Windows support.
674 class EmbedTest(unittest.TestCase):
676 working_dir = "Demos/embed"
679 self.old_dir = os.getcwd()
680 os.chdir(self.working_dir)
682 "make PYTHON='%s' clean > /dev/null" % sys.executable)
687 "make PYTHON='%s' clean > /dev/null" % sys.executable)
690 os.chdir(self.old_dir)
692 def test_embed(self):
693 from distutils import sysconfig
694 libname = sysconfig.get_config_var('LIBRARY')
695 libdir = sysconfig.get_config_var('LIBDIR')
696 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
697 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
698 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
699 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
700 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
701 # report the error for the original directory
702 libdir = sysconfig.get_config_var('LIBDIR')
703 self.assert_(os.system(
704 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
706 os.remove('make.output')
710 class MissingDependencyExcluder:
711 def __init__(self, deps):
712 # deps: { module name : matcher func }
713 self.exclude_matchers = []
714 for mod, matcher in deps.items():
718 self.exclude_matchers.append(matcher)
719 self.tests_missing_deps = []
720 def __call__(self, testname):
721 for matcher in self.exclude_matchers:
722 if matcher(testname):
723 self.tests_missing_deps.append(testname)
727 class VersionDependencyExcluder:
728 def __init__(self, deps):
729 # deps: { version : matcher func }
730 from sys import version_info
731 self.exclude_matchers = []
732 for ver, (compare, matcher) in deps.items():
733 if compare(version_info, ver):
734 self.exclude_matchers.append(matcher)
735 self.tests_missing_deps = []
736 def __call__(self, testname):
737 for matcher in self.exclude_matchers:
738 if matcher(testname):
739 self.tests_missing_deps.append(testname)
743 class FileListExcluder:
745 def __init__(self, list_file):
747 for line in open(list_file).readlines():
749 if line and line[0] != '#':
750 self.excludes[line.split()[0]] = True
752 def __call__(self, testname):
753 return testname in self.excludes or testname.split('.')[-1] in self.excludes
755 def refactor_for_py3(distdir, cy3_dir):
756 # need to convert Cython sources first
757 import lib2to3.refactor
758 from distutils.util import copydir_run_2to3
759 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
760 if fix.split('fix_')[-1] not in ('next',)
762 if not os.path.exists(cy3_dir):
764 import distutils.log as dlog
765 dlog.set_threshold(dlog.INFO)
766 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
770 recursive-exclude Cython *
771 recursive-include Cython *.py *.pyx *.pxd
773 sys.path.insert(0, cy3_dir)
776 if __name__ == '__main__':
777 from optparse import OptionParser
778 parser = OptionParser()
779 parser.add_option("--no-cleanup", dest="cleanup_workdir",
780 action="store_false", default=True,
781 help="do not delete the generated C files (allows passing --no-cython on next run)")
782 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
783 action="store_false", default=True,
784 help="do not delete the generated shared libary files (allows manual module experimentation)")
785 parser.add_option("--no-cython", dest="with_cython",
786 action="store_false", default=True,
787 help="do not run the Cython compiler, only the C compiler")
788 parser.add_option("--no-c", dest="use_c",
789 action="store_false", default=True,
790 help="do not test C compilation")
791 parser.add_option("--no-cpp", dest="use_cpp",
792 action="store_false", default=True,
793 help="do not test C++ compilation")
794 parser.add_option("--no-unit", dest="unittests",
795 action="store_false", default=True,
796 help="do not run the unit tests")
797 parser.add_option("--no-doctest", dest="doctests",
798 action="store_false", default=True,
799 help="do not run the doctests")
800 parser.add_option("--no-file", dest="filetests",
801 action="store_false", default=True,
802 help="do not run the file based tests")
803 parser.add_option("--no-pyregr", dest="pyregr",
804 action="store_false", default=True,
805 help="do not run the regression tests of CPython in tests/pyregr/")
806 parser.add_option("--cython-only", dest="cython_only",
807 action="store_true", default=False,
808 help="only compile pyx to c, do not run C compiler or run the tests")
809 parser.add_option("--no-refnanny", dest="with_refnanny",
810 action="store_false", default=True,
811 help="do not regression test reference counting")
812 parser.add_option("--no-fork", dest="fork",
813 action="store_false", default=True,
814 help="do not fork to run tests")
815 parser.add_option("--sys-pyregr", dest="system_pyregr",
816 action="store_true", default=False,
817 help="run the regression tests of the CPython installation")
818 parser.add_option("-x", "--exclude", dest="exclude",
819 action="append", metavar="PATTERN",
820 help="exclude tests matching the PATTERN")
821 parser.add_option("-C", "--coverage", dest="coverage",
822 action="store_true", default=False,
823 help="collect source coverage data for the Compiler")
824 parser.add_option("--coverage-xml", dest="coverage_xml",
825 action="store_true", default=False,
826 help="collect source coverage data for the Compiler in XML format")
827 parser.add_option("-A", "--annotate", dest="annotate_source",
828 action="store_true", default=True,
829 help="generate annotated HTML versions of the test source files")
830 parser.add_option("--no-annotate", dest="annotate_source",
831 action="store_false",
832 help="do not generate annotated HTML versions of the test source files")
833 parser.add_option("-v", "--verbose", dest="verbosity",
834 action="count", default=0,
835 help="display test progress, pass twice to print test names")
836 parser.add_option("-T", "--ticket", dest="tickets",
838 help="a bug ticket number to run the respective test in 'tests/*'")
839 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
840 help="write test results in XML to directory DIR")
841 parser.add_option("--exit-ok", dest="exit_ok", default=False,
843 help="exit without error code even on test failures")
845 options, cmd_args = parser.parse_args()
847 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
848 ROOTDIR = os.path.join(DISTDIR, 'tests')
849 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
851 if sys.version_info[0] >= 3:
852 options.doctests = False
853 if options.with_cython:
855 # try if Cython is installed in a Py3 version
856 import Cython.Compiler.Main
858 cy_modules = [ name for name in sys.modules
859 if name == 'Cython' or name.startswith('Cython.') ]
860 for name in cy_modules:
861 del sys.modules[name]
862 # hasn't been refactored yet - do it now
863 cy3_dir = os.path.join(WORKDIR, 'Cy3')
864 if sys.version_info >= (3,1):
865 refactor_for_py3(DISTDIR, cy3_dir)
866 elif os.path.isdir(cy3_dir):
867 sys.path.insert(0, cy3_dir)
869 options.with_cython = False
871 WITH_CYTHON = options.with_cython
873 if options.coverage or options.coverage_xml:
875 options.coverage = options.coverage_xml = False
877 from coverage import coverage as _coverage
878 coverage = _coverage(branch=True)
883 from Cython.Compiler.Main import \
884 CompilationOptions, \
885 default_options as pyrex_default_options, \
886 compile as cython_compile
887 from Cython.Compiler import Errors
888 Errors.LEVEL = 0 # show all warnings
889 from Cython.Compiler import Options
890 Options.generate_cleanup_code = 3 # complete cleanup code
891 from Cython.Compiler import DebugFlags
892 DebugFlags.debug_temp_code_comments = 1
895 UNITTEST_MODULE = "Cython"
896 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
898 if os.path.exists(WORKDIR):
899 for path in os.listdir(WORKDIR):
900 if path in ("support", "Cy3"): continue
901 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
902 if not os.path.exists(WORKDIR):
906 from Cython.Compiler.Version import version
907 sys.stderr.write("Running tests against Cython %s\n" % version)
909 sys.stderr.write("Running tests without Cython.\n")
910 sys.stderr.write("Python %s\n" % sys.version)
911 sys.stderr.write("\n")
913 if options.with_refnanny:
914 from pyximport.pyxbuild import pyx_to_dll
915 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
917 pyxbuild_dir=os.path.join(WORKDIR, "support"))
918 sys.path.insert(0, os.path.split(libpath)[0])
919 CFLAGS.append("-DCYTHON_REFNANNY=1")
921 if options.xml_output_dir and options.fork:
922 # doesn't currently work together
923 sys.stderr.write("Disabling forked testing to support XML test output\n")
928 for ticket_number in options.tickets:
930 cmd_args.append('.*T%s$' % ticket_number)
932 for selector in cmd_args:
933 if selector.startswith('bugs'):
937 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
939 selectors = [ lambda x:True ]
941 # Chech which external modules are not present and exclude tests
942 # which depends on them (by prefix)
944 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
945 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
946 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
949 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
952 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
954 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
955 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
959 languages.append('c')
961 languages.append('cpp')
963 test_suite = unittest.TestSuite()
965 if options.unittests:
966 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
969 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
971 if options.filetests and languages:
972 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
973 options.annotate_source, options.cleanup_workdir,
974 options.cleanup_sharedlibs, options.pyregr,
975 options.cython_only, languages, test_bugs,
977 test_suite.addTest(filetests.build_suite())
979 if options.system_pyregr and languages:
980 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
981 options.annotate_source, options.cleanup_workdir,
982 options.cleanup_sharedlibs, True,
983 options.cython_only, languages, test_bugs,
986 filetests.handle_directory(
987 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
990 if options.xml_output_dir:
991 from Cython.Tests.xmlrunner import XMLTestRunner
992 test_runner = XMLTestRunner(output=options.xml_output_dir,
993 verbose=options.verbosity > 0)
995 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
997 result = test_runner.run(test_suite)
999 if options.coverage or options.coverage_xml:
1001 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1002 modules = [ module for name, module in sys.modules.items()
1003 if module is not None and
1004 name.startswith('Cython.Compiler.') and
1005 name[len('Cython.Compiler.'):] not in ignored_modules ]
1006 if options.coverage:
1007 coverage.report(modules, show_missing=0)
1008 if options.coverage_xml:
1009 coverage.xml_report(modules, outfile="coverage-report.xml")
1011 if missing_dep_excluder.tests_missing_deps:
1012 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1013 for test in missing_dep_excluder.tests_missing_deps:
1014 sys.stderr.write(" %s\n" % test)
1016 if options.with_refnanny:
1018 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1023 sys.exit(not result.wasSuccessful())