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.lt, ...) excludes ... when PyVer < 2.4.x
60 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
63 (2,5) : (operator.lt, lambda x: x in ['run.any',
66 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
68 'run.pure_py', # decorators, with statement
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 extra_compile_options=None):
348 include_dirs = INCLUDE_DIRS[:]
350 include_dirs.append(incdir)
351 source = self.find_module_source_file(
352 os.path.join(test_directory, module + '.pyx'))
353 target = os.path.join(targetdir, self.build_target_filename(module))
355 if extra_compile_options is None:
356 extra_compile_options = {}
361 from Cython.Compiler.Main import CompilationOptions
362 from Cython.Compiler.Main import compile as cython_compile
363 from Cython.Compiler.Main import default_options
365 options = CompilationOptions(
367 include_path = include_dirs,
368 output_file = target,
370 use_listing_file = False,
371 cplus = self.language == 'cpp',
372 language_level = self.language_level,
373 generate_pxi = False,
374 evaluate_tree_assertions = True,
375 **extra_compile_options
377 cython_compile(source, options=options,
378 full_module_name=module)
380 def run_distutils(self, test_directory, module, workdir, incdir,
381 extra_extension_args=None):
385 build_extension = build_ext(distutils_distro)
386 build_extension.include_dirs = INCLUDE_DIRS[:]
388 build_extension.include_dirs.append(incdir)
389 build_extension.finalize_options()
390 ext_include_dirs = []
391 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
393 ext_include_dirs += get_additional_include_dirs()
394 self.copy_related_files(test_directory, workdir, module)
396 if extra_extension_args is None:
397 extra_extension_args = {}
399 extension = Extension(
401 sources = self.find_source_files(workdir, module),
402 include_dirs = ext_include_dirs,
403 extra_compile_args = CFLAGS,
404 **extra_extension_args
406 if self.language == 'cpp':
407 extension.language = 'c++'
408 build_extension.extensions = [extension]
409 build_extension.build_temp = workdir
410 build_extension.build_lib = workdir
411 build_extension.run()
415 def compile(self, test_directory, module, workdir, incdir,
416 expect_errors, annotate):
417 expected_errors = errors = ()
419 expected_errors = self.split_source_and_output(
420 test_directory, module, workdir)
421 test_directory = workdir
424 old_stderr = sys.stderr
426 sys.stderr = ErrorWriter()
427 self.run_cython(test_directory, module, workdir, incdir, annotate)
428 errors = sys.stderr.geterrors()
430 sys.stderr = old_stderr
432 if errors or expected_errors:
434 for expected, error in zip(expected_errors, errors):
435 self.assertEquals(expected, error)
436 if len(errors) < len(expected_errors):
437 expected_error = expected_errors[len(errors)]
438 self.assertEquals(expected_error, None)
439 elif len(errors) > len(expected_errors):
440 unexpected_error = errors[len(expected_errors)]
441 self.assertEquals(None, unexpected_error)
442 except AssertionError:
443 print("\n=== Expected errors: ===")
444 print('\n'.join(expected_errors))
445 print("\n\n=== Got errors: ===")
446 print('\n'.join(errors))
450 if not self.cython_only:
451 self.run_distutils(test_directory, module, workdir, incdir)
453 class CythonRunTestCase(CythonCompileTestCase):
454 def shortDescription(self):
455 return "compiling (%s) and running %s" % (self.language, self.module)
457 def run(self, result=None):
459 result = self.defaultTestResult()
460 result.startTest(self)
464 self.runCompileTest()
465 if not self.cython_only:
466 self.run_doctests(self.module, result)
468 check_thread_termination()
470 result.addError(self, sys.exc_info())
471 result.stopTest(self)
477 def run_doctests(self, module_name, result):
478 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
479 doctest.DocTestSuite(module_name).run(result)
483 # fork to make sure we do not keep the tested module loaded
484 result_handle, result_file = tempfile.mkstemp()
485 os.close(result_handle)
493 partial_result = PartialTestResult(result)
494 tests = doctest.DocTestSuite(module_name)
495 tests.run(partial_result)
499 # importing failed, try to fake a test class
501 failureException=sys.exc_info()[1],
502 _shortDescription=self.shortDescription(),
504 partial_result.addError(tests, sys.exc_info())
506 output = open(result_file, 'wb')
507 pickle.dump(partial_result.data(), output)
509 traceback.print_exc()
513 os._exit(result_code)
516 cid, result_code = os.waitpid(child_id, 0)
517 # os.waitpid returns the child's result code in the
518 # upper byte of result_code, and the signal it was
519 # killed by in the lower byte
520 if result_code & 255:
521 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
522 (module_name, result_code & 255))
523 result_code = result_code >> 8
524 if result_code in (0,1):
525 input = open(result_file, 'rb')
527 PartialTestResult.join_results(result, pickle.load(input))
531 raise Exception("Tests in module '%s' exited with status %d" %
532 (module_name, result_code))
534 try: os.unlink(result_file)
537 class PureDoctestTestCase(unittest.TestCase):
538 def __init__(self, module_name, module_path):
539 self.module_name = module_name
540 self.module_path = module_path
541 unittest.TestCase.__init__(self, 'run')
543 def shortDescription(self):
544 return "running pure doctests in %s" % self.module_name
546 def run(self, result=None):
548 result = self.defaultTestResult()
549 loaded_module_name = 'pure_doctest__' + self.module_name
550 result.startTest(self)
555 m = imp.load_source(loaded_module_name, self.module_path)
557 doctest.DocTestSuite(m).run(result)
560 if loaded_module_name in sys.modules:
561 del sys.modules[loaded_module_name]
562 check_thread_termination()
564 result.addError(self, sys.exc_info())
565 result.stopTest(self)
571 is_private_field = re.compile('^_[^_]').match
573 class _FakeClass(object):
574 def __init__(self, **kwargs):
575 self._shortDescription = kwargs.get('module_name')
576 self.__dict__.update(kwargs)
577 def shortDescription(self):
578 return self._shortDescription
580 try: # Py2.7+ and Py3.2+
581 from unittest.runner import _TextTestResult
583 from unittest import _TextTestResult
585 class PartialTestResult(_TextTestResult):
586 def __init__(self, base_result):
587 _TextTestResult.__init__(
588 self, self._StringIO(), True,
589 base_result.dots + base_result.showAll*2)
591 def strip_error_results(self, results):
592 for test_case, error in results:
593 for attr_name in filter(is_private_field, dir(test_case)):
594 if attr_name == '_dt_test':
595 test_case._dt_test = _FakeClass(
596 name=test_case._dt_test.name)
597 elif attr_name != '_shortDescription':
598 setattr(test_case, attr_name, None)
601 self.strip_error_results(self.failures)
602 self.strip_error_results(self.errors)
603 return (self.failures, self.errors, self.testsRun,
604 self.stream.getvalue())
606 def join_results(result, data):
607 """Static method for merging the result back into the main
610 failures, errors, tests_run, output = data
612 result.stream.write(output)
613 result.errors.extend(errors)
614 result.failures.extend(failures)
615 result.testsRun += tests_run
617 join_results = staticmethod(join_results)
619 class _StringIO(StringIO):
620 def writeln(self, line):
621 self.write("%s\n" % line)
624 class CythonUnitTestCase(CythonCompileTestCase):
625 def shortDescription(self):
626 return "compiling (%s) tests in %s" % (self.language, self.module)
628 def run(self, result=None):
630 result = self.defaultTestResult()
631 result.startTest(self)
635 self.runCompileTest()
636 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
638 check_thread_termination()
640 result.addError(self, sys.exc_info())
641 result.stopTest(self)
647 include_debugger = sys.version_info[:2] > (2, 4)
649 def collect_unittests(path, module_prefix, suite, selectors):
650 def file_matches(filename):
651 return filename.startswith("Test") and filename.endswith(".py")
653 def package_matches(dirname):
654 return dirname == "Tests"
656 loader = unittest.TestLoader()
661 cython_dir = os.path.dirname(os.path.abspath(__file__))
662 skipped_dirs = [os.path.join(cython_dir, 'Cython', 'Debugger')]
664 for dirpath, dirnames, filenames in os.walk(path):
665 if dirpath != path and "__init__.py" not in filenames:
666 skipped_dirs.append(dirpath + os.path.sep)
669 for dir in skipped_dirs:
670 if dirpath.startswith(dir):
674 parentname = os.path.split(dirpath)[-1]
675 if package_matches(parentname):
678 filepath = os.path.join(dirpath, f)[:-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 suite.addTests([loader.loadTestsFromModule(module)])
689 def collect_doctests(path, module_prefix, suite, selectors):
690 def package_matches(dirname):
691 if dirname == 'Debugger' and not include_debugger:
693 return dirname not in ("Mac", "Distutils", "Plex")
694 def file_matches(filename):
695 filename, ext = os.path.splitext(filename)
696 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
698 return (ext == '.py' and not
699 '~' in filename and not
700 '#' in filename and not
701 filename.startswith('.') and not
702 filename in blacklist)
703 import doctest, types
704 for dirpath, dirnames, filenames in os.walk(path):
705 parentname = os.path.split(dirpath)[-1]
706 if package_matches(parentname):
709 if not f.endswith('.py'): continue
710 filepath = os.path.join(dirpath, f)
711 if os.path.getsize(filepath) == 0: continue
712 if 'no doctest' in open(filepath).next(): continue
713 filepath = filepath[:-len(".py")]
714 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
715 if not [ 1 for match in selectors if match(modulename) ]:
717 module = __import__(modulename)
718 for x in modulename.split('.')[1:]:
719 module = getattr(module, x)
720 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
722 suite.addTest(doctest.DocTestSuite(module))
723 except ValueError: # no tests
727 class EndToEndTest(unittest.TestCase):
729 This is a test of build/*.srctree files, where srctree defines a full
730 directory structure and its header gives a list of commands to run.
732 cython_root = os.path.dirname(os.path.abspath(__file__))
734 def __init__(self, treefile, workdir, cleanup_workdir=True):
735 self.treefile = treefile
736 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
737 self.cleanup_workdir = cleanup_workdir
738 cython_syspath = self.cython_root
739 for path in sys.path[::-1]:
740 if path.startswith(self.cython_root):
741 # Py3 installation and refnanny build prepend their
742 # fixed paths to sys.path => prefer that over the
744 cython_syspath = path + os.pathsep + cython_syspath
745 self.cython_syspath = cython_syspath
746 unittest.TestCase.__init__(self)
748 def shortDescription(self):
749 return "End-to-end %s" % self.treefile
752 from Cython.TestUtils import unpack_source_tree
753 _, self.commands = unpack_source_tree(
754 os.path.join('tests', 'build', self.treefile), self.workdir)
755 self.old_dir = os.getcwd()
756 os.chdir(self.workdir)
757 if self.workdir not in sys.path:
758 sys.path.insert(0, self.workdir)
761 if self.cleanup_workdir:
762 shutil.rmtree(self.workdir)
763 os.chdir(self.old_dir)
766 commands = (self.commands
767 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
768 .replace("PYTHON", sys.executable))
770 old_path = os.environ.get('PYTHONPATH')
771 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
772 for command in commands.split('\n'):
773 if sys.version_info[:2] >= (2,4):
775 p = subprocess.Popen(commands,
776 stderr=subprocess.PIPE,
777 stdout=subprocess.PIPE,
779 out, err = p.communicate()
786 res = os.system(command)
787 self.assertEqual(0, res, "non-zero exit status")
790 os.environ['PYTHONPATH'] = old_path
792 del os.environ['PYTHONPATH']
795 # TODO: Support cython_freeze needed here as well.
796 # TODO: Windows support.
798 class EmbedTest(unittest.TestCase):
800 working_dir = "Demos/embed"
803 self.old_dir = os.getcwd()
804 os.chdir(self.working_dir)
806 "make PYTHON='%s' clean > /dev/null" % sys.executable)
811 "make PYTHON='%s' clean > /dev/null" % sys.executable)
814 os.chdir(self.old_dir)
816 def test_embed(self):
817 from distutils import sysconfig
818 libname = sysconfig.get_config_var('LIBRARY')
819 libdir = sysconfig.get_config_var('LIBDIR')
820 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
821 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
822 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
823 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
824 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
825 # report the error for the original directory
826 libdir = sysconfig.get_config_var('LIBDIR')
827 self.assert_(os.system(
828 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
830 os.remove('make.output')
834 class MissingDependencyExcluder:
835 def __init__(self, deps):
836 # deps: { module name : matcher func }
837 self.exclude_matchers = []
838 for mod, matcher in deps.items():
842 self.exclude_matchers.append(matcher)
843 self.tests_missing_deps = []
844 def __call__(self, testname):
845 for matcher in self.exclude_matchers:
846 if matcher(testname):
847 self.tests_missing_deps.append(testname)
851 class VersionDependencyExcluder:
852 def __init__(self, deps):
853 # deps: { version : matcher func }
854 from sys import version_info
855 self.exclude_matchers = []
856 for ver, (compare, matcher) in deps.items():
857 if compare(version_info, ver):
858 self.exclude_matchers.append(matcher)
859 self.tests_missing_deps = []
860 def __call__(self, testname):
861 for matcher in self.exclude_matchers:
862 if matcher(testname):
863 self.tests_missing_deps.append(testname)
867 class FileListExcluder:
869 def __init__(self, list_file):
873 for line in f.readlines():
875 if line and line[0] != '#':
876 self.excludes[line.split()[0]] = True
880 def __call__(self, testname):
881 return testname in self.excludes or testname.split('.')[-1] in self.excludes
883 def refactor_for_py3(distdir, cy3_dir):
884 # need to convert Cython sources first
885 import lib2to3.refactor
886 from distutils.util import copydir_run_2to3
887 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
888 if fix.split('fix_')[-1] not in ('next',)
890 if not os.path.exists(cy3_dir):
892 import distutils.log as dlog
893 dlog.set_threshold(dlog.INFO)
894 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
898 recursive-exclude Cython *
899 recursive-include Cython *.py *.pyx *.pxd
901 sys.path.insert(0, cy3_dir)
903 class PendingThreadsError(RuntimeError):
908 def check_thread_termination(ignore_seen=True):
909 if threading is None: # no threading enabled in CPython
911 current = threading.currentThread()
912 blocking_threads = []
913 for t in threading.enumerate():
914 if not t.isAlive() or t == current:
919 blocking_threads.append(t)
921 for seen in threads_seen:
925 threads_seen.append(t)
926 blocking_threads.append(t)
927 if not blocking_threads:
929 sys.stderr.write("warning: left-over threads found after running test:\n")
930 for t in blocking_threads:
931 sys.stderr.write('...%s\n' % repr(t))
932 raise PendingThreadsError("left-over threads found after running test")
935 from optparse import OptionParser
936 parser = OptionParser()
937 parser.add_option("--no-cleanup", dest="cleanup_workdir",
938 action="store_false", default=True,
939 help="do not delete the generated C files (allows passing --no-cython on next run)")
940 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
941 action="store_false", default=True,
942 help="do not delete the generated shared libary files (allows manual module experimentation)")
943 parser.add_option("--no-cython", dest="with_cython",
944 action="store_false", default=True,
945 help="do not run the Cython compiler, only the C compiler")
946 parser.add_option("--no-c", dest="use_c",
947 action="store_false", default=True,
948 help="do not test C compilation")
949 parser.add_option("--no-cpp", dest="use_cpp",
950 action="store_false", default=True,
951 help="do not test C++ compilation")
952 parser.add_option("--no-unit", dest="unittests",
953 action="store_false", default=True,
954 help="do not run the unit tests")
955 parser.add_option("--no-doctest", dest="doctests",
956 action="store_false", default=True,
957 help="do not run the doctests")
958 parser.add_option("--no-file", dest="filetests",
959 action="store_false", default=True,
960 help="do not run the file based tests")
961 parser.add_option("--no-pyregr", dest="pyregr",
962 action="store_false", default=True,
963 help="do not run the regression tests of CPython in tests/pyregr/")
964 parser.add_option("--cython-only", dest="cython_only",
965 action="store_true", default=False,
966 help="only compile pyx to c, do not run C compiler or run the tests")
967 parser.add_option("--no-refnanny", dest="with_refnanny",
968 action="store_false", default=True,
969 help="do not regression test reference counting")
970 parser.add_option("--no-fork", dest="fork",
971 action="store_false", default=True,
972 help="do not fork to run tests")
973 parser.add_option("--sys-pyregr", dest="system_pyregr",
974 action="store_true", default=False,
975 help="run the regression tests of the CPython installation")
976 parser.add_option("-x", "--exclude", dest="exclude",
977 action="append", metavar="PATTERN",
978 help="exclude tests matching the PATTERN")
979 parser.add_option("-C", "--coverage", dest="coverage",
980 action="store_true", default=False,
981 help="collect source coverage data for the Compiler")
982 parser.add_option("--coverage-xml", dest="coverage_xml",
983 action="store_true", default=False,
984 help="collect source coverage data for the Compiler in XML format")
985 parser.add_option("-A", "--annotate", dest="annotate_source",
986 action="store_true", default=True,
987 help="generate annotated HTML versions of the test source files")
988 parser.add_option("--no-annotate", dest="annotate_source",
989 action="store_false",
990 help="do not generate annotated HTML versions of the test source files")
991 parser.add_option("-v", "--verbose", dest="verbosity",
992 action="count", default=0,
993 help="display test progress, pass twice to print test names")
994 parser.add_option("-T", "--ticket", dest="tickets",
996 help="a bug ticket number to run the respective test in 'tests/*'")
997 parser.add_option("-3", dest="language_level",
998 action="store_const", const=3, default=2,
999 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1000 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1001 help="write test results in XML to directory DIR")
1002 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1003 action="store_true",
1004 help="exit without error code even on test failures")
1006 options, cmd_args = parser.parse_args()
1008 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1009 ROOTDIR = os.path.join(DISTDIR, 'tests')
1010 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
1012 if sys.version_info[0] >= 3:
1013 options.doctests = False
1014 if options.with_cython:
1016 # try if Cython is installed in a Py3 version
1017 import Cython.Compiler.Main
1019 # back out anything the import process loaded, then
1020 # 2to3 the Cython sources to make them re-importable
1021 cy_modules = [ name for name in sys.modules
1022 if name == 'Cython' or name.startswith('Cython.') ]
1023 for name in cy_modules:
1024 del sys.modules[name]
1025 # hasn't been refactored yet - do it now
1026 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1027 if sys.version_info >= (3,1):
1028 refactor_for_py3(DISTDIR, cy3_dir)
1029 elif os.path.isdir(cy3_dir):
1030 sys.path.insert(0, cy3_dir)
1032 options.with_cython = False
1034 WITH_CYTHON = options.with_cython
1036 if options.coverage or options.coverage_xml:
1038 options.coverage = options.coverage_xml = False
1040 from coverage import coverage as _coverage
1041 coverage = _coverage(branch=True)
1046 global CompilationOptions, pyrex_default_options, cython_compile
1047 from Cython.Compiler.Main import \
1048 CompilationOptions, \
1049 default_options as pyrex_default_options, \
1050 compile as cython_compile
1051 from Cython.Compiler import Errors
1052 Errors.LEVEL = 0 # show all warnings
1053 from Cython.Compiler import Options
1054 Options.generate_cleanup_code = 3 # complete cleanup code
1055 from Cython.Compiler import DebugFlags
1056 DebugFlags.debug_temp_code_comments = 1
1059 UNITTEST_MODULE = "Cython"
1060 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1062 if os.path.exists(WORKDIR):
1063 for path in os.listdir(WORKDIR):
1064 if path in ("support", "Cy3"): continue
1065 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1066 if not os.path.exists(WORKDIR):
1067 os.makedirs(WORKDIR)
1069 sys.stderr.write("Python %s\n" % sys.version)
1070 sys.stderr.write("\n")
1072 from Cython.Compiler.Version import version
1073 sys.stderr.write("Running tests against Cython %s\n" % version)
1075 sys.stderr.write("Running tests without Cython.\n")
1077 if options.with_refnanny:
1078 from pyximport.pyxbuild import pyx_to_dll
1079 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1081 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1082 sys.path.insert(0, os.path.split(libpath)[0])
1083 CFLAGS.append("-DCYTHON_REFNANNY=1")
1085 if options.xml_output_dir and options.fork:
1086 # doesn't currently work together
1087 sys.stderr.write("Disabling forked testing to support XML test output\n")
1088 options.fork = False
1090 if WITH_CYTHON and options.language_level == 3:
1091 sys.stderr.write("Using Cython language level 3.\n")
1093 sys.stderr.write("\n")
1097 for ticket_number in options.tickets:
1099 cmd_args.append('.*T%s$' % ticket_number)
1101 for selector in cmd_args:
1102 if selector.startswith('bugs'):
1106 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1108 selectors = [ lambda x:True ]
1110 # Chech which external modules are not present and exclude tests
1111 # which depends on them (by prefix)
1113 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1114 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1115 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1118 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1121 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1123 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1124 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1128 languages.append('c')
1130 languages.append('cpp')
1132 test_suite = unittest.TestSuite()
1134 if options.unittests:
1135 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1137 if options.doctests:
1138 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1140 if options.filetests and languages:
1141 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1142 options.annotate_source, options.cleanup_workdir,
1143 options.cleanup_sharedlibs, options.pyregr,
1144 options.cython_only, languages, test_bugs,
1145 options.fork, options.language_level)
1146 test_suite.addTest(filetests.build_suite())
1148 if options.system_pyregr and languages:
1149 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1150 options.annotate_source, options.cleanup_workdir,
1151 options.cleanup_sharedlibs, True,
1152 options.cython_only, languages, test_bugs,
1153 options.fork, options.language_level)
1155 filetests.handle_directory(
1156 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1159 if options.xml_output_dir:
1160 from Cython.Tests.xmlrunner import XMLTestRunner
1161 test_runner = XMLTestRunner(output=options.xml_output_dir,
1162 verbose=options.verbosity > 0)
1164 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1166 result = test_runner.run(test_suite)
1168 if options.coverage or options.coverage_xml:
1170 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1171 modules = [ module for name, module in sys.modules.items()
1172 if module is not None and
1173 name.startswith('Cython.Compiler.') and
1174 name[len('Cython.Compiler.'):] not in ignored_modules ]
1175 if options.coverage:
1176 coverage.report(modules, show_missing=0)
1177 if options.coverage_xml:
1178 coverage.xml_report(modules, outfile="coverage-report.xml")
1180 if missing_dep_excluder.tests_missing_deps:
1181 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1182 for test in missing_dep_excluder.tests_missing_deps:
1183 sys.stderr.write(" %s\n" % test)
1185 if options.with_refnanny:
1187 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1194 return_code = not result.wasSuccessful()
1197 check_thread_termination(ignore_seen=False)
1198 sys.exit(return_code)
1199 except PendingThreadsError:
1200 # normal program exit won't kill the threads, do it the hard way here
1201 os._exit(return_code)
1203 if __name__ == '__main__':
1206 except SystemExit: # <= Py2.4 ...
1209 traceback.print_exc()
1211 check_thread_termination(ignore_seen=False)
1212 except PendingThreadsError:
1213 # normal program exit won't kill the threads, do it the hard way here