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 == 'pyregr':
193 test_class = CythonPyregrTestCase
194 elif context in TEST_RUN_DIRS:
195 if module.startswith("test_"):
196 test_class = CythonUnitTestCase
198 test_class = CythonRunTestCase
200 test_class = CythonCompileTestCase
201 for test in self.build_tests(test_class, path, workdir,
202 module, expect_errors):
204 if context == 'run' and filename.endswith('.py'):
205 # additionally test file in real Python
206 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
209 def build_tests(self, test_class, path, workdir, module, expect_errors):
211 if 'cpp' in module and 'cpp' in self.languages:
214 languages = self.languages[:1]
216 languages = self.languages
217 if 'cpp' in module and 'c' in languages:
218 languages = list(languages)
219 languages.remove('c')
220 tests = [ self.build_test(test_class, path, workdir, module,
221 language, expect_errors)
222 for language in languages ]
225 def build_test(self, test_class, path, workdir, module,
226 language, expect_errors):
227 workdir = os.path.join(workdir, language)
228 if not os.path.exists(workdir):
230 return test_class(path, workdir, module,
232 expect_errors=expect_errors,
233 annotate=self.annotate,
234 cleanup_workdir=self.cleanup_workdir,
235 cleanup_sharedlibs=self.cleanup_sharedlibs,
236 cython_only=self.cython_only,
238 language_level=self.language_level)
240 class CythonCompileTestCase(unittest.TestCase):
241 def __init__(self, test_directory, workdir, module, language='c',
242 expect_errors=False, annotate=False, cleanup_workdir=True,
243 cleanup_sharedlibs=True, cython_only=False, fork=True,
245 self.test_directory = test_directory
246 self.workdir = workdir
248 self.language = language
249 self.expect_errors = expect_errors
250 self.annotate = annotate
251 self.cleanup_workdir = cleanup_workdir
252 self.cleanup_sharedlibs = cleanup_sharedlibs
253 self.cython_only = cython_only
255 self.language_level = language_level
256 unittest.TestCase.__init__(self)
258 def shortDescription(self):
259 return "compiling (%s) %s" % (self.language, self.module)
262 if self.workdir not in sys.path:
263 sys.path.insert(0, self.workdir)
267 sys.path.remove(self.workdir)
271 del sys.modules[self.module]
274 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
275 cleanup_lib_files = self.cleanup_sharedlibs
276 if os.path.exists(self.workdir):
277 for rmfile in os.listdir(self.workdir):
278 if not cleanup_c_files:
279 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
281 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
283 if self.annotate and rmfile.endswith(".html"):
286 rmfile = os.path.join(self.workdir, rmfile)
287 if os.path.isdir(rmfile):
288 shutil.rmtree(rmfile, ignore_errors=True)
294 os.makedirs(self.workdir)
297 self.runCompileTest()
299 def runCompileTest(self):
300 self.compile(self.test_directory, self.module, self.workdir,
301 self.test_directory, self.expect_errors, self.annotate)
303 def find_module_source_file(self, source_file):
304 if not os.path.exists(source_file):
305 source_file = source_file[:-1]
308 def build_target_filename(self, module_name):
309 target = '%s.%s' % (module_name, self.language)
312 def copy_related_files(self, test_directory, target_directory, module_name):
313 is_related = re.compile('%s_.*[.].*' % module_name).match
314 for filename in os.listdir(test_directory):
315 if is_related(filename):
316 shutil.copy(os.path.join(test_directory, filename),
319 def find_source_files(self, workdir, module_name):
320 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
321 return [self.build_target_filename(module_name)] + [
322 filename for filename in os.listdir(workdir)
323 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
325 def split_source_and_output(self, test_directory, module, workdir):
326 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
327 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
329 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
331 for line in source_and_output:
333 if line.startswith("_ERRORS"):
339 source_and_output.close()
341 geterrors = out.geterrors
342 except AttributeError:
348 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
349 extra_compile_options=None):
350 include_dirs = INCLUDE_DIRS[:]
352 include_dirs.append(incdir)
353 source = self.find_module_source_file(
354 os.path.join(test_directory, module + '.pyx'))
355 target = os.path.join(targetdir, self.build_target_filename(module))
357 if extra_compile_options is None:
358 extra_compile_options = {}
363 from Cython.Compiler.Main import CompilationOptions
364 from Cython.Compiler.Main import compile as cython_compile
365 from Cython.Compiler.Main import default_options
367 options = CompilationOptions(
369 include_path = include_dirs,
370 output_file = target,
372 use_listing_file = False,
373 cplus = self.language == 'cpp',
374 language_level = self.language_level,
375 generate_pxi = False,
376 evaluate_tree_assertions = True,
377 **extra_compile_options
379 cython_compile(source, options=options,
380 full_module_name=module)
382 def run_distutils(self, test_directory, module, workdir, incdir,
383 extra_extension_args=None):
387 build_extension = build_ext(distutils_distro)
388 build_extension.include_dirs = INCLUDE_DIRS[:]
390 build_extension.include_dirs.append(incdir)
391 build_extension.finalize_options()
392 ext_include_dirs = []
393 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
395 ext_include_dirs += get_additional_include_dirs()
396 self.copy_related_files(test_directory, workdir, module)
398 if extra_extension_args is None:
399 extra_extension_args = {}
401 extension = Extension(
403 sources = self.find_source_files(workdir, module),
404 include_dirs = ext_include_dirs,
405 extra_compile_args = CFLAGS,
406 **extra_extension_args
408 if self.language == 'cpp':
409 extension.language = 'c++'
410 build_extension.extensions = [extension]
411 build_extension.build_temp = workdir
412 build_extension.build_lib = workdir
413 build_extension.run()
417 def compile(self, test_directory, module, workdir, incdir,
418 expect_errors, annotate):
419 expected_errors = errors = ()
421 expected_errors = self.split_source_and_output(
422 test_directory, module, workdir)
423 test_directory = workdir
426 old_stderr = sys.stderr
428 sys.stderr = ErrorWriter()
429 self.run_cython(test_directory, module, workdir, incdir, annotate)
430 errors = sys.stderr.geterrors()
432 sys.stderr = old_stderr
434 if errors or expected_errors:
436 for expected, error in zip(expected_errors, errors):
437 self.assertEquals(expected, error)
438 if len(errors) < len(expected_errors):
439 expected_error = expected_errors[len(errors)]
440 self.assertEquals(expected_error, None)
441 elif len(errors) > len(expected_errors):
442 unexpected_error = errors[len(expected_errors)]
443 self.assertEquals(None, unexpected_error)
444 except AssertionError:
445 print("\n=== Expected errors: ===")
446 print('\n'.join(expected_errors))
447 print("\n\n=== Got errors: ===")
448 print('\n'.join(errors))
452 if not self.cython_only:
453 self.run_distutils(test_directory, module, workdir, incdir)
455 class CythonRunTestCase(CythonCompileTestCase):
456 def shortDescription(self):
457 return "compiling (%s) and running %s" % (self.language, self.module)
459 def run(self, result=None):
461 result = self.defaultTestResult()
462 result.startTest(self)
466 self.runCompileTest()
467 self.run_tests(result)
469 check_thread_termination()
471 result.addError(self, sys.exc_info())
472 result.stopTest(self)
478 def run_tests(self, result):
479 if not self.cython_only:
480 self.run_doctests(self.module, result)
482 def run_doctests(self, module_name, result):
483 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
484 doctest.DocTestSuite(module_name).run(result)
488 # fork to make sure we do not keep the tested module loaded
489 result_handle, result_file = tempfile.mkstemp()
490 os.close(result_handle)
498 partial_result = PartialTestResult(result)
499 tests = doctest.DocTestSuite(module_name)
500 tests.run(partial_result)
504 # importing failed, try to fake a test class
506 failureException=sys.exc_info()[1],
507 _shortDescription=self.shortDescription(),
509 partial_result.addError(tests, sys.exc_info())
511 output = open(result_file, 'wb')
512 pickle.dump(partial_result.data(), output)
514 traceback.print_exc()
518 os._exit(result_code)
521 cid, result_code = os.waitpid(child_id, 0)
522 # os.waitpid returns the child's result code in the
523 # upper byte of result_code, and the signal it was
524 # killed by in the lower byte
525 if result_code & 255:
526 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
527 (module_name, result_code & 255))
528 result_code = result_code >> 8
529 if result_code in (0,1):
530 input = open(result_file, 'rb')
532 PartialTestResult.join_results(result, pickle.load(input))
536 raise Exception("Tests in module '%s' exited with status %d" %
537 (module_name, result_code))
539 try: os.unlink(result_file)
542 class PureDoctestTestCase(unittest.TestCase):
543 def __init__(self, module_name, module_path):
544 self.module_name = module_name
545 self.module_path = module_path
546 unittest.TestCase.__init__(self, 'run')
548 def shortDescription(self):
549 return "running pure doctests in %s" % self.module_name
551 def run(self, result=None):
553 result = self.defaultTestResult()
554 loaded_module_name = 'pure_doctest__' + self.module_name
555 result.startTest(self)
560 m = imp.load_source(loaded_module_name, self.module_path)
562 doctest.DocTestSuite(m).run(result)
565 if loaded_module_name in sys.modules:
566 del sys.modules[loaded_module_name]
567 check_thread_termination()
569 result.addError(self, sys.exc_info())
570 result.stopTest(self)
576 is_private_field = re.compile('^_[^_]').match
578 class _FakeClass(object):
579 def __init__(self, **kwargs):
580 self._shortDescription = kwargs.get('module_name')
581 self.__dict__.update(kwargs)
582 def shortDescription(self):
583 return self._shortDescription
585 try: # Py2.7+ and Py3.2+
586 from unittest.runner import _TextTestResult
588 from unittest import _TextTestResult
590 class PartialTestResult(_TextTestResult):
591 def __init__(self, base_result):
592 _TextTestResult.__init__(
593 self, self._StringIO(), True,
594 base_result.dots + base_result.showAll*2)
596 def strip_error_results(self, results):
597 for test_case, error in results:
598 for attr_name in filter(is_private_field, dir(test_case)):
599 if attr_name == '_dt_test':
600 test_case._dt_test = _FakeClass(
601 name=test_case._dt_test.name)
602 elif attr_name != '_shortDescription':
603 setattr(test_case, attr_name, None)
606 self.strip_error_results(self.failures)
607 self.strip_error_results(self.errors)
608 return (self.failures, self.errors, self.testsRun,
609 self.stream.getvalue())
611 def join_results(result, data):
612 """Static method for merging the result back into the main
615 failures, errors, tests_run, output = data
617 result.stream.write(output)
618 result.errors.extend(errors)
619 result.failures.extend(failures)
620 result.testsRun += tests_run
622 join_results = staticmethod(join_results)
624 class _StringIO(StringIO):
625 def writeln(self, line):
626 self.write("%s\n" % line)
629 class CythonUnitTestCase(CythonRunTestCase):
630 def shortDescription(self):
631 return "compiling (%s) tests in %s" % (self.language, self.module)
633 def run_tests(self, result):
634 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
637 class CythonPyregrTestCase(CythonRunTestCase):
638 def _run_unittest(self, result, *classes):
639 """Run tests from unittest.TestCase-derived classes."""
640 valid_types = (unittest.TestSuite, unittest.TestCase)
641 suite = unittest.TestSuite()
643 if isinstance(cls, str):
644 if cls in sys.modules:
645 suite.addTest(unittest.findTestCases(sys.modules[cls]))
647 raise ValueError("str arguments must be keys in sys.modules")
648 elif isinstance(cls, valid_types):
651 suite.addTest(unittest.makeSuite(cls))
654 def _run_doctest(self, result, module):
655 self.run_doctests(module, result)
657 def run_tests(self, result):
659 from test import test_support as support
660 except ImportError: # Py3k
661 from test import support
663 def run_unittest(*classes):
664 return self._run_unittest(result, *classes)
665 def run_doctest(module, verbosity=None):
666 return self._run_doctest(result, module)
668 support.run_unittest = run_unittest
669 support.run_doctest = run_doctest
672 module = __import__(self.module)
673 if hasattr(module, 'test_main'):
675 except (unittest.SkipTest, support.ResourceDenied):
676 result.addSkip(self, 'ok')
681 include_debugger = sys.version_info[:2] > (2, 5)
683 include_debugger = False
685 def collect_unittests(path, module_prefix, suite, selectors):
686 def file_matches(filename):
687 return filename.startswith("Test") and filename.endswith(".py")
689 def package_matches(dirname):
690 return dirname == "Tests"
692 loader = unittest.TestLoader()
697 cython_dir = os.path.dirname(os.path.abspath(__file__))
698 skipped_dirs = [os.path.join(cython_dir, 'Cython', 'Debugger')]
700 for dirpath, dirnames, filenames in os.walk(path):
701 if dirpath != path and "__init__.py" not in filenames:
702 skipped_dirs.append(dirpath + os.path.sep)
705 for dir in skipped_dirs:
706 if dirpath.startswith(dir):
710 parentname = os.path.split(dirpath)[-1]
711 if package_matches(parentname):
714 filepath = os.path.join(dirpath, f)[:-len(".py")]
715 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
716 if not [ 1 for match in selectors if match(modulename) ]:
718 module = __import__(modulename)
719 for x in modulename.split('.')[1:]:
720 module = getattr(module, x)
721 suite.addTests([loader.loadTestsFromModule(module)])
725 def collect_doctests(path, module_prefix, suite, selectors):
726 def package_matches(dirname):
727 if dirname == 'Debugger' and not include_debugger:
729 return dirname not in ("Mac", "Distutils", "Plex")
730 def file_matches(filename):
731 filename, ext = os.path.splitext(filename)
732 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
734 return (ext == '.py' and not
735 '~' in filename and not
736 '#' in filename and not
737 filename.startswith('.') and not
738 filename in blacklist)
739 import doctest, types
740 for dirpath, dirnames, filenames in os.walk(path):
741 for dir in list(dirnames):
742 if not package_matches(dir):
746 if not f.endswith('.py'): continue
747 filepath = os.path.join(dirpath, f)
748 if os.path.getsize(filepath) == 0: continue
749 filepath = filepath[:-len(".py")]
750 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
751 if not [ 1 for match in selectors if match(modulename) ]:
753 module = __import__(modulename)
754 for x in modulename.split('.')[1:]:
755 module = getattr(module, x)
756 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
758 suite.addTest(doctest.DocTestSuite(module))
759 except ValueError: # no tests
763 class EndToEndTest(unittest.TestCase):
765 This is a test of build/*.srctree files, where srctree defines a full
766 directory structure and its header gives a list of commands to run.
768 cython_root = os.path.dirname(os.path.abspath(__file__))
770 def __init__(self, treefile, workdir, cleanup_workdir=True):
771 self.treefile = treefile
772 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
773 self.cleanup_workdir = cleanup_workdir
774 cython_syspath = self.cython_root
775 for path in sys.path[::-1]:
776 if path.startswith(self.cython_root):
777 # Py3 installation and refnanny build prepend their
778 # fixed paths to sys.path => prefer that over the
780 cython_syspath = path + os.pathsep + cython_syspath
781 self.cython_syspath = cython_syspath
782 unittest.TestCase.__init__(self)
784 def shortDescription(self):
785 return "End-to-end %s" % self.treefile
788 from Cython.TestUtils import unpack_source_tree
789 _, self.commands = unpack_source_tree(
790 os.path.join('tests', 'build', self.treefile), self.workdir)
791 self.old_dir = os.getcwd()
792 os.chdir(self.workdir)
793 if self.workdir not in sys.path:
794 sys.path.insert(0, self.workdir)
797 if self.cleanup_workdir:
798 shutil.rmtree(self.workdir)
799 os.chdir(self.old_dir)
802 commands = (self.commands
803 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
804 .replace("PYTHON", sys.executable))
806 old_path = os.environ.get('PYTHONPATH')
807 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
808 for command in commands.split('\n'):
809 if sys.version_info[:2] >= (2,4):
811 p = subprocess.Popen(commands,
812 stderr=subprocess.PIPE,
813 stdout=subprocess.PIPE,
815 out, err = p.communicate()
822 res = os.system(command)
823 self.assertEqual(0, res, "non-zero exit status")
826 os.environ['PYTHONPATH'] = old_path
828 del os.environ['PYTHONPATH']
831 # TODO: Support cython_freeze needed here as well.
832 # TODO: Windows support.
834 class EmbedTest(unittest.TestCase):
836 working_dir = "Demos/embed"
839 self.old_dir = os.getcwd()
840 os.chdir(self.working_dir)
842 "make PYTHON='%s' clean > /dev/null" % sys.executable)
847 "make PYTHON='%s' clean > /dev/null" % sys.executable)
850 os.chdir(self.old_dir)
852 def test_embed(self):
853 from distutils import sysconfig
854 libname = sysconfig.get_config_var('LIBRARY')
855 libdir = sysconfig.get_config_var('LIBDIR')
856 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
857 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
858 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
859 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
860 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
861 # report the error for the original directory
862 libdir = sysconfig.get_config_var('LIBDIR')
863 self.assert_(os.system(
864 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
866 os.remove('make.output')
870 class MissingDependencyExcluder:
871 def __init__(self, deps):
872 # deps: { module name : matcher func }
873 self.exclude_matchers = []
874 for mod, matcher in deps.items():
878 self.exclude_matchers.append(matcher)
879 self.tests_missing_deps = []
880 def __call__(self, testname):
881 for matcher in self.exclude_matchers:
882 if matcher(testname):
883 self.tests_missing_deps.append(testname)
887 class VersionDependencyExcluder:
888 def __init__(self, deps):
889 # deps: { version : matcher func }
890 from sys import version_info
891 self.exclude_matchers = []
892 for ver, (compare, matcher) in deps.items():
893 if compare(version_info, ver):
894 self.exclude_matchers.append(matcher)
895 self.tests_missing_deps = []
896 def __call__(self, testname):
897 for matcher in self.exclude_matchers:
898 if matcher(testname):
899 self.tests_missing_deps.append(testname)
903 class FileListExcluder:
905 def __init__(self, list_file):
909 for line in f.readlines():
911 if line and line[0] != '#':
912 self.excludes[line.split()[0]] = True
916 def __call__(self, testname):
917 return testname in self.excludes or testname.split('.')[-1] in self.excludes
919 def refactor_for_py3(distdir, cy3_dir):
920 # need to convert Cython sources first
921 import lib2to3.refactor
922 from distutils.util import copydir_run_2to3
923 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
924 if fix.split('fix_')[-1] not in ('next',)
926 if not os.path.exists(cy3_dir):
928 import distutils.log as dlog
929 dlog.set_threshold(dlog.INFO)
930 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
934 recursive-exclude Cython *
935 recursive-include Cython *.py *.pyx *.pxd
937 sys.path.insert(0, cy3_dir)
939 class PendingThreadsError(RuntimeError):
944 def check_thread_termination(ignore_seen=True):
945 if threading is None: # no threading enabled in CPython
947 current = threading.currentThread()
948 blocking_threads = []
949 for t in threading.enumerate():
950 if not t.isAlive() or t == current:
955 blocking_threads.append(t)
957 for seen in threads_seen:
961 threads_seen.append(t)
962 blocking_threads.append(t)
963 if not blocking_threads:
965 sys.stderr.write("warning: left-over threads found after running test:\n")
966 for t in blocking_threads:
967 sys.stderr.write('...%s\n' % repr(t))
968 raise PendingThreadsError("left-over threads found after running test")
971 from optparse import OptionParser
972 parser = OptionParser()
973 parser.add_option("--no-cleanup", dest="cleanup_workdir",
974 action="store_false", default=True,
975 help="do not delete the generated C files (allows passing --no-cython on next run)")
976 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
977 action="store_false", default=True,
978 help="do not delete the generated shared libary files (allows manual module experimentation)")
979 parser.add_option("--no-cython", dest="with_cython",
980 action="store_false", default=True,
981 help="do not run the Cython compiler, only the C compiler")
982 parser.add_option("--no-c", dest="use_c",
983 action="store_false", default=True,
984 help="do not test C compilation")
985 parser.add_option("--no-cpp", dest="use_cpp",
986 action="store_false", default=True,
987 help="do not test C++ compilation")
988 parser.add_option("--no-unit", dest="unittests",
989 action="store_false", default=True,
990 help="do not run the unit tests")
991 parser.add_option("--no-doctest", dest="doctests",
992 action="store_false", default=True,
993 help="do not run the doctests")
994 parser.add_option("--no-file", dest="filetests",
995 action="store_false", default=True,
996 help="do not run the file based tests")
997 parser.add_option("--no-pyregr", dest="pyregr",
998 action="store_false", default=True,
999 help="do not run the regression tests of CPython in tests/pyregr/")
1000 parser.add_option("--cython-only", dest="cython_only",
1001 action="store_true", default=False,
1002 help="only compile pyx to c, do not run C compiler or run the tests")
1003 parser.add_option("--no-refnanny", dest="with_refnanny",
1004 action="store_false", default=True,
1005 help="do not regression test reference counting")
1006 parser.add_option("--no-fork", dest="fork",
1007 action="store_false", default=True,
1008 help="do not fork to run tests")
1009 parser.add_option("--sys-pyregr", dest="system_pyregr",
1010 action="store_true", default=False,
1011 help="run the regression tests of the CPython installation")
1012 parser.add_option("-x", "--exclude", dest="exclude",
1013 action="append", metavar="PATTERN",
1014 help="exclude tests matching the PATTERN")
1015 parser.add_option("-C", "--coverage", dest="coverage",
1016 action="store_true", default=False,
1017 help="collect source coverage data for the Compiler")
1018 parser.add_option("--coverage-xml", dest="coverage_xml",
1019 action="store_true", default=False,
1020 help="collect source coverage data for the Compiler in XML format")
1021 parser.add_option("-A", "--annotate", dest="annotate_source",
1022 action="store_true", default=True,
1023 help="generate annotated HTML versions of the test source files")
1024 parser.add_option("--no-annotate", dest="annotate_source",
1025 action="store_false",
1026 help="do not generate annotated HTML versions of the test source files")
1027 parser.add_option("-v", "--verbose", dest="verbosity",
1028 action="count", default=0,
1029 help="display test progress, pass twice to print test names")
1030 parser.add_option("-T", "--ticket", dest="tickets",
1032 help="a bug ticket number to run the respective test in 'tests/*'")
1033 parser.add_option("-3", dest="language_level",
1034 action="store_const", const=3, default=2,
1035 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1036 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1037 help="write test results in XML to directory DIR")
1038 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1039 action="store_true",
1040 help="exit without error code even on test failures")
1042 options, cmd_args = parser.parse_args()
1044 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1045 ROOTDIR = os.path.join(DISTDIR, 'tests')
1046 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
1048 if sys.version_info[0] >= 3:
1049 options.doctests = False
1050 if options.with_cython:
1052 # try if Cython is installed in a Py3 version
1053 import Cython.Compiler.Main
1055 # back out anything the import process loaded, then
1056 # 2to3 the Cython sources to make them re-importable
1057 cy_modules = [ name for name in sys.modules
1058 if name == 'Cython' or name.startswith('Cython.') ]
1059 for name in cy_modules:
1060 del sys.modules[name]
1061 # hasn't been refactored yet - do it now
1062 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1063 if sys.version_info >= (3,1):
1064 refactor_for_py3(DISTDIR, cy3_dir)
1065 elif os.path.isdir(cy3_dir):
1066 sys.path.insert(0, cy3_dir)
1068 options.with_cython = False
1070 WITH_CYTHON = options.with_cython
1072 if options.coverage or options.coverage_xml:
1074 options.coverage = options.coverage_xml = False
1076 from coverage import coverage as _coverage
1077 coverage = _coverage(branch=True)
1082 global CompilationOptions, pyrex_default_options, cython_compile
1083 from Cython.Compiler.Main import \
1084 CompilationOptions, \
1085 default_options as pyrex_default_options, \
1086 compile as cython_compile
1087 from Cython.Compiler import Errors
1088 Errors.LEVEL = 0 # show all warnings
1089 from Cython.Compiler import Options
1090 Options.generate_cleanup_code = 3 # complete cleanup code
1091 from Cython.Compiler import DebugFlags
1092 DebugFlags.debug_temp_code_comments = 1
1095 UNITTEST_MODULE = "Cython"
1096 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1098 if os.path.exists(WORKDIR):
1099 for path in os.listdir(WORKDIR):
1100 if path in ("support", "Cy3"): continue
1101 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1102 if not os.path.exists(WORKDIR):
1103 os.makedirs(WORKDIR)
1105 sys.stderr.write("Python %s\n" % sys.version)
1106 sys.stderr.write("\n")
1108 from Cython.Compiler.Version import version
1109 sys.stderr.write("Running tests against Cython %s\n" % version)
1111 sys.stderr.write("Running tests without Cython.\n")
1113 if options.with_refnanny:
1114 from pyximport.pyxbuild import pyx_to_dll
1115 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1117 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1118 sys.path.insert(0, os.path.split(libpath)[0])
1119 CFLAGS.append("-DCYTHON_REFNANNY=1")
1121 if options.xml_output_dir and options.fork:
1122 # doesn't currently work together
1123 sys.stderr.write("Disabling forked testing to support XML test output\n")
1124 options.fork = False
1126 if WITH_CYTHON and options.language_level == 3:
1127 sys.stderr.write("Using Cython language level 3.\n")
1129 sys.stderr.write("\n")
1133 for ticket_number in options.tickets:
1135 cmd_args.append('.*T%s$' % ticket_number)
1137 for selector in cmd_args:
1138 if selector.startswith('bugs'):
1142 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1144 selectors = [ lambda x:True ]
1146 # Chech which external modules are not present and exclude tests
1147 # which depends on them (by prefix)
1149 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1150 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1151 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1154 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1157 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1159 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1160 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1164 languages.append('c')
1166 languages.append('cpp')
1168 test_suite = unittest.TestSuite()
1170 if options.unittests:
1171 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1173 if options.doctests:
1174 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1176 if options.filetests and languages:
1177 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1178 options.annotate_source, options.cleanup_workdir,
1179 options.cleanup_sharedlibs, options.pyregr,
1180 options.cython_only, languages, test_bugs,
1181 options.fork, options.language_level)
1182 test_suite.addTest(filetests.build_suite())
1184 if options.system_pyregr and languages:
1185 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1186 options.annotate_source, options.cleanup_workdir,
1187 options.cleanup_sharedlibs, True,
1188 options.cython_only, languages, test_bugs,
1189 options.fork, options.language_level)
1191 filetests.handle_directory(
1192 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1195 if options.xml_output_dir:
1196 from Cython.Tests.xmlrunner import XMLTestRunner
1197 test_runner = XMLTestRunner(output=options.xml_output_dir,
1198 verbose=options.verbosity > 0)
1200 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1202 result = test_runner.run(test_suite)
1204 if options.coverage or options.coverage_xml:
1206 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1207 modules = [ module for name, module in sys.modules.items()
1208 if module is not None and
1209 name.startswith('Cython.Compiler.') and
1210 name[len('Cython.Compiler.'):] not in ignored_modules ]
1211 if options.coverage:
1212 coverage.report(modules, show_missing=0)
1213 if options.coverage_xml:
1214 coverage.xml_report(modules, outfile="coverage-report.xml")
1216 if missing_dep_excluder.tests_missing_deps:
1217 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1218 for test in missing_dep_excluder.tests_missing_deps:
1219 sys.stderr.write(" %s\n" % test)
1221 if options.with_refnanny:
1223 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1230 return_code = not result.wasSuccessful()
1233 check_thread_termination(ignore_seen=False)
1234 sys.exit(return_code)
1235 except PendingThreadsError:
1236 # normal program exit won't kill the threads, do it the hard way here
1237 os._exit(return_code)
1239 if __name__ == '__main__':
1242 except SystemExit: # <= Py2.4 ...
1245 traceback.print_exc()
1247 check_thread_termination(ignore_seen=False)
1248 except PendingThreadsError:
1249 # normal program exit won't kill the threads, do it the hard way here