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,4) : (operator.lt, lambda x: x in ['run.builtin_sorted'
67 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
70 # The next line should start (3,); but this is a dictionary, so
71 # we can only have one (3,) key. Since 2.7 is supposed to be the
72 # last 2.x release, things would have to change drastically for this
74 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
75 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
76 'compile.extsetslice',
77 'compile.extdelslice',
78 'run.special_methods_T561_py2']),
81 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
82 CFLAGS = os.getenv('CFLAGS', '').split()
84 class build_ext(_build_ext):
85 def build_extension(self, ext):
86 if ext.language == 'c++':
88 try: # Py2.7+ & Py3.2+
89 compiler_obj = self.compiler_obj
90 except AttributeError:
91 compiler_obj = self.compiler
92 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
95 _build_ext.build_extension(self, ext)
97 class ErrorWriter(object):
98 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
101 self.write = self.output.append
103 def _collect(self, collect_errors, collect_warnings):
104 s = ''.join(self.output)
106 for line in s.split('\n'):
107 match = self.match_error(line)
109 is_warning, line, column, message = match.groups()
110 if (is_warning and collect_warnings) or \
111 (not is_warning and collect_errors):
112 result.append( (int(line), int(column), message.strip()) )
114 return [ "%d:%d: %s" % values for values in result ]
117 return self._collect(True, False)
119 def getwarnings(self):
120 return self._collect(False, True)
123 return self._collect(True, True)
125 class TestBuilder(object):
126 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
127 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
128 languages, test_bugs, fork, language_level):
129 self.rootdir = rootdir
130 self.workdir = workdir
131 self.selectors = selectors
132 self.exclude_selectors = exclude_selectors
133 self.annotate = annotate
134 self.cleanup_workdir = cleanup_workdir
135 self.cleanup_sharedlibs = cleanup_sharedlibs
136 self.with_pyregr = with_pyregr
137 self.cython_only = cython_only
138 self.languages = languages
139 self.test_bugs = test_bugs
141 self.language_level = language_level
143 def build_suite(self):
144 suite = unittest.TestSuite()
145 test_dirs = TEST_DIRS
146 filenames = os.listdir(self.rootdir)
148 for filename in filenames:
149 if not WITH_CYTHON and filename == "errors":
150 # we won't get any errors without running Cython
152 path = os.path.join(self.rootdir, filename)
153 if os.path.isdir(path) and filename in test_dirs:
154 if filename == 'pyregr' and not self.with_pyregr:
157 self.handle_directory(path, filename))
158 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
159 # Non-Windows makefile, can't run Cython under Py3.
160 if [1 for selector in self.selectors if selector("embedded")]:
161 suite.addTest(unittest.makeSuite(EmbedTest))
164 def handle_directory(self, path, context):
165 workdir = os.path.join(self.workdir, context)
166 if not os.path.exists(workdir):
169 expect_errors = (context == 'errors')
170 suite = unittest.TestSuite()
171 filenames = os.listdir(path)
173 for filename in filenames:
174 if context == "build" and filename.endswith(".srctree"):
175 if not [ 1 for match in self.selectors if match(filename) ]:
177 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
179 if not (filename.endswith(".pyx") or filename.endswith(".py")):
181 if filename.startswith('.'): continue # certain emacs backup files
182 if context == 'pyregr' and not filename.startswith('test_'):
184 module = os.path.splitext(filename)[0]
185 fqmodule = "%s.%s" % (context, module)
186 if not [ 1 for match in self.selectors
187 if match(fqmodule) ]:
189 if self.exclude_selectors:
190 if [1 for match in self.exclude_selectors if match(fqmodule)]:
192 if context in TEST_RUN_DIRS:
193 if module.startswith("test_"):
194 test_class = CythonUnitTestCase
196 test_class = CythonRunTestCase
198 test_class = CythonCompileTestCase
199 for test in self.build_tests(test_class, path, workdir,
200 module, expect_errors):
202 if context == 'run' and filename.endswith('.py'):
203 # additionally test file in real Python
204 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
207 def build_tests(self, test_class, path, workdir, module, expect_errors):
209 if 'cpp' in module and 'cpp' in self.languages:
212 languages = self.languages[:1]
214 languages = self.languages
215 if 'cpp' in module and 'c' in languages:
216 languages = list(languages)
217 languages.remove('c')
218 tests = [ self.build_test(test_class, path, workdir, module,
219 language, expect_errors)
220 for language in languages ]
223 def build_test(self, test_class, path, workdir, module,
224 language, expect_errors):
225 workdir = os.path.join(workdir, language)
226 if not os.path.exists(workdir):
228 return test_class(path, workdir, module,
230 expect_errors=expect_errors,
231 annotate=self.annotate,
232 cleanup_workdir=self.cleanup_workdir,
233 cleanup_sharedlibs=self.cleanup_sharedlibs,
234 cython_only=self.cython_only,
236 language_level=self.language_level)
238 class CythonCompileTestCase(unittest.TestCase):
239 def __init__(self, test_directory, workdir, module, language='c',
240 expect_errors=False, annotate=False, cleanup_workdir=True,
241 cleanup_sharedlibs=True, cython_only=False, fork=True,
243 self.test_directory = test_directory
244 self.workdir = workdir
246 self.language = language
247 self.expect_errors = expect_errors
248 self.annotate = annotate
249 self.cleanup_workdir = cleanup_workdir
250 self.cleanup_sharedlibs = cleanup_sharedlibs
251 self.cython_only = cython_only
253 self.language_level = language_level
254 unittest.TestCase.__init__(self)
256 def shortDescription(self):
257 return "compiling (%s) %s" % (self.language, self.module)
260 if self.workdir not in sys.path:
261 sys.path.insert(0, self.workdir)
265 sys.path.remove(self.workdir)
269 del sys.modules[self.module]
272 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
273 cleanup_lib_files = self.cleanup_sharedlibs
274 if os.path.exists(self.workdir):
275 for rmfile in os.listdir(self.workdir):
276 if not cleanup_c_files:
277 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
279 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
281 if self.annotate and rmfile.endswith(".html"):
284 rmfile = os.path.join(self.workdir, rmfile)
285 if os.path.isdir(rmfile):
286 shutil.rmtree(rmfile, ignore_errors=True)
292 os.makedirs(self.workdir)
295 self.runCompileTest()
297 def runCompileTest(self):
298 self.compile(self.test_directory, self.module, self.workdir,
299 self.test_directory, self.expect_errors, self.annotate)
301 def find_module_source_file(self, source_file):
302 if not os.path.exists(source_file):
303 source_file = source_file[:-1]
306 def build_target_filename(self, module_name):
307 target = '%s.%s' % (module_name, self.language)
310 def copy_related_files(self, test_directory, target_directory, module_name):
311 is_related = re.compile('%s_.*[.].*' % module_name).match
312 for filename in os.listdir(test_directory):
313 if is_related(filename):
314 shutil.copy(os.path.join(test_directory, filename),
317 def find_source_files(self, workdir, module_name):
318 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
319 return [self.build_target_filename(module_name)] + [
320 filename for filename in os.listdir(workdir)
321 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
323 def split_source_and_output(self, test_directory, module, workdir):
324 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
325 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
327 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
329 for line in source_and_output:
331 if line.startswith("_ERRORS"):
337 source_and_output.close()
339 geterrors = out.geterrors
340 except AttributeError:
346 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
347 include_dirs = INCLUDE_DIRS[:]
349 include_dirs.append(incdir)
350 source = self.find_module_source_file(
351 os.path.join(test_directory, module + '.pyx'))
352 target = os.path.join(targetdir, self.build_target_filename(module))
353 options = CompilationOptions(
354 pyrex_default_options,
355 include_path = include_dirs,
356 output_file = target,
358 use_listing_file = False,
359 cplus = self.language == 'cpp',
360 language_level = self.language_level,
361 generate_pxi = False,
362 evaluate_tree_assertions = True,
364 cython_compile(source, options=options,
365 full_module_name=module)
367 def run_distutils(self, test_directory, module, workdir, incdir):
371 build_extension = build_ext(distutils_distro)
372 build_extension.include_dirs = INCLUDE_DIRS[:]
374 build_extension.include_dirs.append(incdir)
375 build_extension.finalize_options()
376 ext_include_dirs = []
377 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
379 ext_include_dirs += get_additional_include_dirs()
380 self.copy_related_files(test_directory, workdir, module)
381 extension = Extension(
383 sources = self.find_source_files(workdir, module),
384 include_dirs = ext_include_dirs,
385 extra_compile_args = CFLAGS,
387 if self.language == 'cpp':
388 extension.language = 'c++'
389 build_extension.extensions = [extension]
390 build_extension.build_temp = workdir
391 build_extension.build_lib = workdir
392 build_extension.run()
396 def compile(self, test_directory, module, workdir, incdir,
397 expect_errors, annotate):
398 expected_errors = errors = ()
400 expected_errors = self.split_source_and_output(
401 test_directory, module, workdir)
402 test_directory = workdir
405 old_stderr = sys.stderr
407 sys.stderr = ErrorWriter()
408 self.run_cython(test_directory, module, workdir, incdir, annotate)
409 errors = sys.stderr.geterrors()
411 sys.stderr = old_stderr
413 if errors or expected_errors:
415 for expected, error in zip(expected_errors, errors):
416 self.assertEquals(expected, error)
417 if len(errors) < len(expected_errors):
418 expected_error = expected_errors[len(errors)]
419 self.assertEquals(expected_error, None)
420 elif len(errors) > len(expected_errors):
421 unexpected_error = errors[len(expected_errors)]
422 self.assertEquals(None, unexpected_error)
423 except AssertionError:
424 print("\n=== Expected errors: ===")
425 print('\n'.join(expected_errors))
426 print("\n\n=== Got errors: ===")
427 print('\n'.join(errors))
431 if not self.cython_only:
432 self.run_distutils(test_directory, module, workdir, incdir)
434 class CythonRunTestCase(CythonCompileTestCase):
435 def shortDescription(self):
436 return "compiling (%s) and running %s" % (self.language, self.module)
438 def run(self, result=None):
440 result = self.defaultTestResult()
441 result.startTest(self)
445 self.runCompileTest()
446 if not self.cython_only:
447 self.run_doctests(self.module, result)
449 check_thread_termination()
451 result.addError(self, sys.exc_info())
452 result.stopTest(self)
458 def run_doctests(self, module_name, result):
459 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
460 doctest.DocTestSuite(module_name).run(result)
464 # fork to make sure we do not keep the tested module loaded
465 result_handle, result_file = tempfile.mkstemp()
466 os.close(result_handle)
474 partial_result = PartialTestResult(result)
475 tests = doctest.DocTestSuite(module_name)
476 tests.run(partial_result)
480 # importing failed, try to fake a test class
482 failureException=sys.exc_info()[1],
483 _shortDescription=self.shortDescription(),
485 partial_result.addError(tests, sys.exc_info())
487 output = open(result_file, 'wb')
488 pickle.dump(partial_result.data(), output)
490 traceback.print_exc()
494 os._exit(result_code)
497 cid, result_code = os.waitpid(child_id, 0)
498 # os.waitpid returns the child's result code in the
499 # upper byte of result_code, and the signal it was
500 # killed by in the lower byte
501 if result_code & 255:
502 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
503 (module_name, result_code & 255))
504 result_code = result_code >> 8
505 if result_code in (0,1):
506 input = open(result_file, 'rb')
508 PartialTestResult.join_results(result, pickle.load(input))
512 raise Exception("Tests in module '%s' exited with status %d" %
513 (module_name, result_code))
515 try: os.unlink(result_file)
518 class PureDoctestTestCase(unittest.TestCase):
519 def __init__(self, module_name, module_path):
520 self.module_name = module_name
521 self.module_path = module_path
522 unittest.TestCase.__init__(self, 'run')
524 def shortDescription(self):
525 return "running pure doctests in %s" % self.module_name
527 def run(self, result=None):
529 result = self.defaultTestResult()
530 loaded_module_name = 'pure_doctest__' + self.module_name
531 result.startTest(self)
536 m = imp.load_source(loaded_module_name, self.module_path)
538 doctest.DocTestSuite(m).run(result)
541 if loaded_module_name in sys.modules:
542 del sys.modules[loaded_module_name]
543 check_thread_termination()
545 result.addError(self, sys.exc_info())
546 result.stopTest(self)
552 is_private_field = re.compile('^_[^_]').match
554 class _FakeClass(object):
555 def __init__(self, **kwargs):
556 self._shortDescription = kwargs.get('module_name')
557 self.__dict__.update(kwargs)
558 def shortDescription(self):
559 return self._shortDescription
561 try: # Py2.7+ and Py3.2+
562 from unittest.runner import _TextTestResult
564 from unittest import _TextTestResult
566 class PartialTestResult(_TextTestResult):
567 def __init__(self, base_result):
568 _TextTestResult.__init__(
569 self, self._StringIO(), True,
570 base_result.dots + base_result.showAll*2)
572 def strip_error_results(self, results):
573 for test_case, error in results:
574 for attr_name in filter(is_private_field, dir(test_case)):
575 if attr_name == '_dt_test':
576 test_case._dt_test = _FakeClass(
577 name=test_case._dt_test.name)
578 elif attr_name != '_shortDescription':
579 setattr(test_case, attr_name, None)
582 self.strip_error_results(self.failures)
583 self.strip_error_results(self.errors)
584 return (self.failures, self.errors, self.testsRun,
585 self.stream.getvalue())
587 def join_results(result, data):
588 """Static method for merging the result back into the main
591 failures, errors, tests_run, output = data
593 result.stream.write(output)
594 result.errors.extend(errors)
595 result.failures.extend(failures)
596 result.testsRun += tests_run
598 join_results = staticmethod(join_results)
600 class _StringIO(StringIO):
601 def writeln(self, line):
602 self.write("%s\n" % line)
605 class CythonUnitTestCase(CythonCompileTestCase):
606 def shortDescription(self):
607 return "compiling (%s) tests in %s" % (self.language, self.module)
609 def run(self, result=None):
611 result = self.defaultTestResult()
612 result.startTest(self)
616 self.runCompileTest()
617 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
619 check_thread_termination()
621 result.addError(self, sys.exc_info())
622 result.stopTest(self)
628 def collect_unittests(path, module_prefix, suite, selectors):
629 def file_matches(filename):
630 return filename.startswith("Test") and filename.endswith(".py")
632 def package_matches(dirname):
633 return dirname == "Tests"
635 loader = unittest.TestLoader()
639 for dirpath, dirnames, filenames in os.walk(path):
640 if dirpath != path and "__init__.py" not in filenames:
641 skipped_dirs.append(dirpath + os.path.sep)
644 for dir in skipped_dirs:
645 if dirpath.startswith(dir):
649 parentname = os.path.split(dirpath)[-1]
650 if package_matches(parentname):
653 filepath = os.path.join(dirpath, f)[:-len(".py")]
654 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
655 if not [ 1 for match in selectors if match(modulename) ]:
657 module = __import__(modulename)
658 for x in modulename.split('.')[1:]:
659 module = getattr(module, x)
660 suite.addTests([loader.loadTestsFromModule(module)])
662 def collect_doctests(path, module_prefix, suite, selectors):
663 def package_matches(dirname):
664 return dirname not in ("Mac", "Distutils", "Plex")
665 def file_matches(filename):
666 return (filename.endswith(".py") and not ('~' in filename
667 or '#' in filename or filename.startswith('.')))
668 import doctest, types
669 for dirpath, dirnames, filenames in os.walk(path):
670 parentname = os.path.split(dirpath)[-1]
671 if package_matches(parentname):
674 if not f.endswith('.py'): continue
675 filepath = os.path.join(dirpath, f)
676 if os.path.getsize(filepath) == 0: continue
677 if 'no doctest' in open(filepath).next(): continue
678 filepath = filepath[:-len(".py")]
679 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
680 if not [ 1 for match in selectors if match(modulename) ]:
682 module = __import__(modulename)
683 for x in modulename.split('.')[1:]:
684 module = getattr(module, x)
685 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
687 suite.addTest(doctest.DocTestSuite(module))
688 except ValueError: # no tests
692 class EndToEndTest(unittest.TestCase):
694 This is a test of build/*.srctree files, where srctree defines a full
695 directory structure and its header gives a list of commands to run.
697 cython_root = os.path.dirname(os.path.abspath(__file__))
699 def __init__(self, treefile, workdir, cleanup_workdir=True):
700 self.treefile = treefile
701 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
702 self.cleanup_workdir = cleanup_workdir
703 cython_syspath = self.cython_root
704 for path in sys.path[::-1]:
705 if path.startswith(self.cython_root):
706 # Py3 installation and refnanny build prepend their
707 # fixed paths to sys.path => prefer that over the
709 cython_syspath = path + os.pathsep + cython_syspath
710 self.cython_syspath = cython_syspath
711 unittest.TestCase.__init__(self)
713 def shortDescription(self):
714 return "End-to-end %s" % self.treefile
717 from Cython.TestUtils import unpack_source_tree
718 _, self.commands = unpack_source_tree(os.path.join('tests', 'build', self.treefile), self.workdir)
719 self.old_dir = os.getcwd()
720 os.chdir(self.workdir)
721 if self.workdir not in sys.path:
722 sys.path.insert(0, self.workdir)
725 if self.cleanup_workdir:
726 shutil.rmtree(self.workdir)
727 os.chdir(self.old_dir)
730 commands = (self.commands
731 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
732 .replace("PYTHON", sys.executable))
733 old_path = os.environ.get('PYTHONPATH')
735 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + (old_path or '')
736 print(os.environ['PYTHONPATH'])
737 self.assertEqual(0, os.system(commands))
740 os.environ['PYTHONPATH'] = old_path
742 del os.environ['PYTHONPATH']
745 # TODO: Support cython_freeze needed here as well.
746 # TODO: Windows support.
748 class EmbedTest(unittest.TestCase):
750 working_dir = "Demos/embed"
753 self.old_dir = os.getcwd()
754 os.chdir(self.working_dir)
756 "make PYTHON='%s' clean > /dev/null" % sys.executable)
761 "make PYTHON='%s' clean > /dev/null" % sys.executable)
764 os.chdir(self.old_dir)
766 def test_embed(self):
767 from distutils import sysconfig
768 libname = sysconfig.get_config_var('LIBRARY')
769 libdir = sysconfig.get_config_var('LIBDIR')
770 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
771 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
772 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
773 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
774 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
775 # report the error for the original directory
776 libdir = sysconfig.get_config_var('LIBDIR')
777 self.assert_(os.system(
778 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
780 os.remove('make.output')
784 class MissingDependencyExcluder:
785 def __init__(self, deps):
786 # deps: { module name : matcher func }
787 self.exclude_matchers = []
788 for mod, matcher in deps.items():
792 self.exclude_matchers.append(matcher)
793 self.tests_missing_deps = []
794 def __call__(self, testname):
795 for matcher in self.exclude_matchers:
796 if matcher(testname):
797 self.tests_missing_deps.append(testname)
801 class VersionDependencyExcluder:
802 def __init__(self, deps):
803 # deps: { version : matcher func }
804 from sys import version_info
805 self.exclude_matchers = []
806 for ver, (compare, matcher) in deps.items():
807 if compare(version_info, ver):
808 self.exclude_matchers.append(matcher)
809 self.tests_missing_deps = []
810 def __call__(self, testname):
811 for matcher in self.exclude_matchers:
812 if matcher(testname):
813 self.tests_missing_deps.append(testname)
817 class FileListExcluder:
819 def __init__(self, list_file):
823 for line in f.readlines():
825 if line and line[0] != '#':
826 self.excludes[line.split()[0]] = True
830 def __call__(self, testname):
831 return testname in self.excludes or testname.split('.')[-1] in self.excludes
833 def refactor_for_py3(distdir, cy3_dir):
834 # need to convert Cython sources first
835 import lib2to3.refactor
836 from distutils.util import copydir_run_2to3
837 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
838 if fix.split('fix_')[-1] not in ('next',)
840 if not os.path.exists(cy3_dir):
842 import distutils.log as dlog
843 dlog.set_threshold(dlog.INFO)
844 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
848 recursive-exclude Cython *
849 recursive-include Cython *.py *.pyx *.pxd
851 sys.path.insert(0, cy3_dir)
853 class PendingThreadsError(RuntimeError):
858 def check_thread_termination(ignore_seen=True):
859 if threading is None: # no threading enabled in CPython
861 current = threading.currentThread()
862 blocking_threads = []
863 for t in threading.enumerate():
864 if not t.isAlive() or t == current:
869 blocking_threads.append(t)
871 for seen in threads_seen:
875 threads_seen.append(t)
876 blocking_threads.append(t)
877 if not blocking_threads:
879 sys.stderr.write("warning: left-over threads found after running test:\n")
880 for t in blocking_threads:
881 sys.stderr.write('...%s\n' % repr(t))
882 raise PendingThreadsError("left-over threads found after running test")
885 from optparse import OptionParser
886 parser = OptionParser()
887 parser.add_option("--no-cleanup", dest="cleanup_workdir",
888 action="store_false", default=True,
889 help="do not delete the generated C files (allows passing --no-cython on next run)")
890 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
891 action="store_false", default=True,
892 help="do not delete the generated shared libary files (allows manual module experimentation)")
893 parser.add_option("--no-cython", dest="with_cython",
894 action="store_false", default=True,
895 help="do not run the Cython compiler, only the C compiler")
896 parser.add_option("--no-c", dest="use_c",
897 action="store_false", default=True,
898 help="do not test C compilation")
899 parser.add_option("--no-cpp", dest="use_cpp",
900 action="store_false", default=True,
901 help="do not test C++ compilation")
902 parser.add_option("--no-unit", dest="unittests",
903 action="store_false", default=True,
904 help="do not run the unit tests")
905 parser.add_option("--no-doctest", dest="doctests",
906 action="store_false", default=True,
907 help="do not run the doctests")
908 parser.add_option("--no-file", dest="filetests",
909 action="store_false", default=True,
910 help="do not run the file based tests")
911 parser.add_option("--no-pyregr", dest="pyregr",
912 action="store_false", default=True,
913 help="do not run the regression tests of CPython in tests/pyregr/")
914 parser.add_option("--cython-only", dest="cython_only",
915 action="store_true", default=False,
916 help="only compile pyx to c, do not run C compiler or run the tests")
917 parser.add_option("--no-refnanny", dest="with_refnanny",
918 action="store_false", default=True,
919 help="do not regression test reference counting")
920 parser.add_option("--no-fork", dest="fork",
921 action="store_false", default=True,
922 help="do not fork to run tests")
923 parser.add_option("--sys-pyregr", dest="system_pyregr",
924 action="store_true", default=False,
925 help="run the regression tests of the CPython installation")
926 parser.add_option("-x", "--exclude", dest="exclude",
927 action="append", metavar="PATTERN",
928 help="exclude tests matching the PATTERN")
929 parser.add_option("-C", "--coverage", dest="coverage",
930 action="store_true", default=False,
931 help="collect source coverage data for the Compiler")
932 parser.add_option("--coverage-xml", dest="coverage_xml",
933 action="store_true", default=False,
934 help="collect source coverage data for the Compiler in XML format")
935 parser.add_option("-A", "--annotate", dest="annotate_source",
936 action="store_true", default=True,
937 help="generate annotated HTML versions of the test source files")
938 parser.add_option("--no-annotate", dest="annotate_source",
939 action="store_false",
940 help="do not generate annotated HTML versions of the test source files")
941 parser.add_option("-v", "--verbose", dest="verbosity",
942 action="count", default=0,
943 help="display test progress, pass twice to print test names")
944 parser.add_option("-T", "--ticket", dest="tickets",
946 help="a bug ticket number to run the respective test in 'tests/*'")
947 parser.add_option("-3", dest="language_level",
948 action="store_const", const=3, default=2,
949 help="set language level to Python 3 (useful for running the CPython regression tests)'")
950 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
951 help="write test results in XML to directory DIR")
952 parser.add_option("--exit-ok", dest="exit_ok", default=False,
954 help="exit without error code even on test failures")
956 options, cmd_args = parser.parse_args()
958 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
959 ROOTDIR = os.path.join(DISTDIR, 'tests')
960 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
962 if sys.version_info[0] >= 3:
963 options.doctests = False
964 if options.with_cython:
966 # try if Cython is installed in a Py3 version
967 import Cython.Compiler.Main
969 # back out anything the import process loaded, then
970 # 2to3 the Cython sources to make them re-importable
971 cy_modules = [ name for name in sys.modules
972 if name == 'Cython' or name.startswith('Cython.') ]
973 for name in cy_modules:
974 del sys.modules[name]
975 # hasn't been refactored yet - do it now
976 cy3_dir = os.path.join(WORKDIR, 'Cy3')
977 if sys.version_info >= (3,1):
978 refactor_for_py3(DISTDIR, cy3_dir)
979 elif os.path.isdir(cy3_dir):
980 sys.path.insert(0, cy3_dir)
982 options.with_cython = False
984 WITH_CYTHON = options.with_cython
986 if options.coverage or options.coverage_xml:
988 options.coverage = options.coverage_xml = False
990 from coverage import coverage as _coverage
991 coverage = _coverage(branch=True)
996 global CompilationOptions, pyrex_default_options, cython_compile
997 from Cython.Compiler.Main import \
998 CompilationOptions, \
999 default_options as pyrex_default_options, \
1000 compile as cython_compile
1001 from Cython.Compiler import Errors
1002 Errors.LEVEL = 0 # show all warnings
1003 from Cython.Compiler import Options
1004 Options.generate_cleanup_code = 3 # complete cleanup code
1005 from Cython.Compiler import DebugFlags
1006 DebugFlags.debug_temp_code_comments = 1
1009 UNITTEST_MODULE = "Cython"
1010 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1012 if os.path.exists(WORKDIR):
1013 for path in os.listdir(WORKDIR):
1014 if path in ("support", "Cy3"): continue
1015 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1016 if not os.path.exists(WORKDIR):
1017 os.makedirs(WORKDIR)
1019 sys.stderr.write("Python %s\n" % sys.version)
1020 sys.stderr.write("\n")
1022 from Cython.Compiler.Version import version
1023 sys.stderr.write("Running tests against Cython %s\n" % version)
1025 sys.stderr.write("Running tests without Cython.\n")
1027 if options.with_refnanny:
1028 from pyximport.pyxbuild import pyx_to_dll
1029 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1031 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1032 sys.path.insert(0, os.path.split(libpath)[0])
1033 CFLAGS.append("-DCYTHON_REFNANNY=1")
1035 if options.xml_output_dir and options.fork:
1036 # doesn't currently work together
1037 sys.stderr.write("Disabling forked testing to support XML test output\n")
1038 options.fork = False
1040 if WITH_CYTHON and options.language_level == 3:
1041 sys.stderr.write("Using Cython language level 3.\n")
1043 sys.stderr.write("\n")
1047 for ticket_number in options.tickets:
1049 cmd_args.append('.*T%s$' % ticket_number)
1051 for selector in cmd_args:
1052 if selector.startswith('bugs'):
1056 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1058 selectors = [ lambda x:True ]
1060 # Chech which external modules are not present and exclude tests
1061 # which depends on them (by prefix)
1063 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1064 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1065 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1068 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1071 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1073 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1074 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1078 languages.append('c')
1080 languages.append('cpp')
1082 test_suite = unittest.TestSuite()
1084 if options.unittests:
1085 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1087 if options.doctests:
1088 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1090 if options.filetests and languages:
1091 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1092 options.annotate_source, options.cleanup_workdir,
1093 options.cleanup_sharedlibs, options.pyregr,
1094 options.cython_only, languages, test_bugs,
1095 options.fork, options.language_level)
1096 test_suite.addTest(filetests.build_suite())
1098 if options.system_pyregr and languages:
1099 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1100 options.annotate_source, options.cleanup_workdir,
1101 options.cleanup_sharedlibs, True,
1102 options.cython_only, languages, test_bugs,
1103 options.fork, options.language_level)
1105 filetests.handle_directory(
1106 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1109 if options.xml_output_dir:
1110 from Cython.Tests.xmlrunner import XMLTestRunner
1111 test_runner = XMLTestRunner(output=options.xml_output_dir,
1112 verbose=options.verbosity > 0)
1114 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1116 result = test_runner.run(test_suite)
1118 if options.coverage or options.coverage_xml:
1120 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1121 modules = [ module for name, module in sys.modules.items()
1122 if module is not None and
1123 name.startswith('Cython.Compiler.') and
1124 name[len('Cython.Compiler.'):] not in ignored_modules ]
1125 if options.coverage:
1126 coverage.report(modules, show_missing=0)
1127 if options.coverage_xml:
1128 coverage.xml_report(modules, outfile="coverage-report.xml")
1130 if missing_dep_excluder.tests_missing_deps:
1131 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1132 for test in missing_dep_excluder.tests_missing_deps:
1133 sys.stderr.write(" %s\n" % test)
1135 if options.with_refnanny:
1137 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1144 return_code = not result.wasSuccessful()
1147 check_thread_termination(ignore_seen=False)
1148 sys.exit(return_code)
1149 except PendingThreadsError:
1150 # normal program exit won't kill the threads, do it the hard way here
1151 os._exit(return_code)
1153 if __name__ == '__main__':
1156 except SystemExit: # <= Py2.4 ...
1159 traceback.print_exc()
1161 check_thread_termination(ignore_seen=False)
1162 except PendingThreadsError:
1163 # normal program exit won't kill the threads, do it the hard way here