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, language_level):
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
133 self.language_level = language_level
135 def build_suite(self):
136 suite = unittest.TestSuite()
137 test_dirs = TEST_DIRS
138 filenames = os.listdir(self.rootdir)
140 for filename in filenames:
141 if not WITH_CYTHON and filename == "errors":
142 # we won't get any errors without running Cython
144 path = os.path.join(self.rootdir, filename)
145 if os.path.isdir(path) and filename in test_dirs:
146 if filename == 'pyregr' and not self.with_pyregr:
149 self.handle_directory(path, filename))
150 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
151 # Non-Windows makefile, can't run Cython under Py3.
152 if [1 for selector in self.selectors if selector("embedded")]:
153 suite.addTest(unittest.makeSuite(EmbedTest))
156 def handle_directory(self, path, context):
157 workdir = os.path.join(self.workdir, context)
158 if not os.path.exists(workdir):
161 expect_errors = (context == 'errors')
162 suite = unittest.TestSuite()
163 filenames = os.listdir(path)
165 for filename in filenames:
166 if context == "build" and filename.endswith(".srctree"):
167 if not [ 1 for match in self.selectors if match(filename) ]:
169 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
171 if not (filename.endswith(".pyx") or filename.endswith(".py")):
173 if filename.startswith('.'): continue # certain emacs backup files
174 if context == 'pyregr' and not filename.startswith('test_'):
176 module = os.path.splitext(filename)[0]
177 fqmodule = "%s.%s" % (context, module)
178 if not [ 1 for match in self.selectors
179 if match(fqmodule) ]:
181 if self.exclude_selectors:
182 if [1 for match in self.exclude_selectors if match(fqmodule)]:
184 if context in TEST_RUN_DIRS:
185 if module.startswith("test_"):
186 test_class = CythonUnitTestCase
188 test_class = CythonRunTestCase
190 test_class = CythonCompileTestCase
191 for test in self.build_tests(test_class, path, workdir,
192 module, expect_errors):
194 if filename.endswith('.py'):
195 # additionally test file in real Python
196 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
199 def build_tests(self, test_class, path, workdir, module, expect_errors):
201 if 'cpp' in module and 'cpp' in self.languages:
204 languages = self.languages[:1]
206 languages = self.languages
207 if 'cpp' in module and 'c' in languages:
208 languages = list(languages)
209 languages.remove('c')
210 tests = [ self.build_test(test_class, path, workdir, module,
211 language, expect_errors)
212 for language in languages ]
215 def build_test(self, test_class, path, workdir, module,
216 language, expect_errors):
217 workdir = os.path.join(workdir, language)
218 if not os.path.exists(workdir):
220 return test_class(path, workdir, module,
222 expect_errors=expect_errors,
223 annotate=self.annotate,
224 cleanup_workdir=self.cleanup_workdir,
225 cleanup_sharedlibs=self.cleanup_sharedlibs,
226 cython_only=self.cython_only,
228 language_level=self.language_level)
230 class CythonCompileTestCase(unittest.TestCase):
231 def __init__(self, test_directory, workdir, module, language='c',
232 expect_errors=False, annotate=False, cleanup_workdir=True,
233 cleanup_sharedlibs=True, cython_only=False, fork=True,
235 self.test_directory = test_directory
236 self.workdir = workdir
238 self.language = language
239 self.expect_errors = expect_errors
240 self.annotate = annotate
241 self.cleanup_workdir = cleanup_workdir
242 self.cleanup_sharedlibs = cleanup_sharedlibs
243 self.cython_only = cython_only
245 self.language_level = language_level
246 unittest.TestCase.__init__(self)
248 def shortDescription(self):
249 return "compiling (%s) %s" % (self.language, self.module)
252 if self.workdir not in sys.path:
253 sys.path.insert(0, self.workdir)
257 sys.path.remove(self.workdir)
261 del sys.modules[self.module]
264 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
265 cleanup_lib_files = self.cleanup_sharedlibs
266 if os.path.exists(self.workdir):
267 for rmfile in os.listdir(self.workdir):
268 if not cleanup_c_files:
269 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
271 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
273 if self.annotate and rmfile.endswith(".html"):
276 rmfile = os.path.join(self.workdir, rmfile)
277 if os.path.isdir(rmfile):
278 shutil.rmtree(rmfile, ignore_errors=True)
284 os.makedirs(self.workdir)
287 self.runCompileTest()
289 def runCompileTest(self):
290 self.compile(self.test_directory, self.module, self.workdir,
291 self.test_directory, self.expect_errors, self.annotate)
293 def find_module_source_file(self, source_file):
294 if not os.path.exists(source_file):
295 source_file = source_file[:-1]
298 def build_target_filename(self, module_name):
299 target = '%s.%s' % (module_name, self.language)
302 def copy_related_files(self, test_directory, target_directory, module_name):
303 is_related = re.compile('%s_.*[.].*' % module_name).match
304 for filename in os.listdir(test_directory):
305 if is_related(filename):
306 shutil.copy(os.path.join(test_directory, filename),
309 def find_source_files(self, workdir, module_name):
310 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
311 return [self.build_target_filename(module_name)] + [
312 filename for filename in os.listdir(workdir)
313 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
315 def split_source_and_output(self, test_directory, module, workdir):
316 source_file = os.path.join(test_directory, module) + '.pyx'
317 source_and_output = codecs.open(
318 self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
319 out = codecs.open(os.path.join(workdir, module + '.pyx'),
321 for line in source_and_output:
323 if line.startswith("_ERRORS"):
329 geterrors = out.geterrors
330 except AttributeError:
335 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
336 include_dirs = INCLUDE_DIRS[:]
338 include_dirs.append(incdir)
339 source = self.find_module_source_file(
340 os.path.join(test_directory, module + '.pyx'))
341 target = os.path.join(targetdir, self.build_target_filename(module))
342 options = CompilationOptions(
343 pyrex_default_options,
344 include_path = include_dirs,
345 output_file = target,
347 use_listing_file = False,
348 cplus = self.language == 'cpp',
349 language_level = self.language_level,
350 generate_pxi = False,
351 evaluate_tree_assertions = True,
353 cython_compile(source, options=options,
354 full_module_name=module)
356 def run_distutils(self, test_directory, module, workdir, incdir):
360 build_extension = build_ext(distutils_distro)
361 build_extension.include_dirs = INCLUDE_DIRS[:]
363 build_extension.include_dirs.append(incdir)
364 build_extension.finalize_options()
365 ext_include_dirs = []
366 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
368 ext_include_dirs += get_additional_include_dirs()
369 self.copy_related_files(test_directory, workdir, module)
370 extension = Extension(
372 sources = self.find_source_files(workdir, module),
373 include_dirs = ext_include_dirs,
374 extra_compile_args = CFLAGS,
376 if self.language == 'cpp':
377 extension.language = 'c++'
378 build_extension.extensions = [extension]
379 build_extension.build_temp = workdir
380 build_extension.build_lib = workdir
381 build_extension.run()
385 def compile(self, test_directory, module, workdir, incdir,
386 expect_errors, annotate):
387 expected_errors = errors = ()
389 expected_errors = self.split_source_and_output(
390 test_directory, module, workdir)
391 test_directory = workdir
394 old_stderr = sys.stderr
396 sys.stderr = ErrorWriter()
397 self.run_cython(test_directory, module, workdir, incdir, annotate)
398 errors = sys.stderr.geterrors()
400 sys.stderr = old_stderr
402 if errors or expected_errors:
404 for expected, error in zip(expected_errors, errors):
405 self.assertEquals(expected, error)
406 if len(errors) < len(expected_errors):
407 expected_error = expected_errors[len(errors)]
408 self.assertEquals(expected_error, None)
409 elif len(errors) > len(expected_errors):
410 unexpected_error = errors[len(expected_errors)]
411 self.assertEquals(None, unexpected_error)
412 except AssertionError:
413 print("\n=== Expected errors: ===")
414 print('\n'.join(expected_errors))
415 print("\n\n=== Got errors: ===")
416 print('\n'.join(errors))
420 if not self.cython_only:
421 self.run_distutils(test_directory, module, workdir, incdir)
423 class CythonRunTestCase(CythonCompileTestCase):
424 def shortDescription(self):
425 return "compiling (%s) and running %s" % (self.language, self.module)
427 def run(self, result=None):
429 result = self.defaultTestResult()
430 result.startTest(self)
433 self.runCompileTest()
434 if not self.cython_only:
435 self.run_doctests(self.module, result)
437 result.addError(self, sys.exc_info())
438 result.stopTest(self)
444 def run_doctests(self, module_name, result):
445 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
446 doctest.DocTestSuite(module_name).run(result)
450 # fork to make sure we do not keep the tested module loaded
451 result_handle, result_file = tempfile.mkstemp()
452 os.close(result_handle)
460 partial_result = PartialTestResult(result)
461 tests = doctest.DocTestSuite(module_name)
462 tests.run(partial_result)
466 # importing failed, try to fake a test class
468 failureException=sys.exc_info()[1],
469 _shortDescription=self.shortDescription(),
471 partial_result.addError(tests, sys.exc_info())
473 output = open(result_file, 'wb')
474 pickle.dump(partial_result.data(), output)
477 traceback.print_exc()
481 os._exit(result_code)
484 cid, result_code = os.waitpid(child_id, 0)
485 # os.waitpid returns the child's result code in the
486 # upper byte of result_code, and the signal it was
487 # killed by in the lower byte
488 if result_code & 255:
489 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
490 (module_name, result_code & 255))
491 result_code = result_code >> 8
492 if result_code in (0,1):
493 input = open(result_file, 'rb')
495 PartialTestResult.join_results(result, pickle.load(input))
499 raise Exception("Tests in module '%s' exited with status %d" %
500 (module_name, result_code))
502 try: os.unlink(result_file)
505 class PureDoctestTestCase(unittest.TestCase):
506 def __init__(self, module_name, module_path):
507 self.module_name = module_name
508 self.module_path = module_path
509 unittest.TestCase.__init__(self, 'run')
511 def shortDescription(self):
512 return "running pure doctests in %s" % self.module_name
514 def run(self, result=None):
516 result = self.defaultTestResult()
517 loaded_module_name = 'pure_doctest__' + self.module_name
518 result.startTest(self)
523 m = imp.load_source(loaded_module_name, self.module_path)
525 doctest.DocTestSuite(m).run(result)
528 if loaded_module_name in sys.modules:
529 del sys.modules[loaded_module_name]
531 result.addError(self, sys.exc_info())
532 result.stopTest(self)
538 is_private_field = re.compile('^_[^_]').match
540 class _FakeClass(object):
541 def __init__(self, **kwargs):
542 self._shortDescription = kwargs.get('module_name')
543 self.__dict__.update(kwargs)
544 def shortDescription(self):
545 return self._shortDescription
547 try: # Py2.7+ and Py3.2+
548 from unittest.runner import _TextTestResult
550 from unittest import _TextTestResult
552 class PartialTestResult(_TextTestResult):
553 def __init__(self, base_result):
554 _TextTestResult.__init__(
555 self, self._StringIO(), True,
556 base_result.dots + base_result.showAll*2)
558 def strip_error_results(self, results):
559 for test_case, error in results:
560 for attr_name in filter(is_private_field, dir(test_case)):
561 if attr_name == '_dt_test':
562 test_case._dt_test = _FakeClass(
563 name=test_case._dt_test.name)
564 elif attr_name != '_shortDescription':
565 setattr(test_case, attr_name, None)
568 self.strip_error_results(self.failures)
569 self.strip_error_results(self.errors)
570 return (self.failures, self.errors, self.testsRun,
571 self.stream.getvalue())
573 def join_results(result, data):
574 """Static method for merging the result back into the main
577 failures, errors, tests_run, output = data
579 result.stream.write(output)
580 result.errors.extend(errors)
581 result.failures.extend(failures)
582 result.testsRun += tests_run
584 join_results = staticmethod(join_results)
586 class _StringIO(StringIO):
587 def writeln(self, line):
588 self.write("%s\n" % line)
591 class CythonUnitTestCase(CythonCompileTestCase):
592 def shortDescription(self):
593 return "compiling (%s) tests in %s" % (self.language, self.module)
595 def run(self, result=None):
597 result = self.defaultTestResult()
598 result.startTest(self)
601 self.runCompileTest()
602 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
604 result.addError(self, sys.exc_info())
605 result.stopTest(self)
611 def collect_unittests(path, module_prefix, suite, selectors):
612 def file_matches(filename):
613 return filename.startswith("Test") and filename.endswith(".py")
615 def package_matches(dirname):
616 return dirname == "Tests"
618 loader = unittest.TestLoader()
622 for dirpath, dirnames, filenames in os.walk(path):
623 if dirpath != path and "__init__.py" not in filenames:
624 skipped_dirs.append(dirpath + os.path.sep)
627 for dir in skipped_dirs:
628 if dirpath.startswith(dir):
632 parentname = os.path.split(dirpath)[-1]
633 if package_matches(parentname):
636 filepath = os.path.join(dirpath, f)[:-len(".py")]
637 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
638 if not [ 1 for match in selectors if match(modulename) ]:
640 module = __import__(modulename)
641 for x in modulename.split('.')[1:]:
642 module = getattr(module, x)
643 suite.addTests([loader.loadTestsFromModule(module)])
645 def collect_doctests(path, module_prefix, suite, selectors):
646 def package_matches(dirname):
647 return dirname not in ("Mac", "Distutils", "Plex")
648 def file_matches(filename):
649 return (filename.endswith(".py") and not ('~' in filename
650 or '#' in filename or filename.startswith('.')))
651 import doctest, types
652 for dirpath, dirnames, filenames in os.walk(path):
653 parentname = os.path.split(dirpath)[-1]
654 if package_matches(parentname):
657 if not f.endswith('.py'): continue
658 filepath = os.path.join(dirpath, f)[:-len(".py")]
659 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
660 if not [ 1 for match in selectors if match(modulename) ]:
662 module = __import__(modulename)
663 for x in modulename.split('.')[1:]:
664 module = getattr(module, x)
665 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
667 suite.addTest(doctest.DocTestSuite(module))
668 except ValueError: # no tests
672 class EndToEndTest(unittest.TestCase):
674 This is a test of build/*.srctree files, where srctree defines a full
675 directory structure and its header gives a list of commands to run.
677 cython_root = os.path.dirname(os.path.abspath(__file__))
679 def __init__(self, treefile, workdir, cleanup_workdir=True):
680 self.treefile = treefile
681 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
682 self.cleanup_workdir = cleanup_workdir
683 cython_syspath = self.cython_root
684 for path in sys.path[::-1]:
685 if path.startswith(self.cython_root):
686 # Py3 installation and refnanny build prepend their
687 # fixed paths to sys.path => prefer that over the
689 cython_syspath = path + os.pathsep + cython_syspath
690 self.cython_syspath = cython_syspath
691 unittest.TestCase.__init__(self)
693 def shortDescription(self):
694 return "End-to-end %s" % self.treefile
697 from Cython.TestUtils import unpack_source_tree
698 _, self.commands = unpack_source_tree(os.path.join('tests', 'build', self.treefile), self.workdir)
699 self.old_dir = os.getcwd()
700 os.chdir(self.workdir)
701 if self.workdir not in sys.path:
702 sys.path.insert(0, self.workdir)
705 if self.cleanup_workdir:
706 shutil.rmtree(self.workdir)
707 os.chdir(self.old_dir)
710 commands = (self.commands
711 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
712 .replace("PYTHON", sys.executable))
713 old_path = os.environ.get('PYTHONPATH')
715 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + (old_path or '')
716 print(os.environ['PYTHONPATH'])
717 self.assertEqual(0, os.system(commands))
720 os.environ['PYTHONPATH'] = old_path
722 del os.environ['PYTHONPATH']
725 # TODO: Support cython_freeze needed here as well.
726 # TODO: Windows support.
728 class EmbedTest(unittest.TestCase):
730 working_dir = "Demos/embed"
733 self.old_dir = os.getcwd()
734 os.chdir(self.working_dir)
736 "make PYTHON='%s' clean > /dev/null" % sys.executable)
741 "make PYTHON='%s' clean > /dev/null" % sys.executable)
744 os.chdir(self.old_dir)
746 def test_embed(self):
747 from distutils import sysconfig
748 libname = sysconfig.get_config_var('LIBRARY')
749 libdir = sysconfig.get_config_var('LIBDIR')
750 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
751 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
752 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
753 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
754 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
755 # report the error for the original directory
756 libdir = sysconfig.get_config_var('LIBDIR')
757 self.assert_(os.system(
758 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
760 os.remove('make.output')
764 class MissingDependencyExcluder:
765 def __init__(self, deps):
766 # deps: { module name : matcher func }
767 self.exclude_matchers = []
768 for mod, matcher in deps.items():
772 self.exclude_matchers.append(matcher)
773 self.tests_missing_deps = []
774 def __call__(self, testname):
775 for matcher in self.exclude_matchers:
776 if matcher(testname):
777 self.tests_missing_deps.append(testname)
781 class VersionDependencyExcluder:
782 def __init__(self, deps):
783 # deps: { version : matcher func }
784 from sys import version_info
785 self.exclude_matchers = []
786 for ver, (compare, matcher) in deps.items():
787 if compare(version_info, ver):
788 self.exclude_matchers.append(matcher)
789 self.tests_missing_deps = []
790 def __call__(self, testname):
791 for matcher in self.exclude_matchers:
792 if matcher(testname):
793 self.tests_missing_deps.append(testname)
797 class FileListExcluder:
799 def __init__(self, list_file):
803 for line in f.readlines():
805 if line and line[0] != '#':
806 self.excludes[line.split()[0]] = True
810 def __call__(self, testname):
811 return testname in self.excludes or testname.split('.')[-1] in self.excludes
813 def refactor_for_py3(distdir, cy3_dir):
814 # need to convert Cython sources first
815 import lib2to3.refactor
816 from distutils.util import copydir_run_2to3
817 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
818 if fix.split('fix_')[-1] not in ('next',)
820 if not os.path.exists(cy3_dir):
822 import distutils.log as dlog
823 dlog.set_threshold(dlog.INFO)
824 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
828 recursive-exclude Cython *
829 recursive-include Cython *.py *.pyx *.pxd
831 sys.path.insert(0, cy3_dir)
834 if __name__ == '__main__':
835 from optparse import OptionParser
836 parser = OptionParser()
837 parser.add_option("--no-cleanup", dest="cleanup_workdir",
838 action="store_false", default=True,
839 help="do not delete the generated C files (allows passing --no-cython on next run)")
840 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
841 action="store_false", default=True,
842 help="do not delete the generated shared libary files (allows manual module experimentation)")
843 parser.add_option("--no-cython", dest="with_cython",
844 action="store_false", default=True,
845 help="do not run the Cython compiler, only the C compiler")
846 parser.add_option("--no-c", dest="use_c",
847 action="store_false", default=True,
848 help="do not test C compilation")
849 parser.add_option("--no-cpp", dest="use_cpp",
850 action="store_false", default=True,
851 help="do not test C++ compilation")
852 parser.add_option("--no-unit", dest="unittests",
853 action="store_false", default=True,
854 help="do not run the unit tests")
855 parser.add_option("--no-doctest", dest="doctests",
856 action="store_false", default=True,
857 help="do not run the doctests")
858 parser.add_option("--no-file", dest="filetests",
859 action="store_false", default=True,
860 help="do not run the file based tests")
861 parser.add_option("--no-pyregr", dest="pyregr",
862 action="store_false", default=True,
863 help="do not run the regression tests of CPython in tests/pyregr/")
864 parser.add_option("--cython-only", dest="cython_only",
865 action="store_true", default=False,
866 help="only compile pyx to c, do not run C compiler or run the tests")
867 parser.add_option("--no-refnanny", dest="with_refnanny",
868 action="store_false", default=True,
869 help="do not regression test reference counting")
870 parser.add_option("--no-fork", dest="fork",
871 action="store_false", default=True,
872 help="do not fork to run tests")
873 parser.add_option("--sys-pyregr", dest="system_pyregr",
874 action="store_true", default=False,
875 help="run the regression tests of the CPython installation")
876 parser.add_option("-x", "--exclude", dest="exclude",
877 action="append", metavar="PATTERN",
878 help="exclude tests matching the PATTERN")
879 parser.add_option("-C", "--coverage", dest="coverage",
880 action="store_true", default=False,
881 help="collect source coverage data for the Compiler")
882 parser.add_option("--coverage-xml", dest="coverage_xml",
883 action="store_true", default=False,
884 help="collect source coverage data for the Compiler in XML format")
885 parser.add_option("-A", "--annotate", dest="annotate_source",
886 action="store_true", default=True,
887 help="generate annotated HTML versions of the test source files")
888 parser.add_option("--no-annotate", dest="annotate_source",
889 action="store_false",
890 help="do not generate annotated HTML versions of the test source files")
891 parser.add_option("-v", "--verbose", dest="verbosity",
892 action="count", default=0,
893 help="display test progress, pass twice to print test names")
894 parser.add_option("-T", "--ticket", dest="tickets",
896 help="a bug ticket number to run the respective test in 'tests/*'")
897 parser.add_option("-3", dest="language_level",
898 action="store_const", const=3, default=2,
899 help="set language level to Python 3 (useful for running the CPython regression tests)'")
900 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
901 help="write test results in XML to directory DIR")
902 parser.add_option("--exit-ok", dest="exit_ok", default=False,
904 help="exit without error code even on test failures")
906 options, cmd_args = parser.parse_args()
908 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
909 ROOTDIR = os.path.join(DISTDIR, 'tests')
910 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
912 if sys.version_info[0] >= 3:
913 options.doctests = False
914 if options.with_cython:
916 # try if Cython is installed in a Py3 version
917 import Cython.Compiler.Main
919 # back out anything the import process loaded, then
920 # 2to3 the Cython sources to make them re-importable
921 cy_modules = [ name for name in sys.modules
922 if name == 'Cython' or name.startswith('Cython.') ]
923 for name in cy_modules:
924 del sys.modules[name]
925 # hasn't been refactored yet - do it now
926 cy3_dir = os.path.join(WORKDIR, 'Cy3')
927 if sys.version_info >= (3,1):
928 refactor_for_py3(DISTDIR, cy3_dir)
929 elif os.path.isdir(cy3_dir):
930 sys.path.insert(0, cy3_dir)
932 options.with_cython = False
934 WITH_CYTHON = options.with_cython
936 if options.coverage or options.coverage_xml:
938 options.coverage = options.coverage_xml = False
940 from coverage import coverage as _coverage
941 coverage = _coverage(branch=True)
946 from Cython.Compiler.Main import \
947 CompilationOptions, \
948 default_options as pyrex_default_options, \
949 compile as cython_compile
950 from Cython.Compiler import Errors
951 Errors.LEVEL = 0 # show all warnings
952 from Cython.Compiler import Options
953 Options.generate_cleanup_code = 3 # complete cleanup code
954 from Cython.Compiler import DebugFlags
955 DebugFlags.debug_temp_code_comments = 1
958 UNITTEST_MODULE = "Cython"
959 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
961 if os.path.exists(WORKDIR):
962 for path in os.listdir(WORKDIR):
963 if path in ("support", "Cy3"): continue
964 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
965 if not os.path.exists(WORKDIR):
968 sys.stderr.write("Python %s\n" % sys.version)
969 sys.stderr.write("\n")
971 from Cython.Compiler.Version import version
972 sys.stderr.write("Running tests against Cython %s\n" % version)
974 sys.stderr.write("Running tests without Cython.\n")
976 if options.with_refnanny:
977 from pyximport.pyxbuild import pyx_to_dll
978 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
980 pyxbuild_dir=os.path.join(WORKDIR, "support"))
981 sys.path.insert(0, os.path.split(libpath)[0])
982 CFLAGS.append("-DCYTHON_REFNANNY=1")
984 if options.xml_output_dir and options.fork:
985 # doesn't currently work together
986 sys.stderr.write("Disabling forked testing to support XML test output\n")
989 if WITH_CYTHON and options.language_level == 3:
990 sys.stderr.write("Using Cython language level 3.\n")
992 sys.stderr.write("\n")
996 for ticket_number in options.tickets:
998 cmd_args.append('.*T%s$' % ticket_number)
1000 for selector in cmd_args:
1001 if selector.startswith('bugs'):
1005 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1007 selectors = [ lambda x:True ]
1009 # Chech which external modules are not present and exclude tests
1010 # which depends on them (by prefix)
1012 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1013 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1014 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1017 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1020 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1022 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1023 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1027 languages.append('c')
1029 languages.append('cpp')
1031 test_suite = unittest.TestSuite()
1033 if options.unittests:
1034 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1036 if options.doctests:
1037 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1039 if options.filetests and languages:
1040 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1041 options.annotate_source, options.cleanup_workdir,
1042 options.cleanup_sharedlibs, options.pyregr,
1043 options.cython_only, languages, test_bugs,
1044 options.fork, options.language_level)
1045 test_suite.addTest(filetests.build_suite())
1047 if options.system_pyregr and languages:
1048 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1049 options.annotate_source, options.cleanup_workdir,
1050 options.cleanup_sharedlibs, True,
1051 options.cython_only, languages, test_bugs,
1052 options.fork, options.language_level)
1054 filetests.handle_directory(
1055 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1058 if options.xml_output_dir:
1059 from Cython.Tests.xmlrunner import XMLTestRunner
1060 test_runner = XMLTestRunner(output=options.xml_output_dir,
1061 verbose=options.verbosity > 0)
1063 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1065 result = test_runner.run(test_suite)
1067 if options.coverage or options.coverage_xml:
1069 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1070 modules = [ module for name, module in sys.modules.items()
1071 if module is not None and
1072 name.startswith('Cython.Compiler.') and
1073 name[len('Cython.Compiler.'):] not in ignored_modules ]
1074 if options.coverage:
1075 coverage.report(modules, show_missing=0)
1076 if options.coverage_xml:
1077 coverage.xml_report(modules, outfile="coverage-report.xml")
1079 if missing_dep_excluder.tests_missing_deps:
1080 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1081 for test in missing_dep_excluder.tests_missing_deps:
1082 sys.stderr.write(" %s\n" % test)
1084 if options.with_refnanny:
1086 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1091 sys.exit(not result.wasSuccessful())