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')
678 include_debugger = sys.version_info[:2] > (2, 5)
680 def collect_unittests(path, module_prefix, suite, selectors):
681 def file_matches(filename):
682 return filename.startswith("Test") and filename.endswith(".py")
684 def package_matches(dirname):
685 return dirname == "Tests"
687 loader = unittest.TestLoader()
692 cython_dir = os.path.dirname(os.path.abspath(__file__))
693 skipped_dirs = [os.path.join(cython_dir, 'Cython', 'Debugger')]
695 for dirpath, dirnames, filenames in os.walk(path):
696 if dirpath != path and "__init__.py" not in filenames:
697 skipped_dirs.append(dirpath + os.path.sep)
700 for dir in skipped_dirs:
701 if dirpath.startswith(dir):
705 parentname = os.path.split(dirpath)[-1]
706 if package_matches(parentname):
709 filepath = os.path.join(dirpath, f)[:-len(".py")]
710 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
711 if not [ 1 for match in selectors if match(modulename) ]:
713 module = __import__(modulename)
714 for x in modulename.split('.')[1:]:
715 module = getattr(module, x)
716 suite.addTests([loader.loadTestsFromModule(module)])
720 def collect_doctests(path, module_prefix, suite, selectors):
721 def package_matches(dirname):
722 if dirname == 'Debugger' and not include_debugger:
724 return dirname not in ("Mac", "Distutils", "Plex")
725 def file_matches(filename):
726 filename, ext = os.path.splitext(filename)
727 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
729 return (ext == '.py' and not
730 '~' in filename and not
731 '#' in filename and not
732 filename.startswith('.') and not
733 filename in blacklist)
734 import doctest, types
735 for dirpath, dirnames, filenames in os.walk(path):
736 for dir in list(dirnames):
737 if not package_matches(dir):
741 if not f.endswith('.py'): continue
742 filepath = os.path.join(dirpath, f)
743 if os.path.getsize(filepath) == 0: continue
744 filepath = filepath[:-len(".py")]
745 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
746 if not [ 1 for match in selectors if match(modulename) ]:
748 if 'in_gdb' in modulename:
749 # These should only be imported from gdb.
751 module = __import__(modulename)
752 for x in modulename.split('.')[1:]:
753 module = getattr(module, x)
754 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
756 suite.addTest(doctest.DocTestSuite(module))
757 except ValueError: # no tests
761 class EndToEndTest(unittest.TestCase):
763 This is a test of build/*.srctree files, where srctree defines a full
764 directory structure and its header gives a list of commands to run.
766 cython_root = os.path.dirname(os.path.abspath(__file__))
768 def __init__(self, treefile, workdir, cleanup_workdir=True):
769 self.treefile = treefile
770 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
771 self.cleanup_workdir = cleanup_workdir
772 cython_syspath = self.cython_root
773 for path in sys.path[::-1]:
774 if path.startswith(self.cython_root):
775 # Py3 installation and refnanny build prepend their
776 # fixed paths to sys.path => prefer that over the
778 cython_syspath = path + os.pathsep + cython_syspath
779 self.cython_syspath = cython_syspath
780 unittest.TestCase.__init__(self)
782 def shortDescription(self):
783 return "End-to-end %s" % self.treefile
786 from Cython.TestUtils import unpack_source_tree
787 _, self.commands = unpack_source_tree(
788 os.path.join('tests', 'build', self.treefile), self.workdir)
789 self.old_dir = os.getcwd()
790 os.chdir(self.workdir)
791 if self.workdir not in sys.path:
792 sys.path.insert(0, self.workdir)
795 if self.cleanup_workdir:
796 shutil.rmtree(self.workdir)
797 os.chdir(self.old_dir)
800 commands = (self.commands
801 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
802 .replace("PYTHON", sys.executable))
804 old_path = os.environ.get('PYTHONPATH')
805 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
806 for command in commands.split('\n'):
807 if sys.version_info[:2] >= (2,4):
809 p = subprocess.Popen(commands,
810 stderr=subprocess.PIPE,
811 stdout=subprocess.PIPE,
813 out, err = p.communicate()
820 res = os.system(command)
821 self.assertEqual(0, res, "non-zero exit status")
824 os.environ['PYTHONPATH'] = old_path
826 del os.environ['PYTHONPATH']
829 # TODO: Support cython_freeze needed here as well.
830 # TODO: Windows support.
832 class EmbedTest(unittest.TestCase):
834 working_dir = "Demos/embed"
837 self.old_dir = os.getcwd()
838 os.chdir(self.working_dir)
840 "make PYTHON='%s' clean > /dev/null" % sys.executable)
845 "make PYTHON='%s' clean > /dev/null" % sys.executable)
848 os.chdir(self.old_dir)
850 def test_embed(self):
851 from distutils import sysconfig
852 libname = sysconfig.get_config_var('LIBRARY')
853 libdir = sysconfig.get_config_var('LIBDIR')
854 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
855 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
856 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
857 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
858 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
859 # report the error for the original directory
860 libdir = sysconfig.get_config_var('LIBDIR')
861 self.assert_(os.system(
862 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
864 os.remove('make.output')
868 class MissingDependencyExcluder:
869 def __init__(self, deps):
870 # deps: { module name : matcher func }
871 self.exclude_matchers = []
872 for mod, matcher in deps.items():
876 self.exclude_matchers.append(matcher)
877 self.tests_missing_deps = []
878 def __call__(self, testname):
879 for matcher in self.exclude_matchers:
880 if matcher(testname):
881 self.tests_missing_deps.append(testname)
885 class VersionDependencyExcluder:
886 def __init__(self, deps):
887 # deps: { version : matcher func }
888 from sys import version_info
889 self.exclude_matchers = []
890 for ver, (compare, matcher) in deps.items():
891 if compare(version_info, ver):
892 self.exclude_matchers.append(matcher)
893 self.tests_missing_deps = []
894 def __call__(self, testname):
895 for matcher in self.exclude_matchers:
896 if matcher(testname):
897 self.tests_missing_deps.append(testname)
901 class FileListExcluder:
903 def __init__(self, list_file):
907 for line in f.readlines():
909 if line and line[0] != '#':
910 self.excludes[line.split()[0]] = True
914 def __call__(self, testname):
915 return testname in self.excludes or testname.split('.')[-1] in self.excludes
917 def refactor_for_py3(distdir, cy3_dir):
918 # need to convert Cython sources first
919 import lib2to3.refactor
920 from distutils.util import copydir_run_2to3
921 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
922 if fix.split('fix_')[-1] not in ('next',)
924 if not os.path.exists(cy3_dir):
926 import distutils.log as dlog
927 dlog.set_threshold(dlog.INFO)
928 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
932 recursive-exclude Cython *
933 recursive-include Cython *.py *.pyx *.pxd
934 recursive-include Cython/Debugger/Tests *
936 sys.path.insert(0, cy3_dir)
938 class PendingThreadsError(RuntimeError):
943 def check_thread_termination(ignore_seen=True):
944 if threading is None: # no threading enabled in CPython
946 current = threading.currentThread()
947 blocking_threads = []
948 for t in threading.enumerate():
949 if not t.isAlive() or t == current:
954 blocking_threads.append(t)
956 for seen in threads_seen:
960 threads_seen.append(t)
961 blocking_threads.append(t)
962 if not blocking_threads:
964 sys.stderr.write("warning: left-over threads found after running test:\n")
965 for t in blocking_threads:
966 sys.stderr.write('...%s\n' % repr(t))
967 raise PendingThreadsError("left-over threads found after running test")
970 from optparse import OptionParser
971 parser = OptionParser()
972 parser.add_option("--no-cleanup", dest="cleanup_workdir",
973 action="store_false", default=True,
974 help="do not delete the generated C files (allows passing --no-cython on next run)")
975 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
976 action="store_false", default=True,
977 help="do not delete the generated shared libary files (allows manual module experimentation)")
978 parser.add_option("--no-cython", dest="with_cython",
979 action="store_false", default=True,
980 help="do not run the Cython compiler, only the C compiler")
981 parser.add_option("--no-c", dest="use_c",
982 action="store_false", default=True,
983 help="do not test C compilation")
984 parser.add_option("--no-cpp", dest="use_cpp",
985 action="store_false", default=True,
986 help="do not test C++ compilation")
987 parser.add_option("--no-unit", dest="unittests",
988 action="store_false", default=True,
989 help="do not run the unit tests")
990 parser.add_option("--no-doctest", dest="doctests",
991 action="store_false", default=True,
992 help="do not run the doctests")
993 parser.add_option("--no-file", dest="filetests",
994 action="store_false", default=True,
995 help="do not run the file based tests")
996 parser.add_option("--no-pyregr", dest="pyregr",
997 action="store_false", default=True,
998 help="do not run the regression tests of CPython in tests/pyregr/")
999 parser.add_option("--cython-only", dest="cython_only",
1000 action="store_true", default=False,
1001 help="only compile pyx to c, do not run C compiler or run the tests")
1002 parser.add_option("--no-refnanny", dest="with_refnanny",
1003 action="store_false", default=True,
1004 help="do not regression test reference counting")
1005 parser.add_option("--no-fork", dest="fork",
1006 action="store_false", default=True,
1007 help="do not fork to run tests")
1008 parser.add_option("--sys-pyregr", dest="system_pyregr",
1009 action="store_true", default=False,
1010 help="run the regression tests of the CPython installation")
1011 parser.add_option("-x", "--exclude", dest="exclude",
1012 action="append", metavar="PATTERN",
1013 help="exclude tests matching the PATTERN")
1014 parser.add_option("-C", "--coverage", dest="coverage",
1015 action="store_true", default=False,
1016 help="collect source coverage data for the Compiler")
1017 parser.add_option("--coverage-xml", dest="coverage_xml",
1018 action="store_true", default=False,
1019 help="collect source coverage data for the Compiler in XML format")
1020 parser.add_option("-A", "--annotate", dest="annotate_source",
1021 action="store_true", default=True,
1022 help="generate annotated HTML versions of the test source files")
1023 parser.add_option("--no-annotate", dest="annotate_source",
1024 action="store_false",
1025 help="do not generate annotated HTML versions of the test source files")
1026 parser.add_option("-v", "--verbose", dest="verbosity",
1027 action="count", default=0,
1028 help="display test progress, pass twice to print test names")
1029 parser.add_option("-T", "--ticket", dest="tickets",
1031 help="a bug ticket number to run the respective test in 'tests/*'")
1032 parser.add_option("-3", dest="language_level",
1033 action="store_const", const=3, default=2,
1034 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1035 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1036 help="write test results in XML to directory DIR")
1037 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1038 action="store_true",
1039 help="exit without error code even on test failures")
1041 options, cmd_args = parser.parse_args()
1043 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1044 ROOTDIR = os.path.join(DISTDIR, 'tests')
1045 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
1047 if sys.version_info[0] >= 3:
1048 options.doctests = False
1049 if options.with_cython:
1051 # try if Cython is installed in a Py3 version
1052 import Cython.Compiler.Main
1054 # back out anything the import process loaded, then
1055 # 2to3 the Cython sources to make them re-importable
1056 cy_modules = [ name for name in sys.modules
1057 if name == 'Cython' or name.startswith('Cython.') ]
1058 for name in cy_modules:
1059 del sys.modules[name]
1060 # hasn't been refactored yet - do it now
1061 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1062 if sys.version_info >= (3,1):
1063 refactor_for_py3(DISTDIR, cy3_dir)
1064 elif os.path.isdir(cy3_dir):
1065 sys.path.insert(0, cy3_dir)
1067 options.with_cython = False
1069 WITH_CYTHON = options.with_cython
1071 if options.coverage or options.coverage_xml:
1073 options.coverage = options.coverage_xml = False
1075 from coverage import coverage as _coverage
1076 coverage = _coverage(branch=True)
1081 global CompilationOptions, pyrex_default_options, cython_compile
1082 from Cython.Compiler.Main import \
1083 CompilationOptions, \
1084 default_options as pyrex_default_options, \
1085 compile as cython_compile
1086 from Cython.Compiler import Errors
1087 Errors.LEVEL = 0 # show all warnings
1088 from Cython.Compiler import Options
1089 Options.generate_cleanup_code = 3 # complete cleanup code
1090 from Cython.Compiler import DebugFlags
1091 DebugFlags.debug_temp_code_comments = 1
1094 UNITTEST_MODULE = "Cython"
1095 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1097 if os.path.exists(WORKDIR):
1098 for path in os.listdir(WORKDIR):
1099 if path in ("support", "Cy3"): continue
1100 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1101 if not os.path.exists(WORKDIR):
1102 os.makedirs(WORKDIR)
1104 sys.stderr.write("Python %s\n" % sys.version)
1105 sys.stderr.write("\n")
1107 from Cython.Compiler.Version import version
1108 sys.stderr.write("Running tests against Cython %s\n" % version)
1110 sys.stderr.write("Running tests without Cython.\n")
1112 if options.with_refnanny:
1113 from pyximport.pyxbuild import pyx_to_dll
1114 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1116 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1117 sys.path.insert(0, os.path.split(libpath)[0])
1118 CFLAGS.append("-DCYTHON_REFNANNY=1")
1120 if options.xml_output_dir and options.fork:
1121 # doesn't currently work together
1122 sys.stderr.write("Disabling forked testing to support XML test output\n")
1123 options.fork = False
1125 if WITH_CYTHON and options.language_level == 3:
1126 sys.stderr.write("Using Cython language level 3.\n")
1128 sys.stderr.write("\n")
1132 for ticket_number in options.tickets:
1134 cmd_args.append('.*T%s$' % ticket_number)
1136 for selector in cmd_args:
1137 if selector.startswith('bugs'):
1141 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1143 selectors = [ lambda x:True ]
1145 # Chech which external modules are not present and exclude tests
1146 # which depends on them (by prefix)
1148 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1149 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1150 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1153 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1156 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1158 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1159 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1163 languages.append('c')
1165 languages.append('cpp')
1167 test_suite = unittest.TestSuite()
1169 if options.unittests:
1170 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1172 if options.doctests:
1173 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1175 if options.filetests and languages:
1176 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1177 options.annotate_source, options.cleanup_workdir,
1178 options.cleanup_sharedlibs, options.pyregr,
1179 options.cython_only, languages, test_bugs,
1180 options.fork, options.language_level)
1181 test_suite.addTest(filetests.build_suite())
1183 if options.system_pyregr and languages:
1184 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1185 options.annotate_source, options.cleanup_workdir,
1186 options.cleanup_sharedlibs, True,
1187 options.cython_only, languages, test_bugs,
1188 options.fork, options.language_level)
1190 filetests.handle_directory(
1191 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1194 if options.xml_output_dir:
1195 from Cython.Tests.xmlrunner import XMLTestRunner
1196 test_runner = XMLTestRunner(output=options.xml_output_dir,
1197 verbose=options.verbosity > 0)
1199 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1201 result = test_runner.run(test_suite)
1203 if options.coverage or options.coverage_xml:
1205 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1206 modules = [ module for name, module in sys.modules.items()
1207 if module is not None and
1208 name.startswith('Cython.Compiler.') and
1209 name[len('Cython.Compiler.'):] not in ignored_modules ]
1210 if options.coverage:
1211 coverage.report(modules, show_missing=0)
1212 if options.coverage_xml:
1213 coverage.xml_report(modules, outfile="coverage-report.xml")
1215 if missing_dep_excluder.tests_missing_deps:
1216 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1217 for test in missing_dep_excluder.tests_missing_deps:
1218 sys.stderr.write(" %s\n" % test)
1220 if options.with_refnanny:
1222 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1229 return_code = not result.wasSuccessful()
1232 check_thread_termination(ignore_seen=False)
1233 sys.exit(return_code)
1234 except PendingThreadsError:
1235 # normal program exit won't kill the threads, do it the hard way here
1236 os._exit(return_code)
1238 if __name__ == '__main__':
1241 except SystemExit: # <= Py2.4 ...
1244 traceback.print_exc()
1246 check_thread_termination(ignore_seen=False)
1247 except PendingThreadsError:
1248 # normal program exit won't kill the threads, do it the hard way here