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 # Someone wrapped this in a:
648 # 'try: import gdb; ... except: include_debugger = False' thing, but don't do
649 # this, it doesn't work as gdb is a builtin module in GDB. The tests themselves
650 # are doing the skipping. If there's a problem with the tests, please file an
652 include_debugger = sys.version_info[:2] > (2, 5)
654 def collect_unittests(path, module_prefix, suite, selectors):
655 def file_matches(filename):
656 return filename.startswith("Test") and filename.endswith(".py")
658 def package_matches(dirname):
659 return dirname == "Tests"
661 loader = unittest.TestLoader()
666 cython_dir = os.path.dirname(os.path.abspath(__file__))
667 skipped_dirs = [os.path.join(cython_dir, 'Cython', 'Debugger')]
669 for dirpath, dirnames, filenames in os.walk(path):
670 if dirpath != path and "__init__.py" not in filenames:
671 skipped_dirs.append(dirpath + os.path.sep)
674 for dir in skipped_dirs:
675 if dirpath.startswith(dir):
679 parentname = os.path.split(dirpath)[-1]
680 if package_matches(parentname):
683 filepath = os.path.join(dirpath, f)[:-len(".py")]
684 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
685 if not [ 1 for match in selectors if match(modulename) ]:
687 module = __import__(modulename)
688 for x in modulename.split('.')[1:]:
689 module = getattr(module, x)
690 suite.addTests([loader.loadTestsFromModule(module)])
694 def collect_doctests(path, module_prefix, suite, selectors):
695 def package_matches(dirname):
696 if dirname == 'Debugger' and not include_debugger:
698 return dirname not in ("Mac", "Distutils", "Plex")
699 def file_matches(filename):
700 filename, ext = os.path.splitext(filename)
701 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
703 return (ext == '.py' and not
704 '~' in filename and not
705 '#' in filename and not
706 filename.startswith('.') and not
707 filename in blacklist)
708 import doctest, types
709 for dirpath, dirnames, filenames in os.walk(path):
710 for dir in list(dirnames):
711 if not package_matches(dir):
715 if not f.endswith('.py'): continue
716 filepath = os.path.join(dirpath, f)
717 if os.path.getsize(filepath) == 0: continue
718 filepath = filepath[:-len(".py")]
719 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
720 if not [ 1 for match in selectors if match(modulename) ]:
722 module = __import__(modulename)
723 for x in modulename.split('.')[1:]:
724 module = getattr(module, x)
725 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
727 suite.addTest(doctest.DocTestSuite(module))
728 except ValueError: # no tests
732 class EndToEndTest(unittest.TestCase):
734 This is a test of build/*.srctree files, where srctree defines a full
735 directory structure and its header gives a list of commands to run.
737 cython_root = os.path.dirname(os.path.abspath(__file__))
739 def __init__(self, treefile, workdir, cleanup_workdir=True):
740 self.treefile = treefile
741 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
742 self.cleanup_workdir = cleanup_workdir
743 cython_syspath = self.cython_root
744 for path in sys.path[::-1]:
745 if path.startswith(self.cython_root):
746 # Py3 installation and refnanny build prepend their
747 # fixed paths to sys.path => prefer that over the
749 cython_syspath = path + os.pathsep + cython_syspath
750 self.cython_syspath = cython_syspath
751 unittest.TestCase.__init__(self)
753 def shortDescription(self):
754 return "End-to-end %s" % self.treefile
757 from Cython.TestUtils import unpack_source_tree
758 _, self.commands = unpack_source_tree(
759 os.path.join('tests', 'build', self.treefile), self.workdir)
760 self.old_dir = os.getcwd()
761 os.chdir(self.workdir)
762 if self.workdir not in sys.path:
763 sys.path.insert(0, self.workdir)
766 if self.cleanup_workdir:
767 shutil.rmtree(self.workdir)
768 os.chdir(self.old_dir)
771 commands = (self.commands
772 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
773 .replace("PYTHON", sys.executable))
775 old_path = os.environ.get('PYTHONPATH')
776 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
777 for command in commands.split('\n'):
778 if sys.version_info[:2] >= (2,4):
780 p = subprocess.Popen(commands,
781 stderr=subprocess.PIPE,
782 stdout=subprocess.PIPE,
784 out, err = p.communicate()
791 res = os.system(command)
792 self.assertEqual(0, res, "non-zero exit status")
795 os.environ['PYTHONPATH'] = old_path
797 del os.environ['PYTHONPATH']
800 # TODO: Support cython_freeze needed here as well.
801 # TODO: Windows support.
803 class EmbedTest(unittest.TestCase):
805 working_dir = "Demos/embed"
808 self.old_dir = os.getcwd()
809 os.chdir(self.working_dir)
811 "make PYTHON='%s' clean > /dev/null" % sys.executable)
816 "make PYTHON='%s' clean > /dev/null" % sys.executable)
819 os.chdir(self.old_dir)
821 def test_embed(self):
822 from distutils import sysconfig
823 libname = sysconfig.get_config_var('LIBRARY')
824 libdir = sysconfig.get_config_var('LIBDIR')
825 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
826 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
827 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
828 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
829 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
830 # report the error for the original directory
831 libdir = sysconfig.get_config_var('LIBDIR')
832 self.assert_(os.system(
833 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
835 os.remove('make.output')
839 class MissingDependencyExcluder:
840 def __init__(self, deps):
841 # deps: { module name : matcher func }
842 self.exclude_matchers = []
843 for mod, matcher in deps.items():
847 self.exclude_matchers.append(matcher)
848 self.tests_missing_deps = []
849 def __call__(self, testname):
850 for matcher in self.exclude_matchers:
851 if matcher(testname):
852 self.tests_missing_deps.append(testname)
856 class VersionDependencyExcluder:
857 def __init__(self, deps):
858 # deps: { version : matcher func }
859 from sys import version_info
860 self.exclude_matchers = []
861 for ver, (compare, matcher) in deps.items():
862 if compare(version_info, ver):
863 self.exclude_matchers.append(matcher)
864 self.tests_missing_deps = []
865 def __call__(self, testname):
866 for matcher in self.exclude_matchers:
867 if matcher(testname):
868 self.tests_missing_deps.append(testname)
872 class FileListExcluder:
874 def __init__(self, list_file):
878 for line in f.readlines():
880 if line and line[0] != '#':
881 self.excludes[line.split()[0]] = True
885 def __call__(self, testname):
886 return testname in self.excludes or testname.split('.')[-1] in self.excludes
888 def refactor_for_py3(distdir, cy3_dir):
889 # need to convert Cython sources first
890 import lib2to3.refactor
891 from distutils.util import copydir_run_2to3
892 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
893 if fix.split('fix_')[-1] not in ('next',)
895 if not os.path.exists(cy3_dir):
897 import distutils.log as dlog
898 dlog.set_threshold(dlog.INFO)
899 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
903 recursive-exclude Cython *
904 recursive-include Cython *.py *.pyx *.pxd
906 sys.path.insert(0, cy3_dir)
908 class PendingThreadsError(RuntimeError):
913 def check_thread_termination(ignore_seen=True):
914 if threading is None: # no threading enabled in CPython
916 current = threading.currentThread()
917 blocking_threads = []
918 for t in threading.enumerate():
919 if not t.isAlive() or t == current:
924 blocking_threads.append(t)
926 for seen in threads_seen:
930 threads_seen.append(t)
931 blocking_threads.append(t)
932 if not blocking_threads:
934 sys.stderr.write("warning: left-over threads found after running test:\n")
935 for t in blocking_threads:
936 sys.stderr.write('...%s\n' % repr(t))
937 raise PendingThreadsError("left-over threads found after running test")
940 from optparse import OptionParser
941 parser = OptionParser()
942 parser.add_option("--no-cleanup", dest="cleanup_workdir",
943 action="store_false", default=True,
944 help="do not delete the generated C files (allows passing --no-cython on next run)")
945 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
946 action="store_false", default=True,
947 help="do not delete the generated shared libary files (allows manual module experimentation)")
948 parser.add_option("--no-cython", dest="with_cython",
949 action="store_false", default=True,
950 help="do not run the Cython compiler, only the C compiler")
951 parser.add_option("--no-c", dest="use_c",
952 action="store_false", default=True,
953 help="do not test C compilation")
954 parser.add_option("--no-cpp", dest="use_cpp",
955 action="store_false", default=True,
956 help="do not test C++ compilation")
957 parser.add_option("--no-unit", dest="unittests",
958 action="store_false", default=True,
959 help="do not run the unit tests")
960 parser.add_option("--no-doctest", dest="doctests",
961 action="store_false", default=True,
962 help="do not run the doctests")
963 parser.add_option("--no-file", dest="filetests",
964 action="store_false", default=True,
965 help="do not run the file based tests")
966 parser.add_option("--no-pyregr", dest="pyregr",
967 action="store_false", default=True,
968 help="do not run the regression tests of CPython in tests/pyregr/")
969 parser.add_option("--cython-only", dest="cython_only",
970 action="store_true", default=False,
971 help="only compile pyx to c, do not run C compiler or run the tests")
972 parser.add_option("--no-refnanny", dest="with_refnanny",
973 action="store_false", default=True,
974 help="do not regression test reference counting")
975 parser.add_option("--no-fork", dest="fork",
976 action="store_false", default=True,
977 help="do not fork to run tests")
978 parser.add_option("--sys-pyregr", dest="system_pyregr",
979 action="store_true", default=False,
980 help="run the regression tests of the CPython installation")
981 parser.add_option("-x", "--exclude", dest="exclude",
982 action="append", metavar="PATTERN",
983 help="exclude tests matching the PATTERN")
984 parser.add_option("-C", "--coverage", dest="coverage",
985 action="store_true", default=False,
986 help="collect source coverage data for the Compiler")
987 parser.add_option("--coverage-xml", dest="coverage_xml",
988 action="store_true", default=False,
989 help="collect source coverage data for the Compiler in XML format")
990 parser.add_option("-A", "--annotate", dest="annotate_source",
991 action="store_true", default=True,
992 help="generate annotated HTML versions of the test source files")
993 parser.add_option("--no-annotate", dest="annotate_source",
994 action="store_false",
995 help="do not generate annotated HTML versions of the test source files")
996 parser.add_option("-v", "--verbose", dest="verbosity",
997 action="count", default=0,
998 help="display test progress, pass twice to print test names")
999 parser.add_option("-T", "--ticket", dest="tickets",
1001 help="a bug ticket number to run the respective test in 'tests/*'")
1002 parser.add_option("-3", dest="language_level",
1003 action="store_const", const=3, default=2,
1004 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1005 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1006 help="write test results in XML to directory DIR")
1007 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1008 action="store_true",
1009 help="exit without error code even on test failures")
1011 options, cmd_args = parser.parse_args()
1013 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1014 ROOTDIR = os.path.join(DISTDIR, 'tests')
1015 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
1017 if sys.version_info[0] >= 3:
1018 options.doctests = False
1019 if options.with_cython:
1021 # try if Cython is installed in a Py3 version
1022 import Cython.Compiler.Main
1024 # back out anything the import process loaded, then
1025 # 2to3 the Cython sources to make them re-importable
1026 cy_modules = [ name for name in sys.modules
1027 if name == 'Cython' or name.startswith('Cython.') ]
1028 for name in cy_modules:
1029 del sys.modules[name]
1030 # hasn't been refactored yet - do it now
1031 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1032 if sys.version_info >= (3,1):
1033 refactor_for_py3(DISTDIR, cy3_dir)
1034 elif os.path.isdir(cy3_dir):
1035 sys.path.insert(0, cy3_dir)
1037 options.with_cython = False
1039 WITH_CYTHON = options.with_cython
1041 if options.coverage or options.coverage_xml:
1043 options.coverage = options.coverage_xml = False
1045 from coverage import coverage as _coverage
1046 coverage = _coverage(branch=True)
1051 global CompilationOptions, pyrex_default_options, cython_compile
1052 from Cython.Compiler.Main import \
1053 CompilationOptions, \
1054 default_options as pyrex_default_options, \
1055 compile as cython_compile
1056 from Cython.Compiler import Errors
1057 Errors.LEVEL = 0 # show all warnings
1058 from Cython.Compiler import Options
1059 Options.generate_cleanup_code = 3 # complete cleanup code
1060 from Cython.Compiler import DebugFlags
1061 DebugFlags.debug_temp_code_comments = 1
1064 UNITTEST_MODULE = "Cython"
1065 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1067 if os.path.exists(WORKDIR):
1068 for path in os.listdir(WORKDIR):
1069 if path in ("support", "Cy3"): continue
1070 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1071 if not os.path.exists(WORKDIR):
1072 os.makedirs(WORKDIR)
1074 sys.stderr.write("Python %s\n" % sys.version)
1075 sys.stderr.write("\n")
1077 from Cython.Compiler.Version import version
1078 sys.stderr.write("Running tests against Cython %s\n" % version)
1080 sys.stderr.write("Running tests without Cython.\n")
1082 if options.with_refnanny:
1083 from pyximport.pyxbuild import pyx_to_dll
1084 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1086 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1087 sys.path.insert(0, os.path.split(libpath)[0])
1088 CFLAGS.append("-DCYTHON_REFNANNY=1")
1090 if options.xml_output_dir and options.fork:
1091 # doesn't currently work together
1092 sys.stderr.write("Disabling forked testing to support XML test output\n")
1093 options.fork = False
1095 if WITH_CYTHON and options.language_level == 3:
1096 sys.stderr.write("Using Cython language level 3.\n")
1098 sys.stderr.write("\n")
1102 for ticket_number in options.tickets:
1104 cmd_args.append('.*T%s$' % ticket_number)
1106 for selector in cmd_args:
1107 if selector.startswith('bugs'):
1111 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1113 selectors = [ lambda x:True ]
1115 # Chech which external modules are not present and exclude tests
1116 # which depends on them (by prefix)
1118 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1119 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1120 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1123 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1126 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1128 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1129 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1133 languages.append('c')
1135 languages.append('cpp')
1137 test_suite = unittest.TestSuite()
1139 if options.unittests:
1140 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1142 if options.doctests:
1143 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1145 if options.filetests and languages:
1146 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1147 options.annotate_source, options.cleanup_workdir,
1148 options.cleanup_sharedlibs, options.pyregr,
1149 options.cython_only, languages, test_bugs,
1150 options.fork, options.language_level)
1151 test_suite.addTest(filetests.build_suite())
1153 if options.system_pyregr and languages:
1154 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1155 options.annotate_source, options.cleanup_workdir,
1156 options.cleanup_sharedlibs, True,
1157 options.cython_only, languages, test_bugs,
1158 options.fork, options.language_level)
1160 filetests.handle_directory(
1161 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1164 if options.xml_output_dir:
1165 from Cython.Tests.xmlrunner import XMLTestRunner
1166 test_runner = XMLTestRunner(output=options.xml_output_dir,
1167 verbose=options.verbosity > 0)
1169 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1171 result = test_runner.run(test_suite)
1173 if options.coverage or options.coverage_xml:
1175 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1176 modules = [ module for name, module in sys.modules.items()
1177 if module is not None and
1178 name.startswith('Cython.Compiler.') and
1179 name[len('Cython.Compiler.'):] not in ignored_modules ]
1180 if options.coverage:
1181 coverage.report(modules, show_missing=0)
1182 if options.coverage_xml:
1183 coverage.xml_report(modules, outfile="coverage-report.xml")
1185 if missing_dep_excluder.tests_missing_deps:
1186 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1187 for test in missing_dep_excluder.tests_missing_deps:
1188 sys.stderr.write(" %s\n" % test)
1190 if options.with_refnanny:
1192 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1199 return_code = not result.wasSuccessful()
1202 check_thread_termination(ignore_seen=False)
1203 sys.exit(return_code)
1204 except PendingThreadsError:
1205 # normal program exit won't kill the threads, do it the hard way here
1206 os._exit(return_code)
1208 if __name__ == '__main__':
1211 except SystemExit: # <= Py2.4 ...
1214 traceback.print_exc()
1216 check_thread_termination(ignore_seen=False)
1217 except PendingThreadsError:
1218 # normal program exit won't kill the threads, do it the hard way here