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',
69 # The next line should start (3,); but this is a dictionary, so
70 # we can only have one (3,) key. Since 2.7 is supposed to be the
71 # last 2.x release, things would have to change drastically for this
73 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
74 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
75 'compile.extsetslice',
76 'compile.extdelslice',
77 'run.special_methods_T561_py2']),
80 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
81 CFLAGS = os.getenv('CFLAGS', '').split()
83 class build_ext(_build_ext):
84 def build_extension(self, ext):
85 if ext.language == 'c++':
87 try: # Py2.7+ & Py3.2+
88 compiler_obj = self.compiler_obj
89 except AttributeError:
90 compiler_obj = self.compiler
91 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
94 _build_ext.build_extension(self, ext)
96 class ErrorWriter(object):
97 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
100 self.write = self.output.append
102 def _collect(self, collect_errors, collect_warnings):
103 s = ''.join(self.output)
105 for line in s.split('\n'):
106 match = self.match_error(line)
108 is_warning, line, column, message = match.groups()
109 if (is_warning and collect_warnings) or \
110 (not is_warning and collect_errors):
111 result.append( (int(line), int(column), message.strip()) )
113 return [ "%d:%d: %s" % values for values in result ]
116 return self._collect(True, False)
118 def getwarnings(self):
119 return self._collect(False, True)
122 return self._collect(True, True)
124 class TestBuilder(object):
125 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
126 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
127 languages, test_bugs, fork, language_level):
128 self.rootdir = rootdir
129 self.workdir = workdir
130 self.selectors = selectors
131 self.exclude_selectors = exclude_selectors
132 self.annotate = annotate
133 self.cleanup_workdir = cleanup_workdir
134 self.cleanup_sharedlibs = cleanup_sharedlibs
135 self.with_pyregr = with_pyregr
136 self.cython_only = cython_only
137 self.languages = languages
138 self.test_bugs = test_bugs
140 self.language_level = language_level
142 def build_suite(self):
143 suite = unittest.TestSuite()
144 test_dirs = TEST_DIRS
145 filenames = os.listdir(self.rootdir)
147 for filename in filenames:
148 if not WITH_CYTHON and filename == "errors":
149 # we won't get any errors without running Cython
151 path = os.path.join(self.rootdir, filename)
152 if os.path.isdir(path) and filename in test_dirs:
153 if filename == 'pyregr' and not self.with_pyregr:
156 self.handle_directory(path, filename))
157 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
158 # Non-Windows makefile, can't run Cython under Py3.
159 if [1 for selector in self.selectors if selector("embedded")]:
160 suite.addTest(unittest.makeSuite(EmbedTest))
163 def handle_directory(self, path, context):
164 workdir = os.path.join(self.workdir, context)
165 if not os.path.exists(workdir):
168 expect_errors = (context == 'errors')
169 suite = unittest.TestSuite()
170 filenames = os.listdir(path)
172 for filename in filenames:
173 if context == "build" and filename.endswith(".srctree"):
174 if not [ 1 for match in self.selectors if match(filename) ]:
176 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
178 if not (filename.endswith(".pyx") or filename.endswith(".py")):
180 if filename.startswith('.'): continue # certain emacs backup files
181 if context == 'pyregr' and not filename.startswith('test_'):
183 module = os.path.splitext(filename)[0]
184 fqmodule = "%s.%s" % (context, module)
185 if not [ 1 for match in self.selectors
186 if match(fqmodule) ]:
188 if self.exclude_selectors:
189 if [1 for match in self.exclude_selectors if match(fqmodule)]:
191 if context in TEST_RUN_DIRS:
192 if module.startswith("test_"):
193 test_class = CythonUnitTestCase
195 test_class = CythonRunTestCase
197 test_class = CythonCompileTestCase
198 for test in self.build_tests(test_class, path, workdir,
199 module, expect_errors):
201 if context == 'run' and filename.endswith('.py'):
202 # additionally test file in real Python
203 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
206 def build_tests(self, test_class, path, workdir, module, expect_errors):
208 if 'cpp' in module and 'cpp' in self.languages:
211 languages = self.languages[:1]
213 languages = self.languages
214 if 'cpp' in module and 'c' in languages:
215 languages = list(languages)
216 languages.remove('c')
217 tests = [ self.build_test(test_class, path, workdir, module,
218 language, expect_errors)
219 for language in languages ]
222 def build_test(self, test_class, path, workdir, module,
223 language, expect_errors):
224 workdir = os.path.join(workdir, language)
225 if not os.path.exists(workdir):
227 return test_class(path, workdir, module,
229 expect_errors=expect_errors,
230 annotate=self.annotate,
231 cleanup_workdir=self.cleanup_workdir,
232 cleanup_sharedlibs=self.cleanup_sharedlibs,
233 cython_only=self.cython_only,
235 language_level=self.language_level)
237 class CythonCompileTestCase(unittest.TestCase):
238 def __init__(self, test_directory, workdir, module, language='c',
239 expect_errors=False, annotate=False, cleanup_workdir=True,
240 cleanup_sharedlibs=True, cython_only=False, fork=True,
242 self.test_directory = test_directory
243 self.workdir = workdir
245 self.language = language
246 self.expect_errors = expect_errors
247 self.annotate = annotate
248 self.cleanup_workdir = cleanup_workdir
249 self.cleanup_sharedlibs = cleanup_sharedlibs
250 self.cython_only = cython_only
252 self.language_level = language_level
253 unittest.TestCase.__init__(self)
255 def shortDescription(self):
256 return "compiling (%s) %s" % (self.language, self.module)
259 if self.workdir not in sys.path:
260 sys.path.insert(0, self.workdir)
264 sys.path.remove(self.workdir)
268 del sys.modules[self.module]
271 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
272 cleanup_lib_files = self.cleanup_sharedlibs
273 if os.path.exists(self.workdir):
274 for rmfile in os.listdir(self.workdir):
275 if not cleanup_c_files:
276 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
278 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
280 if self.annotate and rmfile.endswith(".html"):
283 rmfile = os.path.join(self.workdir, rmfile)
284 if os.path.isdir(rmfile):
285 shutil.rmtree(rmfile, ignore_errors=True)
291 os.makedirs(self.workdir)
294 self.runCompileTest()
296 def runCompileTest(self):
297 self.compile(self.test_directory, self.module, self.workdir,
298 self.test_directory, self.expect_errors, self.annotate)
300 def find_module_source_file(self, source_file):
301 if not os.path.exists(source_file):
302 source_file = source_file[:-1]
305 def build_target_filename(self, module_name):
306 target = '%s.%s' % (module_name, self.language)
309 def copy_related_files(self, test_directory, target_directory, module_name):
310 is_related = re.compile('%s_.*[.].*' % module_name).match
311 for filename in os.listdir(test_directory):
312 if is_related(filename):
313 shutil.copy(os.path.join(test_directory, filename),
316 def find_source_files(self, workdir, module_name):
317 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
318 return [self.build_target_filename(module_name)] + [
319 filename for filename in os.listdir(workdir)
320 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
322 def split_source_and_output(self, test_directory, module, workdir):
323 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
324 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
326 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
328 for line in source_and_output:
330 if line.startswith("_ERRORS"):
336 source_and_output.close()
338 geterrors = out.geterrors
339 except AttributeError:
345 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
346 include_dirs = INCLUDE_DIRS[:]
348 include_dirs.append(incdir)
349 source = self.find_module_source_file(
350 os.path.join(test_directory, module + '.pyx'))
351 target = os.path.join(targetdir, self.build_target_filename(module))
352 options = CompilationOptions(
353 pyrex_default_options,
354 include_path = include_dirs,
355 output_file = target,
357 use_listing_file = False,
358 cplus = self.language == 'cpp',
359 language_level = self.language_level,
360 generate_pxi = False,
361 evaluate_tree_assertions = True,
363 cython_compile(source, options=options,
364 full_module_name=module)
366 def run_distutils(self, test_directory, module, workdir, incdir):
370 build_extension = build_ext(distutils_distro)
371 build_extension.include_dirs = INCLUDE_DIRS[:]
373 build_extension.include_dirs.append(incdir)
374 build_extension.finalize_options()
375 ext_include_dirs = []
376 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
378 ext_include_dirs += get_additional_include_dirs()
379 self.copy_related_files(test_directory, workdir, module)
380 extension = Extension(
382 sources = self.find_source_files(workdir, module),
383 include_dirs = ext_include_dirs,
384 extra_compile_args = CFLAGS,
386 if self.language == 'cpp':
387 extension.language = 'c++'
388 build_extension.extensions = [extension]
389 build_extension.build_temp = workdir
390 build_extension.build_lib = workdir
391 build_extension.run()
395 def compile(self, test_directory, module, workdir, incdir,
396 expect_errors, annotate):
397 expected_errors = errors = ()
399 expected_errors = self.split_source_and_output(
400 test_directory, module, workdir)
401 test_directory = workdir
404 old_stderr = sys.stderr
406 sys.stderr = ErrorWriter()
407 self.run_cython(test_directory, module, workdir, incdir, annotate)
408 errors = sys.stderr.geterrors()
410 sys.stderr = old_stderr
412 if errors or expected_errors:
414 for expected, error in zip(expected_errors, errors):
415 self.assertEquals(expected, error)
416 if len(errors) < len(expected_errors):
417 expected_error = expected_errors[len(errors)]
418 self.assertEquals(expected_error, None)
419 elif len(errors) > len(expected_errors):
420 unexpected_error = errors[len(expected_errors)]
421 self.assertEquals(None, unexpected_error)
422 except AssertionError:
423 print("\n=== Expected errors: ===")
424 print('\n'.join(expected_errors))
425 print("\n\n=== Got errors: ===")
426 print('\n'.join(errors))
430 if not self.cython_only:
431 self.run_distutils(test_directory, module, workdir, incdir)
433 class CythonRunTestCase(CythonCompileTestCase):
434 def shortDescription(self):
435 return "compiling (%s) and running %s" % (self.language, self.module)
437 def run(self, result=None):
439 result = self.defaultTestResult()
440 result.startTest(self)
444 self.runCompileTest()
445 if not self.cython_only:
446 self.run_doctests(self.module, result)
448 check_thread_termination()
450 result.addError(self, sys.exc_info())
451 result.stopTest(self)
457 def run_doctests(self, module_name, result):
458 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
459 doctest.DocTestSuite(module_name).run(result)
463 # fork to make sure we do not keep the tested module loaded
464 result_handle, result_file = tempfile.mkstemp()
465 os.close(result_handle)
473 partial_result = PartialTestResult(result)
474 tests = doctest.DocTestSuite(module_name)
475 tests.run(partial_result)
479 # importing failed, try to fake a test class
481 failureException=sys.exc_info()[1],
482 _shortDescription=self.shortDescription(),
484 partial_result.addError(tests, sys.exc_info())
486 output = open(result_file, 'wb')
487 pickle.dump(partial_result.data(), output)
489 traceback.print_exc()
493 os._exit(result_code)
496 cid, result_code = os.waitpid(child_id, 0)
497 # os.waitpid returns the child's result code in the
498 # upper byte of result_code, and the signal it was
499 # killed by in the lower byte
500 if result_code & 255:
501 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
502 (module_name, result_code & 255))
503 result_code = result_code >> 8
504 if result_code in (0,1):
505 input = open(result_file, 'rb')
507 PartialTestResult.join_results(result, pickle.load(input))
511 raise Exception("Tests in module '%s' exited with status %d" %
512 (module_name, result_code))
514 try: os.unlink(result_file)
517 class PureDoctestTestCase(unittest.TestCase):
518 def __init__(self, module_name, module_path):
519 self.module_name = module_name
520 self.module_path = module_path
521 unittest.TestCase.__init__(self, 'run')
523 def shortDescription(self):
524 return "running pure doctests in %s" % self.module_name
526 def run(self, result=None):
528 result = self.defaultTestResult()
529 loaded_module_name = 'pure_doctest__' + self.module_name
530 result.startTest(self)
535 m = imp.load_source(loaded_module_name, self.module_path)
537 doctest.DocTestSuite(m).run(result)
540 if loaded_module_name in sys.modules:
541 del sys.modules[loaded_module_name]
542 check_thread_termination()
544 result.addError(self, sys.exc_info())
545 result.stopTest(self)
551 is_private_field = re.compile('^_[^_]').match
553 class _FakeClass(object):
554 def __init__(self, **kwargs):
555 self._shortDescription = kwargs.get('module_name')
556 self.__dict__.update(kwargs)
557 def shortDescription(self):
558 return self._shortDescription
560 try: # Py2.7+ and Py3.2+
561 from unittest.runner import _TextTestResult
563 from unittest import _TextTestResult
565 class PartialTestResult(_TextTestResult):
566 def __init__(self, base_result):
567 _TextTestResult.__init__(
568 self, self._StringIO(), True,
569 base_result.dots + base_result.showAll*2)
571 def strip_error_results(self, results):
572 for test_case, error in results:
573 for attr_name in filter(is_private_field, dir(test_case)):
574 if attr_name == '_dt_test':
575 test_case._dt_test = _FakeClass(
576 name=test_case._dt_test.name)
577 elif attr_name != '_shortDescription':
578 setattr(test_case, attr_name, None)
581 self.strip_error_results(self.failures)
582 self.strip_error_results(self.errors)
583 return (self.failures, self.errors, self.testsRun,
584 self.stream.getvalue())
586 def join_results(result, data):
587 """Static method for merging the result back into the main
590 failures, errors, tests_run, output = data
592 result.stream.write(output)
593 result.errors.extend(errors)
594 result.failures.extend(failures)
595 result.testsRun += tests_run
597 join_results = staticmethod(join_results)
599 class _StringIO(StringIO):
600 def writeln(self, line):
601 self.write("%s\n" % line)
604 class CythonUnitTestCase(CythonCompileTestCase):
605 def shortDescription(self):
606 return "compiling (%s) tests in %s" % (self.language, self.module)
608 def run(self, result=None):
610 result = self.defaultTestResult()
611 result.startTest(self)
615 self.runCompileTest()
616 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
618 check_thread_termination()
620 result.addError(self, sys.exc_info())
621 result.stopTest(self)
627 def collect_unittests(path, module_prefix, suite, selectors):
628 def file_matches(filename):
629 return filename.startswith("Test") and filename.endswith(".py")
631 def package_matches(dirname):
632 return dirname == "Tests"
634 loader = unittest.TestLoader()
638 for dirpath, dirnames, filenames in os.walk(path):
639 if dirpath != path and "__init__.py" not in filenames:
640 skipped_dirs.append(dirpath + os.path.sep)
643 for dir in skipped_dirs:
644 if dirpath.startswith(dir):
648 parentname = os.path.split(dirpath)[-1]
649 if package_matches(parentname):
652 filepath = os.path.join(dirpath, f)[:-len(".py")]
653 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
654 if not [ 1 for match in selectors if match(modulename) ]:
656 module = __import__(modulename)
657 for x in modulename.split('.')[1:]:
658 module = getattr(module, x)
659 suite.addTests([loader.loadTestsFromModule(module)])
661 def collect_doctests(path, module_prefix, suite, selectors):
662 def package_matches(dirname):
663 return dirname not in ("Mac", "Distutils", "Plex")
664 def file_matches(filename):
665 return (filename.endswith(".py") and not ('~' in filename
666 or '#' in filename or filename.startswith('.')))
667 import doctest, types
668 for dirpath, dirnames, filenames in os.walk(path):
669 parentname = os.path.split(dirpath)[-1]
670 if package_matches(parentname):
673 if not f.endswith('.py'): continue
674 filepath = os.path.join(dirpath, f)
675 if os.path.getsize(filepath) == 0: continue
676 if 'no doctest' in open(filepath).next(): continue
677 filepath = filepath[:-len(".py")]
678 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
679 if not [ 1 for match in selectors if match(modulename) ]:
681 module = __import__(modulename)
682 for x in modulename.split('.')[1:]:
683 module = getattr(module, x)
684 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
686 suite.addTest(doctest.DocTestSuite(module))
687 except ValueError: # no tests
691 class EndToEndTest(unittest.TestCase):
693 This is a test of build/*.srctree files, where srctree defines a full
694 directory structure and its header gives a list of commands to run.
696 cython_root = os.path.dirname(os.path.abspath(__file__))
698 def __init__(self, treefile, workdir, cleanup_workdir=True):
699 self.treefile = treefile
700 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
701 self.cleanup_workdir = cleanup_workdir
702 cython_syspath = self.cython_root
703 for path in sys.path[::-1]:
704 if path.startswith(self.cython_root):
705 # Py3 installation and refnanny build prepend their
706 # fixed paths to sys.path => prefer that over the
708 cython_syspath = path + os.pathsep + cython_syspath
709 self.cython_syspath = cython_syspath
710 unittest.TestCase.__init__(self)
712 def shortDescription(self):
713 return "End-to-end %s" % self.treefile
716 from Cython.TestUtils import unpack_source_tree
717 _, self.commands = unpack_source_tree(
718 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))
734 old_path = os.environ.get('PYTHONPATH')
735 os.environ['PYTHONPATH'] = os.path.join(self.cython_syspath, (old_path or ''))
736 for command in commands.split('\n'):
737 if sys.version_info[:2] >= (2,4):
739 p = subprocess.Popen(commands,
740 stderr=subprocess.PIPE,
741 stdout=subprocess.PIPE,
743 out, err = p.communicate()
750 res = os.system(command)
751 self.assertEqual(0, res, "non-zero exit status")
754 os.environ['PYTHONPATH'] = old_path
756 del os.environ['PYTHONPATH']
759 # TODO: Support cython_freeze needed here as well.
760 # TODO: Windows support.
762 class EmbedTest(unittest.TestCase):
764 working_dir = "Demos/embed"
767 self.old_dir = os.getcwd()
768 os.chdir(self.working_dir)
770 "make PYTHON='%s' clean > /dev/null" % sys.executable)
775 "make PYTHON='%s' clean > /dev/null" % sys.executable)
778 os.chdir(self.old_dir)
780 def test_embed(self):
781 from distutils import sysconfig
782 libname = sysconfig.get_config_var('LIBRARY')
783 libdir = sysconfig.get_config_var('LIBDIR')
784 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
785 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
786 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
787 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
788 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
789 # report the error for the original directory
790 libdir = sysconfig.get_config_var('LIBDIR')
791 self.assert_(os.system(
792 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
794 os.remove('make.output')
798 class MissingDependencyExcluder:
799 def __init__(self, deps):
800 # deps: { module name : matcher func }
801 self.exclude_matchers = []
802 for mod, matcher in deps.items():
806 self.exclude_matchers.append(matcher)
807 self.tests_missing_deps = []
808 def __call__(self, testname):
809 for matcher in self.exclude_matchers:
810 if matcher(testname):
811 self.tests_missing_deps.append(testname)
815 class VersionDependencyExcluder:
816 def __init__(self, deps):
817 # deps: { version : matcher func }
818 from sys import version_info
819 self.exclude_matchers = []
820 for ver, (compare, matcher) in deps.items():
821 if compare(version_info, ver):
822 self.exclude_matchers.append(matcher)
823 self.tests_missing_deps = []
824 def __call__(self, testname):
825 for matcher in self.exclude_matchers:
826 if matcher(testname):
827 self.tests_missing_deps.append(testname)
831 class FileListExcluder:
833 def __init__(self, list_file):
837 for line in f.readlines():
839 if line and line[0] != '#':
840 self.excludes[line.split()[0]] = True
844 def __call__(self, testname):
845 return testname in self.excludes or testname.split('.')[-1] in self.excludes
847 def refactor_for_py3(distdir, cy3_dir):
848 # need to convert Cython sources first
849 import lib2to3.refactor
850 from distutils.util import copydir_run_2to3
851 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
852 if fix.split('fix_')[-1] not in ('next',)
854 if not os.path.exists(cy3_dir):
856 import distutils.log as dlog
857 dlog.set_threshold(dlog.INFO)
858 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
862 recursive-exclude Cython *
863 recursive-include Cython *.py *.pyx *.pxd
865 sys.path.insert(0, cy3_dir)
867 class PendingThreadsError(RuntimeError):
872 def check_thread_termination(ignore_seen=True):
873 if threading is None: # no threading enabled in CPython
875 current = threading.currentThread()
876 blocking_threads = []
877 for t in threading.enumerate():
878 if not t.isAlive() or t == current:
883 blocking_threads.append(t)
885 for seen in threads_seen:
889 threads_seen.append(t)
890 blocking_threads.append(t)
891 if not blocking_threads:
893 sys.stderr.write("warning: left-over threads found after running test:\n")
894 for t in blocking_threads:
895 sys.stderr.write('...%s\n' % repr(t))
896 raise PendingThreadsError("left-over threads found after running test")
899 from optparse import OptionParser
900 parser = OptionParser()
901 parser.add_option("--no-cleanup", dest="cleanup_workdir",
902 action="store_false", default=True,
903 help="do not delete the generated C files (allows passing --no-cython on next run)")
904 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
905 action="store_false", default=True,
906 help="do not delete the generated shared libary files (allows manual module experimentation)")
907 parser.add_option("--no-cython", dest="with_cython",
908 action="store_false", default=True,
909 help="do not run the Cython compiler, only the C compiler")
910 parser.add_option("--no-c", dest="use_c",
911 action="store_false", default=True,
912 help="do not test C compilation")
913 parser.add_option("--no-cpp", dest="use_cpp",
914 action="store_false", default=True,
915 help="do not test C++ compilation")
916 parser.add_option("--no-unit", dest="unittests",
917 action="store_false", default=True,
918 help="do not run the unit tests")
919 parser.add_option("--no-doctest", dest="doctests",
920 action="store_false", default=True,
921 help="do not run the doctests")
922 parser.add_option("--no-file", dest="filetests",
923 action="store_false", default=True,
924 help="do not run the file based tests")
925 parser.add_option("--no-pyregr", dest="pyregr",
926 action="store_false", default=True,
927 help="do not run the regression tests of CPython in tests/pyregr/")
928 parser.add_option("--cython-only", dest="cython_only",
929 action="store_true", default=False,
930 help="only compile pyx to c, do not run C compiler or run the tests")
931 parser.add_option("--no-refnanny", dest="with_refnanny",
932 action="store_false", default=True,
933 help="do not regression test reference counting")
934 parser.add_option("--no-fork", dest="fork",
935 action="store_false", default=True,
936 help="do not fork to run tests")
937 parser.add_option("--sys-pyregr", dest="system_pyregr",
938 action="store_true", default=False,
939 help="run the regression tests of the CPython installation")
940 parser.add_option("-x", "--exclude", dest="exclude",
941 action="append", metavar="PATTERN",
942 help="exclude tests matching the PATTERN")
943 parser.add_option("-C", "--coverage", dest="coverage",
944 action="store_true", default=False,
945 help="collect source coverage data for the Compiler")
946 parser.add_option("--coverage-xml", dest="coverage_xml",
947 action="store_true", default=False,
948 help="collect source coverage data for the Compiler in XML format")
949 parser.add_option("-A", "--annotate", dest="annotate_source",
950 action="store_true", default=True,
951 help="generate annotated HTML versions of the test source files")
952 parser.add_option("--no-annotate", dest="annotate_source",
953 action="store_false",
954 help="do not generate annotated HTML versions of the test source files")
955 parser.add_option("-v", "--verbose", dest="verbosity",
956 action="count", default=0,
957 help="display test progress, pass twice to print test names")
958 parser.add_option("-T", "--ticket", dest="tickets",
960 help="a bug ticket number to run the respective test in 'tests/*'")
961 parser.add_option("-3", dest="language_level",
962 action="store_const", const=3, default=2,
963 help="set language level to Python 3 (useful for running the CPython regression tests)'")
964 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
965 help="write test results in XML to directory DIR")
966 parser.add_option("--exit-ok", dest="exit_ok", default=False,
968 help="exit without error code even on test failures")
970 options, cmd_args = parser.parse_args()
972 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
973 ROOTDIR = os.path.join(DISTDIR, 'tests')
974 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
976 if sys.version_info[0] >= 3:
977 options.doctests = False
978 if options.with_cython:
980 # try if Cython is installed in a Py3 version
981 import Cython.Compiler.Main
983 # back out anything the import process loaded, then
984 # 2to3 the Cython sources to make them re-importable
985 cy_modules = [ name for name in sys.modules
986 if name == 'Cython' or name.startswith('Cython.') ]
987 for name in cy_modules:
988 del sys.modules[name]
989 # hasn't been refactored yet - do it now
990 cy3_dir = os.path.join(WORKDIR, 'Cy3')
991 if sys.version_info >= (3,1):
992 refactor_for_py3(DISTDIR, cy3_dir)
993 elif os.path.isdir(cy3_dir):
994 sys.path.insert(0, cy3_dir)
996 options.with_cython = False
998 WITH_CYTHON = options.with_cython
1000 if options.coverage or options.coverage_xml:
1002 options.coverage = options.coverage_xml = False
1004 from coverage import coverage as _coverage
1005 coverage = _coverage(branch=True)
1010 global CompilationOptions, pyrex_default_options, cython_compile
1011 from Cython.Compiler.Main import \
1012 CompilationOptions, \
1013 default_options as pyrex_default_options, \
1014 compile as cython_compile
1015 from Cython.Compiler import Errors
1016 Errors.LEVEL = 0 # show all warnings
1017 from Cython.Compiler import Options
1018 Options.generate_cleanup_code = 3 # complete cleanup code
1019 from Cython.Compiler import DebugFlags
1020 DebugFlags.debug_temp_code_comments = 1
1023 UNITTEST_MODULE = "Cython"
1024 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1026 if os.path.exists(WORKDIR):
1027 for path in os.listdir(WORKDIR):
1028 if path in ("support", "Cy3"): continue
1029 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1030 if not os.path.exists(WORKDIR):
1031 os.makedirs(WORKDIR)
1033 sys.stderr.write("Python %s\n" % sys.version)
1034 sys.stderr.write("\n")
1036 from Cython.Compiler.Version import version
1037 sys.stderr.write("Running tests against Cython %s\n" % version)
1039 sys.stderr.write("Running tests without Cython.\n")
1041 if options.with_refnanny:
1042 from pyximport.pyxbuild import pyx_to_dll
1043 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1045 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1046 sys.path.insert(0, os.path.split(libpath)[0])
1047 CFLAGS.append("-DCYTHON_REFNANNY=1")
1049 if options.xml_output_dir and options.fork:
1050 # doesn't currently work together
1051 sys.stderr.write("Disabling forked testing to support XML test output\n")
1052 options.fork = False
1054 if WITH_CYTHON and options.language_level == 3:
1055 sys.stderr.write("Using Cython language level 3.\n")
1057 sys.stderr.write("\n")
1061 for ticket_number in options.tickets:
1063 cmd_args.append('.*T%s$' % ticket_number)
1065 for selector in cmd_args:
1066 if selector.startswith('bugs'):
1070 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1072 selectors = [ lambda x:True ]
1074 # Chech which external modules are not present and exclude tests
1075 # which depends on them (by prefix)
1077 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1078 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1079 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1082 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1085 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1087 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1088 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1092 languages.append('c')
1094 languages.append('cpp')
1096 test_suite = unittest.TestSuite()
1098 if options.unittests:
1099 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1101 if options.doctests:
1102 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1104 if options.filetests and languages:
1105 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1106 options.annotate_source, options.cleanup_workdir,
1107 options.cleanup_sharedlibs, options.pyregr,
1108 options.cython_only, languages, test_bugs,
1109 options.fork, options.language_level)
1110 test_suite.addTest(filetests.build_suite())
1112 if options.system_pyregr and languages:
1113 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1114 options.annotate_source, options.cleanup_workdir,
1115 options.cleanup_sharedlibs, True,
1116 options.cython_only, languages, test_bugs,
1117 options.fork, options.language_level)
1119 filetests.handle_directory(
1120 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1123 if options.xml_output_dir:
1124 from Cython.Tests.xmlrunner import XMLTestRunner
1125 test_runner = XMLTestRunner(output=options.xml_output_dir,
1126 verbose=options.verbosity > 0)
1128 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1130 result = test_runner.run(test_suite)
1132 if options.coverage or options.coverage_xml:
1134 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1135 modules = [ module for name, module in sys.modules.items()
1136 if module is not None and
1137 name.startswith('Cython.Compiler.') and
1138 name[len('Cython.Compiler.'):] not in ignored_modules ]
1139 if options.coverage:
1140 coverage.report(modules, show_missing=0)
1141 if options.coverage_xml:
1142 coverage.xml_report(modules, outfile="coverage-report.xml")
1144 if missing_dep_excluder.tests_missing_deps:
1145 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1146 for test in missing_dep_excluder.tests_missing_deps:
1147 sys.stderr.write(" %s\n" % test)
1149 if options.with_refnanny:
1151 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1158 return_code = not result.wasSuccessful()
1161 check_thread_termination(ignore_seen=False)
1162 sys.exit(return_code)
1163 except PendingThreadsError:
1164 # normal program exit won't kill the threads, do it the hard way here
1165 os._exit(return_code)
1167 if __name__ == '__main__':
1170 except SystemExit: # <= Py2.4 ...
1173 traceback.print_exc()
1175 check_thread_termination(ignore_seen=False)
1176 except PendingThreadsError:
1177 # normal program exit won't kill the threads, do it the hard way here