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 extra_compile_options=None):
347 include_dirs = INCLUDE_DIRS[:]
349 include_dirs.append(incdir)
350 source = self.find_module_source_file(
351 os.path.join(test_directory, module + '.pyx'))
352 target = os.path.join(targetdir, self.build_target_filename(module))
354 if extra_compile_options is None:
355 extra_compile_options = {}
360 from Cython.Compiler.Main import CompilationOptions
361 from Cython.Compiler.Main import compile as cython_compile
362 from Cython.Compiler.Main import default_options
364 options = CompilationOptions(
366 include_path = include_dirs,
367 output_file = target,
369 use_listing_file = False,
370 cplus = self.language == 'cpp',
371 language_level = self.language_level,
372 generate_pxi = False,
373 evaluate_tree_assertions = True,
374 **extra_compile_options
376 cython_compile(source, options=options,
377 full_module_name=module)
379 def run_distutils(self, test_directory, module, workdir, incdir,
380 extra_extension_args=None):
384 build_extension = build_ext(distutils_distro)
385 build_extension.include_dirs = INCLUDE_DIRS[:]
387 build_extension.include_dirs.append(incdir)
388 build_extension.finalize_options()
389 ext_include_dirs = []
390 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
392 ext_include_dirs += get_additional_include_dirs()
393 self.copy_related_files(test_directory, workdir, module)
395 if extra_extension_args is None:
396 extra_extension_args = {}
398 extension = Extension(
400 sources = self.find_source_files(workdir, module),
401 include_dirs = ext_include_dirs,
402 extra_compile_args = CFLAGS,
403 **extra_extension_args
405 if self.language == 'cpp':
406 extension.language = 'c++'
407 build_extension.extensions = [extension]
408 build_extension.build_temp = workdir
409 build_extension.build_lib = workdir
410 build_extension.run()
414 def compile(self, test_directory, module, workdir, incdir,
415 expect_errors, annotate):
416 expected_errors = errors = ()
418 expected_errors = self.split_source_and_output(
419 test_directory, module, workdir)
420 test_directory = workdir
423 old_stderr = sys.stderr
425 sys.stderr = ErrorWriter()
426 self.run_cython(test_directory, module, workdir, incdir, annotate)
427 errors = sys.stderr.geterrors()
429 sys.stderr = old_stderr
431 if errors or expected_errors:
433 for expected, error in zip(expected_errors, errors):
434 self.assertEquals(expected, error)
435 if len(errors) < len(expected_errors):
436 expected_error = expected_errors[len(errors)]
437 self.assertEquals(expected_error, None)
438 elif len(errors) > len(expected_errors):
439 unexpected_error = errors[len(expected_errors)]
440 self.assertEquals(None, unexpected_error)
441 except AssertionError:
442 print("\n=== Expected errors: ===")
443 print('\n'.join(expected_errors))
444 print("\n\n=== Got errors: ===")
445 print('\n'.join(errors))
449 if not self.cython_only:
450 self.run_distutils(test_directory, module, workdir, incdir)
452 class CythonRunTestCase(CythonCompileTestCase):
453 def shortDescription(self):
454 return "compiling (%s) and running %s" % (self.language, self.module)
456 def run(self, result=None):
458 result = self.defaultTestResult()
459 result.startTest(self)
463 self.runCompileTest()
464 if not self.cython_only:
465 self.run_doctests(self.module, result)
467 check_thread_termination()
469 result.addError(self, sys.exc_info())
470 result.stopTest(self)
476 def run_doctests(self, module_name, result):
477 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
478 doctest.DocTestSuite(module_name).run(result)
482 # fork to make sure we do not keep the tested module loaded
483 result_handle, result_file = tempfile.mkstemp()
484 os.close(result_handle)
492 partial_result = PartialTestResult(result)
493 tests = doctest.DocTestSuite(module_name)
494 tests.run(partial_result)
498 # importing failed, try to fake a test class
500 failureException=sys.exc_info()[1],
501 _shortDescription=self.shortDescription(),
503 partial_result.addError(tests, sys.exc_info())
505 output = open(result_file, 'wb')
506 pickle.dump(partial_result.data(), output)
508 traceback.print_exc()
512 os._exit(result_code)
515 cid, result_code = os.waitpid(child_id, 0)
516 # os.waitpid returns the child's result code in the
517 # upper byte of result_code, and the signal it was
518 # killed by in the lower byte
519 if result_code & 255:
520 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
521 (module_name, result_code & 255))
522 result_code = result_code >> 8
523 if result_code in (0,1):
524 input = open(result_file, 'rb')
526 PartialTestResult.join_results(result, pickle.load(input))
530 raise Exception("Tests in module '%s' exited with status %d" %
531 (module_name, result_code))
533 try: os.unlink(result_file)
536 class PureDoctestTestCase(unittest.TestCase):
537 def __init__(self, module_name, module_path):
538 self.module_name = module_name
539 self.module_path = module_path
540 unittest.TestCase.__init__(self, 'run')
542 def shortDescription(self):
543 return "running pure doctests in %s" % self.module_name
545 def run(self, result=None):
547 result = self.defaultTestResult()
548 loaded_module_name = 'pure_doctest__' + self.module_name
549 result.startTest(self)
554 m = imp.load_source(loaded_module_name, self.module_path)
556 doctest.DocTestSuite(m).run(result)
559 if loaded_module_name in sys.modules:
560 del sys.modules[loaded_module_name]
561 check_thread_termination()
563 result.addError(self, sys.exc_info())
564 result.stopTest(self)
570 is_private_field = re.compile('^_[^_]').match
572 class _FakeClass(object):
573 def __init__(self, **kwargs):
574 self._shortDescription = kwargs.get('module_name')
575 self.__dict__.update(kwargs)
576 def shortDescription(self):
577 return self._shortDescription
579 try: # Py2.7+ and Py3.2+
580 from unittest.runner import _TextTestResult
582 from unittest import _TextTestResult
584 class PartialTestResult(_TextTestResult):
585 def __init__(self, base_result):
586 _TextTestResult.__init__(
587 self, self._StringIO(), True,
588 base_result.dots + base_result.showAll*2)
590 def strip_error_results(self, results):
591 for test_case, error in results:
592 for attr_name in filter(is_private_field, dir(test_case)):
593 if attr_name == '_dt_test':
594 test_case._dt_test = _FakeClass(
595 name=test_case._dt_test.name)
596 elif attr_name != '_shortDescription':
597 setattr(test_case, attr_name, None)
600 self.strip_error_results(self.failures)
601 self.strip_error_results(self.errors)
602 return (self.failures, self.errors, self.testsRun,
603 self.stream.getvalue())
605 def join_results(result, data):
606 """Static method for merging the result back into the main
609 failures, errors, tests_run, output = data
611 result.stream.write(output)
612 result.errors.extend(errors)
613 result.failures.extend(failures)
614 result.testsRun += tests_run
616 join_results = staticmethod(join_results)
618 class _StringIO(StringIO):
619 def writeln(self, line):
620 self.write("%s\n" % line)
623 class CythonUnitTestCase(CythonCompileTestCase):
624 def shortDescription(self):
625 return "compiling (%s) tests in %s" % (self.language, self.module)
627 def run(self, result=None):
629 result = self.defaultTestResult()
630 result.startTest(self)
634 self.runCompileTest()
635 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
637 check_thread_termination()
639 result.addError(self, sys.exc_info())
640 result.stopTest(self)
646 include_debugger = sys.version_info[:2] > (2, 4)
648 def collect_unittests(path, module_prefix, suite, selectors):
649 def file_matches(filename):
650 return filename.startswith("Test") and filename.endswith(".py")
652 def package_matches(dirname):
653 return dirname == "Tests"
655 loader = unittest.TestLoader()
660 cython_dir = os.path.dirname(os.path.abspath(__file__))
661 skipped_dirs = [os.path.join(cython_dir, 'Cython', 'Debugger')]
663 for dirpath, dirnames, filenames in os.walk(path):
664 if dirpath != path and "__init__.py" not in filenames:
665 skipped_dirs.append(dirpath + os.path.sep)
668 for dir in skipped_dirs:
669 if dirpath.startswith(dir):
673 parentname = os.path.split(dirpath)[-1]
674 if package_matches(parentname):
677 filepath = os.path.join(dirpath, f)[:-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 suite.addTests([loader.loadTestsFromModule(module)])
688 def collect_doctests(path, module_prefix, suite, selectors):
689 def package_matches(dirname):
690 if dirname == 'Debugger' and not include_debugger:
692 return dirname not in ("Mac", "Distutils", "Plex")
693 def file_matches(filename):
694 filename, ext = os.path.splitext(filename)
695 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
697 return (ext == '.py' and not
698 '~' in filename and not
699 '#' in filename and not
700 filename.startswith('.') and not
701 filename in blacklist)
702 import doctest, types
703 for dirpath, dirnames, filenames in os.walk(path):
704 parentname = os.path.split(dirpath)[-1]
705 if package_matches(parentname):
708 if not f.endswith('.py'): continue
709 filepath = os.path.join(dirpath, f)
710 if os.path.getsize(filepath) == 0: continue
711 if 'no doctest' in open(filepath).next(): continue
712 filepath = filepath[:-len(".py")]
713 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
714 if not [ 1 for match in selectors if match(modulename) ]:
716 module = __import__(modulename)
717 for x in modulename.split('.')[1:]:
718 module = getattr(module, x)
719 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
721 suite.addTest(doctest.DocTestSuite(module))
722 except ValueError: # no tests
726 class EndToEndTest(unittest.TestCase):
728 This is a test of build/*.srctree files, where srctree defines a full
729 directory structure and its header gives a list of commands to run.
731 cython_root = os.path.dirname(os.path.abspath(__file__))
733 def __init__(self, treefile, workdir, cleanup_workdir=True):
734 self.treefile = treefile
735 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
736 self.cleanup_workdir = cleanup_workdir
737 cython_syspath = self.cython_root
738 for path in sys.path[::-1]:
739 if path.startswith(self.cython_root):
740 # Py3 installation and refnanny build prepend their
741 # fixed paths to sys.path => prefer that over the
743 cython_syspath = path + os.pathsep + cython_syspath
744 self.cython_syspath = cython_syspath
745 unittest.TestCase.__init__(self)
747 def shortDescription(self):
748 return "End-to-end %s" % self.treefile
751 from Cython.TestUtils import unpack_source_tree
752 _, self.commands = unpack_source_tree(
753 os.path.join('tests', 'build', self.treefile), self.workdir)
754 self.old_dir = os.getcwd()
755 os.chdir(self.workdir)
756 if self.workdir not in sys.path:
757 sys.path.insert(0, self.workdir)
760 if self.cleanup_workdir:
761 shutil.rmtree(self.workdir)
762 os.chdir(self.old_dir)
765 commands = (self.commands
766 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
767 .replace("PYTHON", sys.executable))
769 old_path = os.environ.get('PYTHONPATH')
770 os.environ['PYTHONPATH'] = os.path.join(self.cython_syspath, (old_path or ''))
771 for command in commands.split('\n'):
772 if sys.version_info[:2] >= (2,4):
774 p = subprocess.Popen(commands,
775 stderr=subprocess.PIPE,
776 stdout=subprocess.PIPE,
778 out, err = p.communicate()
785 res = os.system(command)
786 self.assertEqual(0, res, "non-zero exit status")
789 os.environ['PYTHONPATH'] = old_path
791 del os.environ['PYTHONPATH']
794 # TODO: Support cython_freeze needed here as well.
795 # TODO: Windows support.
797 class EmbedTest(unittest.TestCase):
799 working_dir = "Demos/embed"
802 self.old_dir = os.getcwd()
803 os.chdir(self.working_dir)
805 "make PYTHON='%s' clean > /dev/null" % sys.executable)
810 "make PYTHON='%s' clean > /dev/null" % sys.executable)
813 os.chdir(self.old_dir)
815 def test_embed(self):
816 from distutils import sysconfig
817 libname = sysconfig.get_config_var('LIBRARY')
818 libdir = sysconfig.get_config_var('LIBDIR')
819 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
820 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
821 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
822 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
823 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
824 # report the error for the original directory
825 libdir = sysconfig.get_config_var('LIBDIR')
826 self.assert_(os.system(
827 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
829 os.remove('make.output')
833 class MissingDependencyExcluder:
834 def __init__(self, deps):
835 # deps: { module name : matcher func }
836 self.exclude_matchers = []
837 for mod, matcher in deps.items():
841 self.exclude_matchers.append(matcher)
842 self.tests_missing_deps = []
843 def __call__(self, testname):
844 for matcher in self.exclude_matchers:
845 if matcher(testname):
846 self.tests_missing_deps.append(testname)
850 class VersionDependencyExcluder:
851 def __init__(self, deps):
852 # deps: { version : matcher func }
853 from sys import version_info
854 self.exclude_matchers = []
855 for ver, (compare, matcher) in deps.items():
856 if compare(version_info, ver):
857 self.exclude_matchers.append(matcher)
858 self.tests_missing_deps = []
859 def __call__(self, testname):
860 for matcher in self.exclude_matchers:
861 if matcher(testname):
862 self.tests_missing_deps.append(testname)
866 class FileListExcluder:
868 def __init__(self, list_file):
872 for line in f.readlines():
874 if line and line[0] != '#':
875 self.excludes[line.split()[0]] = True
879 def __call__(self, testname):
880 return testname in self.excludes or testname.split('.')[-1] in self.excludes
882 def refactor_for_py3(distdir, cy3_dir):
883 # need to convert Cython sources first
884 import lib2to3.refactor
885 from distutils.util import copydir_run_2to3
886 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
887 if fix.split('fix_')[-1] not in ('next',)
889 if not os.path.exists(cy3_dir):
891 import distutils.log as dlog
892 dlog.set_threshold(dlog.INFO)
893 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
897 recursive-exclude Cython *
898 recursive-include Cython *.py *.pyx *.pxd
900 sys.path.insert(0, cy3_dir)
902 class PendingThreadsError(RuntimeError):
907 def check_thread_termination(ignore_seen=True):
908 if threading is None: # no threading enabled in CPython
910 current = threading.currentThread()
911 blocking_threads = []
912 for t in threading.enumerate():
913 if not t.isAlive() or t == current:
918 blocking_threads.append(t)
920 for seen in threads_seen:
924 threads_seen.append(t)
925 blocking_threads.append(t)
926 if not blocking_threads:
928 sys.stderr.write("warning: left-over threads found after running test:\n")
929 for t in blocking_threads:
930 sys.stderr.write('...%s\n' % repr(t))
931 raise PendingThreadsError("left-over threads found after running test")
934 from optparse import OptionParser
935 parser = OptionParser()
936 parser.add_option("--no-cleanup", dest="cleanup_workdir",
937 action="store_false", default=True,
938 help="do not delete the generated C files (allows passing --no-cython on next run)")
939 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
940 action="store_false", default=True,
941 help="do not delete the generated shared libary files (allows manual module experimentation)")
942 parser.add_option("--no-cython", dest="with_cython",
943 action="store_false", default=True,
944 help="do not run the Cython compiler, only the C compiler")
945 parser.add_option("--no-c", dest="use_c",
946 action="store_false", default=True,
947 help="do not test C compilation")
948 parser.add_option("--no-cpp", dest="use_cpp",
949 action="store_false", default=True,
950 help="do not test C++ compilation")
951 parser.add_option("--no-unit", dest="unittests",
952 action="store_false", default=True,
953 help="do not run the unit tests")
954 parser.add_option("--no-doctest", dest="doctests",
955 action="store_false", default=True,
956 help="do not run the doctests")
957 parser.add_option("--no-file", dest="filetests",
958 action="store_false", default=True,
959 help="do not run the file based tests")
960 parser.add_option("--no-pyregr", dest="pyregr",
961 action="store_false", default=True,
962 help="do not run the regression tests of CPython in tests/pyregr/")
963 parser.add_option("--cython-only", dest="cython_only",
964 action="store_true", default=False,
965 help="only compile pyx to c, do not run C compiler or run the tests")
966 parser.add_option("--no-refnanny", dest="with_refnanny",
967 action="store_false", default=True,
968 help="do not regression test reference counting")
969 parser.add_option("--no-fork", dest="fork",
970 action="store_false", default=True,
971 help="do not fork to run tests")
972 parser.add_option("--sys-pyregr", dest="system_pyregr",
973 action="store_true", default=False,
974 help="run the regression tests of the CPython installation")
975 parser.add_option("-x", "--exclude", dest="exclude",
976 action="append", metavar="PATTERN",
977 help="exclude tests matching the PATTERN")
978 parser.add_option("-C", "--coverage", dest="coverage",
979 action="store_true", default=False,
980 help="collect source coverage data for the Compiler")
981 parser.add_option("--coverage-xml", dest="coverage_xml",
982 action="store_true", default=False,
983 help="collect source coverage data for the Compiler in XML format")
984 parser.add_option("-A", "--annotate", dest="annotate_source",
985 action="store_true", default=True,
986 help="generate annotated HTML versions of the test source files")
987 parser.add_option("--no-annotate", dest="annotate_source",
988 action="store_false",
989 help="do not generate annotated HTML versions of the test source files")
990 parser.add_option("-v", "--verbose", dest="verbosity",
991 action="count", default=0,
992 help="display test progress, pass twice to print test names")
993 parser.add_option("-T", "--ticket", dest="tickets",
995 help="a bug ticket number to run the respective test in 'tests/*'")
996 parser.add_option("-3", dest="language_level",
997 action="store_const", const=3, default=2,
998 help="set language level to Python 3 (useful for running the CPython regression tests)'")
999 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1000 help="write test results in XML to directory DIR")
1001 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1002 action="store_true",
1003 help="exit without error code even on test failures")
1005 options, cmd_args = parser.parse_args()
1007 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1008 ROOTDIR = os.path.join(DISTDIR, 'tests')
1009 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
1011 if sys.version_info[0] >= 3:
1012 options.doctests = False
1013 if options.with_cython:
1015 # try if Cython is installed in a Py3 version
1016 import Cython.Compiler.Main
1018 # back out anything the import process loaded, then
1019 # 2to3 the Cython sources to make them re-importable
1020 cy_modules = [ name for name in sys.modules
1021 if name == 'Cython' or name.startswith('Cython.') ]
1022 for name in cy_modules:
1023 del sys.modules[name]
1024 # hasn't been refactored yet - do it now
1025 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1026 if sys.version_info >= (3,1):
1027 refactor_for_py3(DISTDIR, cy3_dir)
1028 elif os.path.isdir(cy3_dir):
1029 sys.path.insert(0, cy3_dir)
1031 options.with_cython = False
1033 WITH_CYTHON = options.with_cython
1035 if options.coverage or options.coverage_xml:
1037 options.coverage = options.coverage_xml = False
1039 from coverage import coverage as _coverage
1040 coverage = _coverage(branch=True)
1045 global CompilationOptions, pyrex_default_options, cython_compile
1046 from Cython.Compiler.Main import \
1047 CompilationOptions, \
1048 default_options as pyrex_default_options, \
1049 compile as cython_compile
1050 from Cython.Compiler import Errors
1051 Errors.LEVEL = 0 # show all warnings
1052 from Cython.Compiler import Options
1053 Options.generate_cleanup_code = 3 # complete cleanup code
1054 from Cython.Compiler import DebugFlags
1055 DebugFlags.debug_temp_code_comments = 1
1058 UNITTEST_MODULE = "Cython"
1059 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1061 if os.path.exists(WORKDIR):
1062 for path in os.listdir(WORKDIR):
1063 if path in ("support", "Cy3"): continue
1064 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1065 if not os.path.exists(WORKDIR):
1066 os.makedirs(WORKDIR)
1068 sys.stderr.write("Python %s\n" % sys.version)
1069 sys.stderr.write("\n")
1071 from Cython.Compiler.Version import version
1072 sys.stderr.write("Running tests against Cython %s\n" % version)
1074 sys.stderr.write("Running tests without Cython.\n")
1076 if options.with_refnanny:
1077 from pyximport.pyxbuild import pyx_to_dll
1078 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1080 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1081 sys.path.insert(0, os.path.split(libpath)[0])
1082 CFLAGS.append("-DCYTHON_REFNANNY=1")
1084 if options.xml_output_dir and options.fork:
1085 # doesn't currently work together
1086 sys.stderr.write("Disabling forked testing to support XML test output\n")
1087 options.fork = False
1089 if WITH_CYTHON and options.language_level == 3:
1090 sys.stderr.write("Using Cython language level 3.\n")
1092 sys.stderr.write("\n")
1096 for ticket_number in options.tickets:
1098 cmd_args.append('.*T%s$' % ticket_number)
1100 for selector in cmd_args:
1101 if selector.startswith('bugs'):
1105 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1107 selectors = [ lambda x:True ]
1109 # Chech which external modules are not present and exclude tests
1110 # which depends on them (by prefix)
1112 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1113 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1114 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1117 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1120 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1122 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1123 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1127 languages.append('c')
1129 languages.append('cpp')
1131 test_suite = unittest.TestSuite()
1133 if options.unittests:
1134 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1136 if options.doctests:
1137 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1139 if options.filetests and languages:
1140 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1141 options.annotate_source, options.cleanup_workdir,
1142 options.cleanup_sharedlibs, options.pyregr,
1143 options.cython_only, languages, test_bugs,
1144 options.fork, options.language_level)
1145 test_suite.addTest(filetests.build_suite())
1147 if options.system_pyregr and languages:
1148 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1149 options.annotate_source, options.cleanup_workdir,
1150 options.cleanup_sharedlibs, True,
1151 options.cython_only, languages, test_bugs,
1152 options.fork, options.language_level)
1154 filetests.handle_directory(
1155 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1158 if options.xml_output_dir:
1159 from Cython.Tests.xmlrunner import XMLTestRunner
1160 test_runner = XMLTestRunner(output=options.xml_output_dir,
1161 verbose=options.verbosity > 0)
1163 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1165 result = test_runner.run(test_suite)
1167 if options.coverage or options.coverage_xml:
1169 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1170 modules = [ module for name, module in sys.modules.items()
1171 if module is not None and
1172 name.startswith('Cython.Compiler.') and
1173 name[len('Cython.Compiler.'):] not in ignored_modules ]
1174 if options.coverage:
1175 coverage.report(modules, show_missing=0)
1176 if options.coverage_xml:
1177 coverage.xml_report(modules, outfile="coverage-report.xml")
1179 if missing_dep_excluder.tests_missing_deps:
1180 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1181 for test in missing_dep_excluder.tests_missing_deps:
1182 sys.stderr.write(" %s\n" % test)
1184 if options.with_refnanny:
1186 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1193 return_code = not result.wasSuccessful()
1196 check_thread_termination(ignore_seen=False)
1197 sys.exit(return_code)
1198 except PendingThreadsError:
1199 # normal program exit won't kill the threads, do it the hard way here
1200 os._exit(return_code)
1202 if __name__ == '__main__':
1205 except SystemExit: # <= Py2.4 ...
1208 traceback.print_exc()
1210 check_thread_termination(ignore_seen=False)
1211 except PendingThreadsError:
1212 # normal program exit won't kill the threads, do it the hard way here