15 from StringIO import StringIO
17 from io import StringIO
20 import cPickle as pickle
26 except ImportError: # No threads, no problems
32 from distutils.dist import Distribution
33 from distutils.core import Extension
34 from distutils.command.build_ext import build_ext as _build_ext
35 distutils_distro = Distribution()
37 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr', 'build']
38 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
40 # Lists external modules, and a matcher matching tests
41 # which should be excluded if the module is not present.
43 'numpy' : re.compile('.*\.numpy_.*').match,
44 'pstats' : re.compile('.*\.pstats_.*').match,
45 'posix' : re.compile('.*\.posix_.*').match,
48 def get_numpy_include_dirs():
50 return [numpy.get_include()]
53 # test name matcher , callable returning list
54 (re.compile('numpy_.*').match, get_numpy_include_dirs),
58 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
59 # (2,4) : (operator.le, ...) excludes ... when PyVer <= 2.4.x
60 (2,5) : (operator.lt, lambda x: x in ['run.any',
63 (2,4) : (operator.le, lambda x: x in ['run.extern_builtins_T258'
65 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
68 # The next line should start (3,); but this is a dictionary, so
69 # we can only have one (3,) key. Since 2.7 is supposed to be the
70 # last 2.x release, things would have to change drastically for this
72 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
73 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
74 'compile.extsetslice',
75 'compile.extdelslice',
76 'run.special_methods_T561_py2']),
79 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
80 CFLAGS = os.getenv('CFLAGS', '').split()
82 class build_ext(_build_ext):
83 def build_extension(self, ext):
84 if ext.language == 'c++':
86 try: # Py2.7+ & Py3.2+
87 compiler_obj = self.compiler_obj
88 except AttributeError:
89 compiler_obj = self.compiler
90 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
93 _build_ext.build_extension(self, ext)
95 class ErrorWriter(object):
96 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
99 self.write = self.output.append
101 def _collect(self, collect_errors, collect_warnings):
102 s = ''.join(self.output)
104 for line in s.split('\n'):
105 match = self.match_error(line)
107 is_warning, line, column, message = match.groups()
108 if (is_warning and collect_warnings) or \
109 (not is_warning and collect_errors):
110 result.append( (int(line), int(column), message.strip()) )
112 return [ "%d:%d: %s" % values for values in result ]
115 return self._collect(True, False)
117 def getwarnings(self):
118 return self._collect(False, True)
121 return self._collect(True, True)
123 class TestBuilder(object):
124 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
125 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
126 languages, test_bugs, fork, language_level):
127 self.rootdir = rootdir
128 self.workdir = workdir
129 self.selectors = selectors
130 self.exclude_selectors = exclude_selectors
131 self.annotate = annotate
132 self.cleanup_workdir = cleanup_workdir
133 self.cleanup_sharedlibs = cleanup_sharedlibs
134 self.with_pyregr = with_pyregr
135 self.cython_only = cython_only
136 self.languages = languages
137 self.test_bugs = test_bugs
139 self.language_level = language_level
141 def build_suite(self):
142 suite = unittest.TestSuite()
143 test_dirs = TEST_DIRS
144 filenames = os.listdir(self.rootdir)
146 for filename in filenames:
147 if not WITH_CYTHON and filename == "errors":
148 # we won't get any errors without running Cython
150 path = os.path.join(self.rootdir, filename)
151 if os.path.isdir(path) and filename in test_dirs:
152 if filename == 'pyregr' and not self.with_pyregr:
155 self.handle_directory(path, filename))
156 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
157 # Non-Windows makefile, can't run Cython under Py3.
158 if [1 for selector in self.selectors if selector("embedded")]:
159 suite.addTest(unittest.makeSuite(EmbedTest))
162 def handle_directory(self, path, context):
163 workdir = os.path.join(self.workdir, context)
164 if not os.path.exists(workdir):
167 expect_errors = (context == 'errors')
168 suite = unittest.TestSuite()
169 filenames = os.listdir(path)
171 for filename in filenames:
172 if context == "build" and filename.endswith(".srctree"):
173 if not [ 1 for match in self.selectors if match(filename) ]:
175 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
177 if not (filename.endswith(".pyx") or filename.endswith(".py")):
179 if filename.startswith('.'): continue # certain emacs backup files
180 if context == 'pyregr' and not filename.startswith('test_'):
182 module = os.path.splitext(filename)[0]
183 fqmodule = "%s.%s" % (context, module)
184 if not [ 1 for match in self.selectors
185 if match(fqmodule) ]:
187 if self.exclude_selectors:
188 if [1 for match in self.exclude_selectors if match(fqmodule)]:
190 if context in TEST_RUN_DIRS:
191 if module.startswith("test_"):
192 test_class = CythonUnitTestCase
194 test_class = CythonRunTestCase
196 test_class = CythonCompileTestCase
197 for test in self.build_tests(test_class, path, workdir,
198 module, expect_errors):
200 if context == 'run' and filename.endswith('.py'):
201 # additionally test file in real Python
202 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
205 def build_tests(self, test_class, path, workdir, module, expect_errors):
207 if 'cpp' in module and 'cpp' in self.languages:
210 languages = self.languages[:1]
212 languages = self.languages
213 if 'cpp' in module and 'c' in languages:
214 languages = list(languages)
215 languages.remove('c')
216 tests = [ self.build_test(test_class, path, workdir, module,
217 language, expect_errors)
218 for language in languages ]
221 def build_test(self, test_class, path, workdir, module,
222 language, expect_errors):
223 workdir = os.path.join(workdir, language)
224 if not os.path.exists(workdir):
226 return test_class(path, workdir, module,
228 expect_errors=expect_errors,
229 annotate=self.annotate,
230 cleanup_workdir=self.cleanup_workdir,
231 cleanup_sharedlibs=self.cleanup_sharedlibs,
232 cython_only=self.cython_only,
234 language_level=self.language_level)
236 class CythonCompileTestCase(unittest.TestCase):
237 def __init__(self, test_directory, workdir, module, language='c',
238 expect_errors=False, annotate=False, cleanup_workdir=True,
239 cleanup_sharedlibs=True, cython_only=False, fork=True,
241 self.test_directory = test_directory
242 self.workdir = workdir
244 self.language = language
245 self.expect_errors = expect_errors
246 self.annotate = annotate
247 self.cleanup_workdir = cleanup_workdir
248 self.cleanup_sharedlibs = cleanup_sharedlibs
249 self.cython_only = cython_only
251 self.language_level = language_level
252 unittest.TestCase.__init__(self)
254 def shortDescription(self):
255 return "compiling (%s) %s" % (self.language, self.module)
258 if self.workdir not in sys.path:
259 sys.path.insert(0, self.workdir)
263 sys.path.remove(self.workdir)
267 del sys.modules[self.module]
270 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
271 cleanup_lib_files = self.cleanup_sharedlibs
272 if os.path.exists(self.workdir):
273 for rmfile in os.listdir(self.workdir):
274 if not cleanup_c_files:
275 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
277 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
279 if self.annotate and rmfile.endswith(".html"):
282 rmfile = os.path.join(self.workdir, rmfile)
283 if os.path.isdir(rmfile):
284 shutil.rmtree(rmfile, ignore_errors=True)
290 os.makedirs(self.workdir)
293 self.runCompileTest()
295 def runCompileTest(self):
296 self.compile(self.test_directory, self.module, self.workdir,
297 self.test_directory, self.expect_errors, self.annotate)
299 def find_module_source_file(self, source_file):
300 if not os.path.exists(source_file):
301 source_file = source_file[:-1]
304 def build_target_filename(self, module_name):
305 target = '%s.%s' % (module_name, self.language)
308 def copy_related_files(self, test_directory, target_directory, module_name):
309 is_related = re.compile('%s_.*[.].*' % module_name).match
310 for filename in os.listdir(test_directory):
311 if is_related(filename):
312 shutil.copy(os.path.join(test_directory, filename),
315 def find_source_files(self, workdir, module_name):
316 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
317 return [self.build_target_filename(module_name)] + [
318 filename for filename in os.listdir(workdir)
319 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
321 def split_source_and_output(self, test_directory, module, workdir):
322 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
323 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
325 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
327 for line in source_and_output:
329 if line.startswith("_ERRORS"):
335 source_and_output.close()
337 geterrors = out.geterrors
338 except AttributeError:
344 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
345 include_dirs = INCLUDE_DIRS[:]
347 include_dirs.append(incdir)
348 source = self.find_module_source_file(
349 os.path.join(test_directory, module + '.pyx'))
350 target = os.path.join(targetdir, self.build_target_filename(module))
351 options = CompilationOptions(
352 pyrex_default_options,
353 include_path = include_dirs,
354 output_file = target,
356 use_listing_file = False,
357 cplus = self.language == 'cpp',
358 language_level = self.language_level,
359 generate_pxi = False,
360 evaluate_tree_assertions = True,
362 cython_compile(source, options=options,
363 full_module_name=module)
365 def run_distutils(self, test_directory, module, workdir, incdir):
369 build_extension = build_ext(distutils_distro)
370 build_extension.include_dirs = INCLUDE_DIRS[:]
372 build_extension.include_dirs.append(incdir)
373 build_extension.finalize_options()
374 ext_include_dirs = []
375 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
377 ext_include_dirs += get_additional_include_dirs()
378 self.copy_related_files(test_directory, workdir, module)
379 extension = Extension(
381 sources = self.find_source_files(workdir, module),
382 include_dirs = ext_include_dirs,
383 extra_compile_args = CFLAGS,
385 if self.language == 'cpp':
386 extension.language = 'c++'
387 build_extension.extensions = [extension]
388 build_extension.build_temp = workdir
389 build_extension.build_lib = workdir
390 build_extension.run()
394 def compile(self, test_directory, module, workdir, incdir,
395 expect_errors, annotate):
396 expected_errors = errors = ()
398 expected_errors = self.split_source_and_output(
399 test_directory, module, workdir)
400 test_directory = workdir
403 old_stderr = sys.stderr
405 sys.stderr = ErrorWriter()
406 self.run_cython(test_directory, module, workdir, incdir, annotate)
407 errors = sys.stderr.geterrors()
409 sys.stderr = old_stderr
411 if errors or expected_errors:
413 for expected, error in zip(expected_errors, errors):
414 self.assertEquals(expected, error)
415 if len(errors) < len(expected_errors):
416 expected_error = expected_errors[len(errors)]
417 self.assertEquals(expected_error, None)
418 elif len(errors) > len(expected_errors):
419 unexpected_error = errors[len(expected_errors)]
420 self.assertEquals(None, unexpected_error)
421 except AssertionError:
422 print("\n=== Expected errors: ===")
423 print('\n'.join(expected_errors))
424 print("\n\n=== Got errors: ===")
425 print('\n'.join(errors))
429 if not self.cython_only:
430 self.run_distutils(test_directory, module, workdir, incdir)
432 class CythonRunTestCase(CythonCompileTestCase):
433 def shortDescription(self):
434 return "compiling (%s) and running %s" % (self.language, self.module)
436 def run(self, result=None):
438 result = self.defaultTestResult()
439 result.startTest(self)
443 self.runCompileTest()
444 if not self.cython_only:
445 self.run_doctests(self.module, result)
447 check_thread_termination()
449 result.addError(self, sys.exc_info())
450 result.stopTest(self)
456 def run_doctests(self, module_name, result):
457 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
458 doctest.DocTestSuite(module_name).run(result)
462 # fork to make sure we do not keep the tested module loaded
463 result_handle, result_file = tempfile.mkstemp()
464 os.close(result_handle)
472 partial_result = PartialTestResult(result)
473 tests = doctest.DocTestSuite(module_name)
474 tests.run(partial_result)
478 # importing failed, try to fake a test class
480 failureException=sys.exc_info()[1],
481 _shortDescription=self.shortDescription(),
483 partial_result.addError(tests, sys.exc_info())
485 output = open(result_file, 'wb')
486 pickle.dump(partial_result.data(), output)
488 traceback.print_exc()
492 os._exit(result_code)
495 cid, result_code = os.waitpid(child_id, 0)
496 # os.waitpid returns the child's result code in the
497 # upper byte of result_code, and the signal it was
498 # killed by in the lower byte
499 if result_code & 255:
500 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
501 (module_name, result_code & 255))
502 result_code = result_code >> 8
503 if result_code in (0,1):
504 input = open(result_file, 'rb')
506 PartialTestResult.join_results(result, pickle.load(input))
510 raise Exception("Tests in module '%s' exited with status %d" %
511 (module_name, result_code))
513 try: os.unlink(result_file)
516 class PureDoctestTestCase(unittest.TestCase):
517 def __init__(self, module_name, module_path):
518 self.module_name = module_name
519 self.module_path = module_path
520 unittest.TestCase.__init__(self, 'run')
522 def shortDescription(self):
523 return "running pure doctests in %s" % self.module_name
525 def run(self, result=None):
527 result = self.defaultTestResult()
528 loaded_module_name = 'pure_doctest__' + self.module_name
529 result.startTest(self)
534 m = imp.load_source(loaded_module_name, self.module_path)
536 doctest.DocTestSuite(m).run(result)
539 if loaded_module_name in sys.modules:
540 del sys.modules[loaded_module_name]
541 check_thread_termination()
543 result.addError(self, sys.exc_info())
544 result.stopTest(self)
550 is_private_field = re.compile('^_[^_]').match
552 class _FakeClass(object):
553 def __init__(self, **kwargs):
554 self._shortDescription = kwargs.get('module_name')
555 self.__dict__.update(kwargs)
556 def shortDescription(self):
557 return self._shortDescription
559 try: # Py2.7+ and Py3.2+
560 from unittest.runner import _TextTestResult
562 from unittest import _TextTestResult
564 class PartialTestResult(_TextTestResult):
565 def __init__(self, base_result):
566 _TextTestResult.__init__(
567 self, self._StringIO(), True,
568 base_result.dots + base_result.showAll*2)
570 def strip_error_results(self, results):
571 for test_case, error in results:
572 for attr_name in filter(is_private_field, dir(test_case)):
573 if attr_name == '_dt_test':
574 test_case._dt_test = _FakeClass(
575 name=test_case._dt_test.name)
576 elif attr_name != '_shortDescription':
577 setattr(test_case, attr_name, None)
580 self.strip_error_results(self.failures)
581 self.strip_error_results(self.errors)
582 return (self.failures, self.errors, self.testsRun,
583 self.stream.getvalue())
585 def join_results(result, data):
586 """Static method for merging the result back into the main
589 failures, errors, tests_run, output = data
591 result.stream.write(output)
592 result.errors.extend(errors)
593 result.failures.extend(failures)
594 result.testsRun += tests_run
596 join_results = staticmethod(join_results)
598 class _StringIO(StringIO):
599 def writeln(self, line):
600 self.write("%s\n" % line)
603 class CythonUnitTestCase(CythonCompileTestCase):
604 def shortDescription(self):
605 return "compiling (%s) tests in %s" % (self.language, self.module)
607 def run(self, result=None):
609 result = self.defaultTestResult()
610 result.startTest(self)
614 self.runCompileTest()
615 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
617 check_thread_termination()
619 result.addError(self, sys.exc_info())
620 result.stopTest(self)
626 def collect_unittests(path, module_prefix, suite, selectors):
627 def file_matches(filename):
628 return filename.startswith("Test") and filename.endswith(".py")
630 def package_matches(dirname):
631 return dirname == "Tests"
633 loader = unittest.TestLoader()
637 for dirpath, dirnames, filenames in os.walk(path):
638 if dirpath != path and "__init__.py" not in filenames:
639 skipped_dirs.append(dirpath + os.path.sep)
642 for dir in skipped_dirs:
643 if dirpath.startswith(dir):
647 parentname = os.path.split(dirpath)[-1]
648 if package_matches(parentname):
651 filepath = os.path.join(dirpath, f)[:-len(".py")]
652 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
653 if not [ 1 for match in selectors if match(modulename) ]:
655 module = __import__(modulename)
656 for x in modulename.split('.')[1:]:
657 module = getattr(module, x)
658 suite.addTests([loader.loadTestsFromModule(module)])
660 def collect_doctests(path, module_prefix, suite, selectors):
661 def package_matches(dirname):
662 return dirname not in ("Mac", "Distutils", "Plex")
663 def file_matches(filename):
664 return (filename.endswith(".py") and not ('~' in filename
665 or '#' in filename or filename.startswith('.')))
666 import doctest, types
667 for dirpath, dirnames, filenames in os.walk(path):
668 parentname = os.path.split(dirpath)[-1]
669 if package_matches(parentname):
672 if not f.endswith('.py'): continue
673 filepath = os.path.join(dirpath, f)
674 if os.path.getsize(filepath) == 0: continue
675 if 'no doctest' in open(filepath).next(): continue
676 filepath = filepath[:-len(".py")]
677 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
678 if not [ 1 for match in selectors if match(modulename) ]:
680 module = __import__(modulename)
681 for x in modulename.split('.')[1:]:
682 module = getattr(module, x)
683 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
685 suite.addTest(doctest.DocTestSuite(module))
686 except ValueError: # no tests
690 class EndToEndTest(unittest.TestCase):
692 This is a test of build/*.srctree files, where srctree defines a full
693 directory structure and its header gives a list of commands to run.
695 cython_root = os.path.dirname(os.path.abspath(__file__))
697 def __init__(self, treefile, workdir, cleanup_workdir=True):
698 self.treefile = treefile
699 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
700 self.cleanup_workdir = cleanup_workdir
701 cython_syspath = self.cython_root
702 for path in sys.path[::-1]:
703 if path.startswith(self.cython_root):
704 # Py3 installation and refnanny build prepend their
705 # fixed paths to sys.path => prefer that over the
707 cython_syspath = path + os.pathsep + cython_syspath
708 self.cython_syspath = cython_syspath
709 unittest.TestCase.__init__(self)
711 def shortDescription(self):
712 return "End-to-end %s" % self.treefile
715 from Cython.TestUtils import unpack_source_tree
716 _, self.commands = unpack_source_tree(os.path.join('tests', 'build', self.treefile), self.workdir)
717 self.old_dir = os.getcwd()
718 os.chdir(self.workdir)
719 if self.workdir not in sys.path:
720 sys.path.insert(0, self.workdir)
723 if self.cleanup_workdir:
724 shutil.rmtree(self.workdir)
725 os.chdir(self.old_dir)
728 commands = (self.commands
729 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
730 .replace("PYTHON", sys.executable))
731 old_path = os.environ.get('PYTHONPATH')
733 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + (old_path or '')
734 print(os.environ['PYTHONPATH'])
735 self.assertEqual(0, os.system(commands))
738 os.environ['PYTHONPATH'] = old_path
740 del os.environ['PYTHONPATH']
743 # TODO: Support cython_freeze needed here as well.
744 # TODO: Windows support.
746 class EmbedTest(unittest.TestCase):
748 working_dir = "Demos/embed"
751 self.old_dir = os.getcwd()
752 os.chdir(self.working_dir)
754 "make PYTHON='%s' clean > /dev/null" % sys.executable)
759 "make PYTHON='%s' clean > /dev/null" % sys.executable)
762 os.chdir(self.old_dir)
764 def test_embed(self):
765 from distutils import sysconfig
766 libname = sysconfig.get_config_var('LIBRARY')
767 libdir = sysconfig.get_config_var('LIBDIR')
768 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
769 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
770 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
771 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
772 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
773 # report the error for the original directory
774 libdir = sysconfig.get_config_var('LIBDIR')
775 self.assert_(os.system(
776 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
778 os.remove('make.output')
782 class MissingDependencyExcluder:
783 def __init__(self, deps):
784 # deps: { module name : matcher func }
785 self.exclude_matchers = []
786 for mod, matcher in deps.items():
790 self.exclude_matchers.append(matcher)
791 self.tests_missing_deps = []
792 def __call__(self, testname):
793 for matcher in self.exclude_matchers:
794 if matcher(testname):
795 self.tests_missing_deps.append(testname)
799 class VersionDependencyExcluder:
800 def __init__(self, deps):
801 # deps: { version : matcher func }
802 from sys import version_info
803 self.exclude_matchers = []
804 for ver, (compare, matcher) in deps.items():
805 if compare(version_info, ver):
806 self.exclude_matchers.append(matcher)
807 self.tests_missing_deps = []
808 def __call__(self, testname):
809 for matcher in self.exclude_matchers:
810 if matcher(testname):
811 self.tests_missing_deps.append(testname)
815 class FileListExcluder:
817 def __init__(self, list_file):
821 for line in f.readlines():
823 if line and line[0] != '#':
824 self.excludes[line.split()[0]] = True
828 def __call__(self, testname):
829 return testname in self.excludes or testname.split('.')[-1] in self.excludes
831 def refactor_for_py3(distdir, cy3_dir):
832 # need to convert Cython sources first
833 import lib2to3.refactor
834 from distutils.util import copydir_run_2to3
835 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
836 if fix.split('fix_')[-1] not in ('next',)
838 if not os.path.exists(cy3_dir):
840 import distutils.log as dlog
841 dlog.set_threshold(dlog.INFO)
842 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
846 recursive-exclude Cython *
847 recursive-include Cython *.py *.pyx *.pxd
849 sys.path.insert(0, cy3_dir)
851 class PendingThreadsError(RuntimeError):
856 def check_thread_termination(ignore_seen=True):
857 if threading is None: # no threading enabled in CPython
859 current = threading.currentThread()
860 blocking_threads = []
861 for t in threading.enumerate():
862 if not t.isAlive() or t == current:
867 blocking_threads.append(t)
869 for seen in threads_seen:
873 threads_seen.append(t)
874 blocking_threads.append(t)
875 if not blocking_threads:
877 sys.stderr.write("warning: left-over threads found after running test:\n")
878 for t in blocking_threads:
879 sys.stderr.write('...%s\n' % repr(t))
880 raise PendingThreadsError("left-over threads found after running test")
883 from optparse import OptionParser
884 parser = OptionParser()
885 parser.add_option("--no-cleanup", dest="cleanup_workdir",
886 action="store_false", default=True,
887 help="do not delete the generated C files (allows passing --no-cython on next run)")
888 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
889 action="store_false", default=True,
890 help="do not delete the generated shared libary files (allows manual module experimentation)")
891 parser.add_option("--no-cython", dest="with_cython",
892 action="store_false", default=True,
893 help="do not run the Cython compiler, only the C compiler")
894 parser.add_option("--no-c", dest="use_c",
895 action="store_false", default=True,
896 help="do not test C compilation")
897 parser.add_option("--no-cpp", dest="use_cpp",
898 action="store_false", default=True,
899 help="do not test C++ compilation")
900 parser.add_option("--no-unit", dest="unittests",
901 action="store_false", default=True,
902 help="do not run the unit tests")
903 parser.add_option("--no-doctest", dest="doctests",
904 action="store_false", default=True,
905 help="do not run the doctests")
906 parser.add_option("--no-file", dest="filetests",
907 action="store_false", default=True,
908 help="do not run the file based tests")
909 parser.add_option("--no-pyregr", dest="pyregr",
910 action="store_false", default=True,
911 help="do not run the regression tests of CPython in tests/pyregr/")
912 parser.add_option("--cython-only", dest="cython_only",
913 action="store_true", default=False,
914 help="only compile pyx to c, do not run C compiler or run the tests")
915 parser.add_option("--no-refnanny", dest="with_refnanny",
916 action="store_false", default=True,
917 help="do not regression test reference counting")
918 parser.add_option("--no-fork", dest="fork",
919 action="store_false", default=True,
920 help="do not fork to run tests")
921 parser.add_option("--sys-pyregr", dest="system_pyregr",
922 action="store_true", default=False,
923 help="run the regression tests of the CPython installation")
924 parser.add_option("-x", "--exclude", dest="exclude",
925 action="append", metavar="PATTERN",
926 help="exclude tests matching the PATTERN")
927 parser.add_option("-C", "--coverage", dest="coverage",
928 action="store_true", default=False,
929 help="collect source coverage data for the Compiler")
930 parser.add_option("--coverage-xml", dest="coverage_xml",
931 action="store_true", default=False,
932 help="collect source coverage data for the Compiler in XML format")
933 parser.add_option("-A", "--annotate", dest="annotate_source",
934 action="store_true", default=True,
935 help="generate annotated HTML versions of the test source files")
936 parser.add_option("--no-annotate", dest="annotate_source",
937 action="store_false",
938 help="do not generate annotated HTML versions of the test source files")
939 parser.add_option("-v", "--verbose", dest="verbosity",
940 action="count", default=0,
941 help="display test progress, pass twice to print test names")
942 parser.add_option("-T", "--ticket", dest="tickets",
944 help="a bug ticket number to run the respective test in 'tests/*'")
945 parser.add_option("-3", dest="language_level",
946 action="store_const", const=3, default=2,
947 help="set language level to Python 3 (useful for running the CPython regression tests)'")
948 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
949 help="write test results in XML to directory DIR")
950 parser.add_option("--exit-ok", dest="exit_ok", default=False,
952 help="exit without error code even on test failures")
954 options, cmd_args = parser.parse_args()
956 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
957 ROOTDIR = os.path.join(DISTDIR, 'tests')
958 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
960 if sys.version_info[0] >= 3:
961 options.doctests = False
962 if options.with_cython:
964 # try if Cython is installed in a Py3 version
965 import Cython.Compiler.Main
967 # back out anything the import process loaded, then
968 # 2to3 the Cython sources to make them re-importable
969 cy_modules = [ name for name in sys.modules
970 if name == 'Cython' or name.startswith('Cython.') ]
971 for name in cy_modules:
972 del sys.modules[name]
973 # hasn't been refactored yet - do it now
974 cy3_dir = os.path.join(WORKDIR, 'Cy3')
975 if sys.version_info >= (3,1):
976 refactor_for_py3(DISTDIR, cy3_dir)
977 elif os.path.isdir(cy3_dir):
978 sys.path.insert(0, cy3_dir)
980 options.with_cython = False
982 WITH_CYTHON = options.with_cython
984 if options.coverage or options.coverage_xml:
986 options.coverage = options.coverage_xml = False
988 from coverage import coverage as _coverage
989 coverage = _coverage(branch=True)
994 global CompilationOptions, pyrex_default_options, cython_compile
995 from Cython.Compiler.Main import \
996 CompilationOptions, \
997 default_options as pyrex_default_options, \
998 compile as cython_compile
999 from Cython.Compiler import Errors
1000 Errors.LEVEL = 0 # show all warnings
1001 from Cython.Compiler import Options
1002 Options.generate_cleanup_code = 3 # complete cleanup code
1003 from Cython.Compiler import DebugFlags
1004 DebugFlags.debug_temp_code_comments = 1
1007 UNITTEST_MODULE = "Cython"
1008 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1010 if os.path.exists(WORKDIR):
1011 for path in os.listdir(WORKDIR):
1012 if path in ("support", "Cy3"): continue
1013 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1014 if not os.path.exists(WORKDIR):
1015 os.makedirs(WORKDIR)
1017 sys.stderr.write("Python %s\n" % sys.version)
1018 sys.stderr.write("\n")
1020 from Cython.Compiler.Version import version
1021 sys.stderr.write("Running tests against Cython %s\n" % version)
1023 sys.stderr.write("Running tests without Cython.\n")
1025 if options.with_refnanny:
1026 from pyximport.pyxbuild import pyx_to_dll
1027 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1029 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1030 sys.path.insert(0, os.path.split(libpath)[0])
1031 CFLAGS.append("-DCYTHON_REFNANNY=1")
1033 if options.xml_output_dir and options.fork:
1034 # doesn't currently work together
1035 sys.stderr.write("Disabling forked testing to support XML test output\n")
1036 options.fork = False
1038 if WITH_CYTHON and options.language_level == 3:
1039 sys.stderr.write("Using Cython language level 3.\n")
1041 sys.stderr.write("\n")
1045 for ticket_number in options.tickets:
1047 cmd_args.append('.*T%s$' % ticket_number)
1049 for selector in cmd_args:
1050 if selector.startswith('bugs'):
1054 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1056 selectors = [ lambda x:True ]
1058 # Chech which external modules are not present and exclude tests
1059 # which depends on them (by prefix)
1061 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1062 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1063 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1066 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1069 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1071 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1072 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1076 languages.append('c')
1078 languages.append('cpp')
1080 test_suite = unittest.TestSuite()
1082 if options.unittests:
1083 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1085 if options.doctests:
1086 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1088 if options.filetests and languages:
1089 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1090 options.annotate_source, options.cleanup_workdir,
1091 options.cleanup_sharedlibs, options.pyregr,
1092 options.cython_only, languages, test_bugs,
1093 options.fork, options.language_level)
1094 test_suite.addTest(filetests.build_suite())
1096 if options.system_pyregr and languages:
1097 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1098 options.annotate_source, options.cleanup_workdir,
1099 options.cleanup_sharedlibs, True,
1100 options.cython_only, languages, test_bugs,
1101 options.fork, options.language_level)
1103 filetests.handle_directory(
1104 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1107 if options.xml_output_dir:
1108 from Cython.Tests.xmlrunner import XMLTestRunner
1109 test_runner = XMLTestRunner(output=options.xml_output_dir,
1110 verbose=options.verbosity > 0)
1112 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1114 result = test_runner.run(test_suite)
1116 if options.coverage or options.coverage_xml:
1118 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1119 modules = [ module for name, module in sys.modules.items()
1120 if module is not None and
1121 name.startswith('Cython.Compiler.') and
1122 name[len('Cython.Compiler.'):] not in ignored_modules ]
1123 if options.coverage:
1124 coverage.report(modules, show_missing=0)
1125 if options.coverage_xml:
1126 coverage.xml_report(modules, outfile="coverage-report.xml")
1128 if missing_dep_excluder.tests_missing_deps:
1129 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1130 for test in missing_dep_excluder.tests_missing_deps:
1131 sys.stderr.write(" %s\n" % test)
1133 if options.with_refnanny:
1135 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1142 return_code = not result.wasSuccessful()
1145 check_thread_termination(ignore_seen=False)
1146 sys.exit(return_code)
1147 except PendingThreadsError:
1148 # normal program exit won't kill the threads, do it the hard way here
1149 os._exit(return_code)
1151 if __name__ == '__main__':
1154 except SystemExit: # <= Py2.4 ...
1157 traceback.print_exc()
1159 check_thread_termination(ignore_seen=False)
1160 except PendingThreadsError:
1161 # normal program exit won't kill the threads, do it the hard way here