15 from StringIO import StringIO
17 from io import StringIO
20 import cPickle as pickle
26 except ImportError: # No threads, no problems
31 from distutils.dist import Distribution
32 from distutils.core import Extension
33 from distutils.command.build_ext import build_ext as _build_ext
34 distutils_distro = Distribution()
36 if sys.platform == 'win32':
37 # TODO: Figure out why this hackery (see http://thread.gmane.org/gmane.comp.python.cython.devel/8280/).
38 config_files = distutils_distro.find_config_files()
39 try: config_files.remove('setup.cfg')
40 except ValueError: pass
41 distutils_distro.parse_config_files(config_files)
43 cfgfiles = distutils_distro.find_config_files()
44 try: cfgfiles.remove('setup.cfg')
45 except ValueError: pass
46 distutils_distro.parse_config_files(cfgfiles)
48 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr', 'build']
49 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
51 # Lists external modules, and a matcher matching tests
52 # which should be excluded if the module is not present.
54 'numpy' : re.compile('.*\.numpy_.*').match,
55 'pstats' : re.compile('.*\.pstats_.*').match,
56 'posix' : re.compile('.*\.posix_.*').match,
59 def get_numpy_include_dirs():
61 return [numpy.get_include()]
64 # test name matcher , callable returning list
65 (re.compile('numpy_.*').match, get_numpy_include_dirs),
69 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
70 # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
71 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
74 (2,5) : (operator.lt, lambda x: x in ['run.any',
77 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
79 'run.pure_py', # decorators, with statement
81 # The next line should start (3,); but this is a dictionary, so
82 # we can only have one (3,) key. Since 2.7 is supposed to be the
83 # last 2.x release, things would have to change drastically for this
85 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
86 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
87 'compile.extsetslice',
88 'compile.extdelslice',
89 'run.special_methods_T561_py2']),
92 # files that should not be converted to Python 3 code with 2to3
94 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
95 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
96 os.path.join('Cython', 'Debugger', 'libcython.py'),
97 os.path.join('Cython', 'Debugger', 'libpython.py'),
101 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
102 CFLAGS = os.getenv('CFLAGS', '').split()
104 class build_ext(_build_ext):
105 def build_extension(self, ext):
106 if ext.language == 'c++':
108 try: # Py2.7+ & Py3.2+
109 compiler_obj = self.compiler_obj
110 except AttributeError:
111 compiler_obj = self.compiler
112 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
115 _build_ext.build_extension(self, ext)
117 class ErrorWriter(object):
118 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
121 self.write = self.output.append
123 def _collect(self, collect_errors, collect_warnings):
124 s = ''.join(self.output)
126 for line in s.split('\n'):
127 match = self.match_error(line)
129 is_warning, line, column, message = match.groups()
130 if (is_warning and collect_warnings) or \
131 (not is_warning and collect_errors):
132 result.append( (int(line), int(column), message.strip()) )
134 return [ "%d:%d: %s" % values for values in result ]
137 return self._collect(True, False)
139 def getwarnings(self):
140 return self._collect(False, True)
143 return self._collect(True, True)
145 class TestBuilder(object):
146 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
147 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
148 languages, test_bugs, fork, language_level):
149 self.rootdir = rootdir
150 self.workdir = workdir
151 self.selectors = selectors
152 self.exclude_selectors = exclude_selectors
153 self.annotate = annotate
154 self.cleanup_workdir = cleanup_workdir
155 self.cleanup_sharedlibs = cleanup_sharedlibs
156 self.with_pyregr = with_pyregr
157 self.cython_only = cython_only
158 self.languages = languages
159 self.test_bugs = test_bugs
161 self.language_level = language_level
163 def build_suite(self):
164 suite = unittest.TestSuite()
165 test_dirs = TEST_DIRS
166 filenames = os.listdir(self.rootdir)
168 for filename in filenames:
169 if not WITH_CYTHON and filename == "errors":
170 # we won't get any errors without running Cython
172 path = os.path.join(self.rootdir, filename)
173 if os.path.isdir(path) and filename in test_dirs:
174 if filename == 'pyregr' and not self.with_pyregr:
177 self.handle_directory(path, filename))
178 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
179 # Non-Windows makefile, can't run Cython under Py3.
180 if [1 for selector in self.selectors if selector("embedded")]:
181 suite.addTest(unittest.makeSuite(EmbedTest))
184 def handle_directory(self, path, context):
185 workdir = os.path.join(self.workdir, context)
186 if not os.path.exists(workdir):
189 expect_errors = (context == 'errors')
190 suite = unittest.TestSuite()
191 filenames = os.listdir(path)
193 for filename in filenames:
194 if context == "build" and filename.endswith(".srctree"):
195 if not [ 1 for match in self.selectors if match(filename) ]:
197 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
199 if not (filename.endswith(".pyx") or filename.endswith(".py")):
201 if filename.startswith('.'): continue # certain emacs backup files
202 if context == 'pyregr' and not filename.startswith('test_'):
204 module = os.path.splitext(filename)[0]
205 fqmodule = "%s.%s" % (context, module)
206 if not [ 1 for match in self.selectors
207 if match(fqmodule) ]:
209 if self.exclude_selectors:
210 if [1 for match in self.exclude_selectors if match(fqmodule)]:
212 if context == 'pyregr':
213 test_class = CythonPyregrTestCase
214 elif context in TEST_RUN_DIRS:
215 if module.startswith("test_"):
216 test_class = CythonUnitTestCase
218 test_class = CythonRunTestCase
220 test_class = CythonCompileTestCase
221 for test in self.build_tests(test_class, path, workdir,
222 module, expect_errors):
224 if context == 'run' and filename.endswith('.py'):
225 # additionally test file in real Python
226 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
229 def build_tests(self, test_class, path, workdir, module, expect_errors):
231 if 'cpp' in module and 'cpp' in self.languages:
234 languages = self.languages[:1]
236 languages = self.languages
237 if 'cpp' in module and 'c' in languages:
238 languages = list(languages)
239 languages.remove('c')
240 tests = [ self.build_test(test_class, path, workdir, module,
241 language, expect_errors)
242 for language in languages ]
245 def build_test(self, test_class, path, workdir, module,
246 language, expect_errors):
247 workdir = os.path.join(workdir, language)
248 if not os.path.exists(workdir):
250 return test_class(path, workdir, module,
252 expect_errors=expect_errors,
253 annotate=self.annotate,
254 cleanup_workdir=self.cleanup_workdir,
255 cleanup_sharedlibs=self.cleanup_sharedlibs,
256 cython_only=self.cython_only,
258 language_level=self.language_level)
260 class CythonCompileTestCase(unittest.TestCase):
261 def __init__(self, test_directory, workdir, module, language='c',
262 expect_errors=False, annotate=False, cleanup_workdir=True,
263 cleanup_sharedlibs=True, cython_only=False, fork=True,
265 self.test_directory = test_directory
266 self.workdir = workdir
268 self.language = language
269 self.expect_errors = expect_errors
270 self.annotate = annotate
271 self.cleanup_workdir = cleanup_workdir
272 self.cleanup_sharedlibs = cleanup_sharedlibs
273 self.cython_only = cython_only
275 self.language_level = language_level
276 unittest.TestCase.__init__(self)
278 def shortDescription(self):
279 return "compiling (%s) %s" % (self.language, self.module)
282 if self.workdir not in sys.path:
283 sys.path.insert(0, self.workdir)
287 sys.path.remove(self.workdir)
291 del sys.modules[self.module]
294 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
295 cleanup_lib_files = self.cleanup_sharedlibs
296 if os.path.exists(self.workdir):
297 for rmfile in os.listdir(self.workdir):
298 if not cleanup_c_files:
299 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
301 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
303 if self.annotate and rmfile.endswith(".html"):
306 rmfile = os.path.join(self.workdir, rmfile)
307 if os.path.isdir(rmfile):
308 shutil.rmtree(rmfile, ignore_errors=True)
314 os.makedirs(self.workdir)
317 self.runCompileTest()
319 def runCompileTest(self):
320 self.compile(self.test_directory, self.module, self.workdir,
321 self.test_directory, self.expect_errors, self.annotate)
323 def find_module_source_file(self, source_file):
324 if not os.path.exists(source_file):
325 source_file = source_file[:-1]
328 def build_target_filename(self, module_name):
329 target = '%s.%s' % (module_name, self.language)
332 def copy_related_files(self, test_directory, target_directory, module_name):
333 is_related = re.compile('%s_.*[.].*' % module_name).match
334 for filename in os.listdir(test_directory):
335 if is_related(filename):
336 shutil.copy(os.path.join(test_directory, filename),
339 def find_source_files(self, workdir, module_name):
340 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
341 return [self.build_target_filename(module_name)] + [
342 filename for filename in os.listdir(workdir)
343 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
345 def split_source_and_output(self, test_directory, module, workdir):
346 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
347 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
349 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
351 for line in source_and_output:
353 if line.startswith("_ERRORS"):
359 source_and_output.close()
361 geterrors = out.geterrors
362 except AttributeError:
368 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
369 extra_compile_options=None):
370 include_dirs = INCLUDE_DIRS[:]
372 include_dirs.append(incdir)
373 source = self.find_module_source_file(
374 os.path.join(test_directory, module + '.pyx'))
375 target = os.path.join(targetdir, self.build_target_filename(module))
377 if extra_compile_options is None:
378 extra_compile_options = {}
383 from Cython.Compiler.Main import CompilationOptions
384 from Cython.Compiler.Main import compile as cython_compile
385 from Cython.Compiler.Main import default_options
387 options = CompilationOptions(
389 include_path = include_dirs,
390 output_file = target,
392 use_listing_file = False,
393 cplus = self.language == 'cpp',
394 language_level = self.language_level,
395 generate_pxi = False,
396 evaluate_tree_assertions = True,
397 **extra_compile_options
399 cython_compile(source, options=options,
400 full_module_name=module)
402 def run_distutils(self, test_directory, module, workdir, incdir,
403 extra_extension_args=None):
407 build_extension = build_ext(distutils_distro)
408 build_extension.include_dirs = INCLUDE_DIRS[:]
410 build_extension.include_dirs.append(incdir)
411 build_extension.finalize_options()
412 ext_include_dirs = []
413 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
415 ext_include_dirs += get_additional_include_dirs()
416 self.copy_related_files(test_directory, workdir, module)
418 if extra_extension_args is None:
419 extra_extension_args = {}
421 extension = Extension(
423 sources = self.find_source_files(workdir, module),
424 include_dirs = ext_include_dirs,
425 extra_compile_args = CFLAGS,
426 **extra_extension_args
428 if self.language == 'cpp':
429 extension.language = 'c++'
430 build_extension.extensions = [extension]
431 build_extension.build_temp = workdir
432 build_extension.build_lib = workdir
433 build_extension.run()
437 def compile(self, test_directory, module, workdir, incdir,
438 expect_errors, annotate):
439 expected_errors = errors = ()
441 expected_errors = self.split_source_and_output(
442 test_directory, module, workdir)
443 test_directory = workdir
446 old_stderr = sys.stderr
448 sys.stderr = ErrorWriter()
449 self.run_cython(test_directory, module, workdir, incdir, annotate)
450 errors = sys.stderr.geterrors()
452 sys.stderr = old_stderr
454 if errors or expected_errors:
456 for expected, error in zip(expected_errors, errors):
457 self.assertEquals(expected, error)
458 if len(errors) < len(expected_errors):
459 expected_error = expected_errors[len(errors)]
460 self.assertEquals(expected_error, None)
461 elif len(errors) > len(expected_errors):
462 unexpected_error = errors[len(expected_errors)]
463 self.assertEquals(None, unexpected_error)
464 except AssertionError:
465 print("\n=== Expected errors: ===")
466 print('\n'.join(expected_errors))
467 print("\n\n=== Got errors: ===")
468 print('\n'.join(errors))
472 if not self.cython_only:
473 self.run_distutils(test_directory, module, workdir, incdir)
475 class CythonRunTestCase(CythonCompileTestCase):
476 def shortDescription(self):
477 return "compiling (%s) and running %s" % (self.language, self.module)
479 def run(self, result=None):
481 result = self.defaultTestResult()
482 result.startTest(self)
486 self.runCompileTest()
487 self.run_tests(result)
489 check_thread_termination()
491 result.addError(self, sys.exc_info())
492 result.stopTest(self)
498 def run_tests(self, result):
499 if not self.cython_only:
500 self.run_doctests(self.module, result)
502 def run_doctests(self, module_name, result):
503 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
504 doctest.DocTestSuite(module_name).run(result)
508 # fork to make sure we do not keep the tested module loaded
509 result_handle, result_file = tempfile.mkstemp()
510 os.close(result_handle)
518 partial_result = PartialTestResult(result)
519 tests = doctest.DocTestSuite(module_name)
520 tests.run(partial_result)
524 # importing failed, try to fake a test class
526 failureException=sys.exc_info()[1],
527 _shortDescription=self.shortDescription(),
529 partial_result.addError(tests, sys.exc_info())
531 output = open(result_file, 'wb')
532 pickle.dump(partial_result.data(), output)
534 traceback.print_exc()
538 os._exit(result_code)
541 cid, result_code = os.waitpid(child_id, 0)
542 # os.waitpid returns the child's result code in the
543 # upper byte of result_code, and the signal it was
544 # killed by in the lower byte
545 if result_code & 255:
546 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
547 (module_name, result_code & 255))
548 result_code = result_code >> 8
549 if result_code in (0,1):
550 input = open(result_file, 'rb')
552 PartialTestResult.join_results(result, pickle.load(input))
556 raise Exception("Tests in module '%s' exited with status %d" %
557 (module_name, result_code))
559 try: os.unlink(result_file)
562 class PureDoctestTestCase(unittest.TestCase):
563 def __init__(self, module_name, module_path):
564 self.module_name = module_name
565 self.module_path = module_path
566 unittest.TestCase.__init__(self, 'run')
568 def shortDescription(self):
569 return "running pure doctests in %s" % self.module_name
571 def run(self, result=None):
573 result = self.defaultTestResult()
574 loaded_module_name = 'pure_doctest__' + self.module_name
575 result.startTest(self)
580 m = imp.load_source(loaded_module_name, self.module_path)
582 doctest.DocTestSuite(m).run(result)
585 if loaded_module_name in sys.modules:
586 del sys.modules[loaded_module_name]
587 check_thread_termination()
589 result.addError(self, sys.exc_info())
590 result.stopTest(self)
596 is_private_field = re.compile('^_[^_]').match
598 class _FakeClass(object):
599 def __init__(self, **kwargs):
600 self._shortDescription = kwargs.get('module_name')
601 self.__dict__.update(kwargs)
602 def shortDescription(self):
603 return self._shortDescription
605 try: # Py2.7+ and Py3.2+
606 from unittest.runner import _TextTestResult
608 from unittest import _TextTestResult
610 class PartialTestResult(_TextTestResult):
611 def __init__(self, base_result):
612 _TextTestResult.__init__(
613 self, self._StringIO(), True,
614 base_result.dots + base_result.showAll*2)
616 def strip_error_results(self, results):
617 for test_case, error in results:
618 for attr_name in filter(is_private_field, dir(test_case)):
619 if attr_name == '_dt_test':
620 test_case._dt_test = _FakeClass(
621 name=test_case._dt_test.name)
622 elif attr_name != '_shortDescription':
623 setattr(test_case, attr_name, None)
626 self.strip_error_results(self.failures)
627 self.strip_error_results(self.errors)
628 return (self.failures, self.errors, self.testsRun,
629 self.stream.getvalue())
631 def join_results(result, data):
632 """Static method for merging the result back into the main
635 failures, errors, tests_run, output = data
637 result.stream.write(output)
638 result.errors.extend(errors)
639 result.failures.extend(failures)
640 result.testsRun += tests_run
642 join_results = staticmethod(join_results)
644 class _StringIO(StringIO):
645 def writeln(self, line):
646 self.write("%s\n" % line)
649 class CythonUnitTestCase(CythonRunTestCase):
650 def shortDescription(self):
651 return "compiling (%s) tests in %s" % (self.language, self.module)
653 def run_tests(self, result):
654 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
657 class CythonPyregrTestCase(CythonRunTestCase):
658 def _run_unittest(self, result, *classes):
659 """Run tests from unittest.TestCase-derived classes."""
660 valid_types = (unittest.TestSuite, unittest.TestCase)
661 suite = unittest.TestSuite()
663 if isinstance(cls, str):
664 if cls in sys.modules:
665 suite.addTest(unittest.findTestCases(sys.modules[cls]))
667 raise ValueError("str arguments must be keys in sys.modules")
668 elif isinstance(cls, valid_types):
671 suite.addTest(unittest.makeSuite(cls))
674 def _run_doctest(self, result, module):
675 self.run_doctests(module, result)
677 def run_tests(self, result):
679 from test import test_support as support
680 except ImportError: # Py3k
681 from test import support
683 def run_unittest(*classes):
684 return self._run_unittest(result, *classes)
685 def run_doctest(module, verbosity=None):
686 return self._run_doctest(result, module)
688 support.run_unittest = run_unittest
689 support.run_doctest = run_doctest
692 module = __import__(self.module)
693 if hasattr(module, 'test_main'):
695 except (unittest.SkipTest, support.ResourceDenied):
696 result.addSkip(self, 'ok')
698 include_debugger = sys.version_info[:2] > (2, 5)
700 def collect_unittests(path, module_prefix, suite, selectors):
701 def file_matches(filename):
702 return filename.startswith("Test") and filename.endswith(".py")
704 def package_matches(dirname):
705 return dirname == "Tests"
707 loader = unittest.TestLoader()
712 cython_dir = os.path.dirname(os.path.abspath(__file__))
713 skipped_dirs = [os.path.join(cython_dir, 'Cython', 'Debugger')]
715 for dirpath, dirnames, filenames in os.walk(path):
716 if dirpath != path and "__init__.py" not in filenames:
717 skipped_dirs.append(dirpath + os.path.sep)
720 for dir in skipped_dirs:
721 if dirpath.startswith(dir):
725 parentname = os.path.split(dirpath)[-1]
726 if package_matches(parentname):
729 filepath = os.path.join(dirpath, f)[:-len(".py")]
730 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
731 if not [ 1 for match in selectors if match(modulename) ]:
733 module = __import__(modulename)
734 for x in modulename.split('.')[1:]:
735 module = getattr(module, x)
736 suite.addTests([loader.loadTestsFromModule(module)])
740 def collect_doctests(path, module_prefix, suite, selectors):
741 def package_matches(dirname):
742 if dirname == 'Debugger' and not include_debugger:
744 return dirname not in ("Mac", "Distutils", "Plex")
745 def file_matches(filename):
746 filename, ext = os.path.splitext(filename)
747 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
749 return (ext == '.py' and not
750 '~' in filename and not
751 '#' in filename and not
752 filename.startswith('.') and not
753 filename in blacklist)
754 import doctest, types
755 for dirpath, dirnames, filenames in os.walk(path):
756 for dir in list(dirnames):
757 if not package_matches(dir):
761 if not f.endswith('.py'): continue
762 filepath = os.path.join(dirpath, f)
763 if os.path.getsize(filepath) == 0: continue
764 filepath = filepath[:-len(".py")]
765 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
766 if not [ 1 for match in selectors if match(modulename) ]:
768 if 'in_gdb' in modulename:
769 # These should only be imported from gdb.
771 module = __import__(modulename)
772 for x in modulename.split('.')[1:]:
773 module = getattr(module, x)
774 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
776 suite.addTest(doctest.DocTestSuite(module))
777 except ValueError: # no tests
781 class EndToEndTest(unittest.TestCase):
783 This is a test of build/*.srctree files, where srctree defines a full
784 directory structure and its header gives a list of commands to run.
786 cython_root = os.path.dirname(os.path.abspath(__file__))
788 def __init__(self, treefile, workdir, cleanup_workdir=True):
789 self.treefile = treefile
790 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
791 self.cleanup_workdir = cleanup_workdir
792 cython_syspath = self.cython_root
793 for path in sys.path[::-1]:
794 if path.startswith(self.cython_root):
795 # Py3 installation and refnanny build prepend their
796 # fixed paths to sys.path => prefer that over the
798 cython_syspath = path + os.pathsep + cython_syspath
799 self.cython_syspath = cython_syspath
800 unittest.TestCase.__init__(self)
802 def shortDescription(self):
803 return "End-to-end %s" % self.treefile
806 from Cython.TestUtils import unpack_source_tree
807 _, self.commands = unpack_source_tree(
808 os.path.join('tests', 'build', self.treefile), self.workdir)
809 self.old_dir = os.getcwd()
810 os.chdir(self.workdir)
811 if self.workdir not in sys.path:
812 sys.path.insert(0, self.workdir)
815 if self.cleanup_workdir:
816 shutil.rmtree(self.workdir)
817 os.chdir(self.old_dir)
820 commands = (self.commands
821 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
822 .replace("PYTHON", sys.executable))
824 old_path = os.environ.get('PYTHONPATH')
825 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
826 for command in commands.split('\n'):
827 if sys.version_info[:2] >= (2,4):
829 p = subprocess.Popen(commands,
830 stderr=subprocess.PIPE,
831 stdout=subprocess.PIPE,
833 out, err = p.communicate()
840 res = os.system(command)
841 self.assertEqual(0, res, "non-zero exit status")
844 os.environ['PYTHONPATH'] = old_path
846 del os.environ['PYTHONPATH']
849 # TODO: Support cython_freeze needed here as well.
850 # TODO: Windows support.
852 class EmbedTest(unittest.TestCase):
854 working_dir = "Demos/embed"
857 self.old_dir = os.getcwd()
858 os.chdir(self.working_dir)
860 "make PYTHON='%s' clean > /dev/null" % sys.executable)
865 "make PYTHON='%s' clean > /dev/null" % sys.executable)
868 os.chdir(self.old_dir)
870 def test_embed(self):
871 from distutils import sysconfig
872 libname = sysconfig.get_config_var('LIBRARY')
873 libdir = sysconfig.get_config_var('LIBDIR')
874 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
875 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
876 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
877 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
878 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
879 # report the error for the original directory
880 libdir = sysconfig.get_config_var('LIBDIR')
881 self.assert_(os.system(
882 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
884 os.remove('make.output')
888 class MissingDependencyExcluder:
889 def __init__(self, deps):
890 # deps: { module name : matcher func }
891 self.exclude_matchers = []
892 for mod, matcher in deps.items():
896 self.exclude_matchers.append(matcher)
897 self.tests_missing_deps = []
898 def __call__(self, testname):
899 for matcher in self.exclude_matchers:
900 if matcher(testname):
901 self.tests_missing_deps.append(testname)
905 class VersionDependencyExcluder:
906 def __init__(self, deps):
907 # deps: { version : matcher func }
908 from sys import version_info
909 self.exclude_matchers = []
910 for ver, (compare, matcher) in deps.items():
911 if compare(version_info, ver):
912 self.exclude_matchers.append(matcher)
913 self.tests_missing_deps = []
914 def __call__(self, testname):
915 for matcher in self.exclude_matchers:
916 if matcher(testname):
917 self.tests_missing_deps.append(testname)
921 class FileListExcluder:
923 def __init__(self, list_file):
927 for line in f.readlines():
929 if line and line[0] != '#':
930 self.excludes[line.split()[0]] = True
934 def __call__(self, testname):
935 return testname in self.excludes or testname.split('.')[-1] in self.excludes
937 def refactor_for_py3(distdir, cy3_dir):
938 # need to convert Cython sources first
939 import lib2to3.refactor
940 from distutils.util import copydir_run_2to3
941 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
942 if fix.split('fix_')[-1] not in ('next',)
944 if not os.path.exists(cy3_dir):
946 import distutils.log as dlog
947 dlog.set_threshold(dlog.INFO)
948 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
952 recursive-exclude Cython *
953 recursive-include Cython *.py *.pyx *.pxd
954 recursive-include Cython/Debugger/Tests *
957 sys.path.insert(0, cy3_dir)
959 for keep_2x_file in KEEP_2X_FILES:
960 destfile = os.path.join(cy3_dir, keep_2x_file)
961 shutil.copy(keep_2x_file, destfile)
963 class PendingThreadsError(RuntimeError):
968 def check_thread_termination(ignore_seen=True):
969 if threading is None: # no threading enabled in CPython
971 current = threading.currentThread()
972 blocking_threads = []
973 for t in threading.enumerate():
974 if not t.isAlive() or t == current:
979 blocking_threads.append(t)
981 for seen in threads_seen:
985 threads_seen.append(t)
986 blocking_threads.append(t)
987 if not blocking_threads:
989 sys.stderr.write("warning: left-over threads found after running test:\n")
990 for t in blocking_threads:
991 sys.stderr.write('...%s\n' % repr(t))
992 raise PendingThreadsError("left-over threads found after running test")
996 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
998 from optparse import OptionParser
999 parser = OptionParser()
1000 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1001 action="store_false", default=True,
1002 help="do not delete the generated C files (allows passing --no-cython on next run)")
1003 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1004 action="store_false", default=True,
1005 help="do not delete the generated shared libary files (allows manual module experimentation)")
1006 parser.add_option("--no-cython", dest="with_cython",
1007 action="store_false", default=True,
1008 help="do not run the Cython compiler, only the C compiler")
1009 parser.add_option("--no-c", dest="use_c",
1010 action="store_false", default=True,
1011 help="do not test C compilation")
1012 parser.add_option("--no-cpp", dest="use_cpp",
1013 action="store_false", default=True,
1014 help="do not test C++ compilation")
1015 parser.add_option("--no-unit", dest="unittests",
1016 action="store_false", default=True,
1017 help="do not run the unit tests")
1018 parser.add_option("--no-doctest", dest="doctests",
1019 action="store_false", default=True,
1020 help="do not run the doctests")
1021 parser.add_option("--no-file", dest="filetests",
1022 action="store_false", default=True,
1023 help="do not run the file based tests")
1024 parser.add_option("--no-pyregr", dest="pyregr",
1025 action="store_false", default=True,
1026 help="do not run the regression tests of CPython in tests/pyregr/")
1027 parser.add_option("--cython-only", dest="cython_only",
1028 action="store_true", default=False,
1029 help="only compile pyx to c, do not run C compiler or run the tests")
1030 parser.add_option("--no-refnanny", dest="with_refnanny",
1031 action="store_false", default=True,
1032 help="do not regression test reference counting")
1033 parser.add_option("--no-fork", dest="fork",
1034 action="store_false", default=True,
1035 help="do not fork to run tests")
1036 parser.add_option("--sys-pyregr", dest="system_pyregr",
1037 action="store_true", default=False,
1038 help="run the regression tests of the CPython installation")
1039 parser.add_option("-x", "--exclude", dest="exclude",
1040 action="append", metavar="PATTERN",
1041 help="exclude tests matching the PATTERN")
1042 parser.add_option("-C", "--coverage", dest="coverage",
1043 action="store_true", default=False,
1044 help="collect source coverage data for the Compiler")
1045 parser.add_option("--coverage-xml", dest="coverage_xml",
1046 action="store_true", default=False,
1047 help="collect source coverage data for the Compiler in XML format")
1048 parser.add_option("-A", "--annotate", dest="annotate_source",
1049 action="store_true", default=True,
1050 help="generate annotated HTML versions of the test source files")
1051 parser.add_option("--no-annotate", dest="annotate_source",
1052 action="store_false",
1053 help="do not generate annotated HTML versions of the test source files")
1054 parser.add_option("-v", "--verbose", dest="verbosity",
1055 action="count", default=0,
1056 help="display test progress, pass twice to print test names")
1057 parser.add_option("-T", "--ticket", dest="tickets",
1059 help="a bug ticket number to run the respective test in 'tests/*'")
1060 parser.add_option("-3", dest="language_level",
1061 action="store_const", const=3, default=2,
1062 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1063 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1064 help="write test results in XML to directory DIR")
1065 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1066 action="store_true",
1067 help="exit without error code even on test failures")
1068 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1069 help="working directory")
1070 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1071 help="working directory")
1073 options, cmd_args = parser.parse_args()
1075 ROOTDIR = os.path.abspath(options.root_dir)
1076 WORKDIR = os.path.abspath(options.work_dir)
1078 if sys.version_info[0] >= 3:
1079 options.doctests = False
1080 if options.with_cython:
1082 # try if Cython is installed in a Py3 version
1083 import Cython.Compiler.Main
1085 # back out anything the import process loaded, then
1086 # 2to3 the Cython sources to make them re-importable
1087 cy_modules = [ name for name in sys.modules
1088 if name == 'Cython' or name.startswith('Cython.') ]
1089 for name in cy_modules:
1090 del sys.modules[name]
1091 # hasn't been refactored yet - do it now
1092 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1093 if sys.version_info >= (3,1):
1094 refactor_for_py3(DISTDIR, cy3_dir)
1095 elif os.path.isdir(cy3_dir):
1096 sys.path.insert(0, cy3_dir)
1098 options.with_cython = False
1100 WITH_CYTHON = options.with_cython
1102 if options.coverage or options.coverage_xml:
1104 options.coverage = options.coverage_xml = False
1106 from coverage import coverage as _coverage
1107 coverage = _coverage(branch=True)
1112 global CompilationOptions, pyrex_default_options, cython_compile
1113 from Cython.Compiler.Main import \
1114 CompilationOptions, \
1115 default_options as pyrex_default_options, \
1116 compile as cython_compile
1117 from Cython.Compiler import Errors
1118 Errors.LEVEL = 0 # show all warnings
1119 from Cython.Compiler import Options
1120 Options.generate_cleanup_code = 3 # complete cleanup code
1121 from Cython.Compiler import DebugFlags
1122 DebugFlags.debug_temp_code_comments = 1
1125 UNITTEST_MODULE = "Cython"
1126 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1128 if os.path.exists(WORKDIR):
1129 for path in os.listdir(WORKDIR):
1130 if path in ("support", "Cy3"): continue
1131 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1132 if not os.path.exists(WORKDIR):
1133 os.makedirs(WORKDIR)
1135 sys.stderr.write("Python %s\n" % sys.version)
1136 sys.stderr.write("\n")
1138 from Cython.Compiler.Version import version
1139 sys.stderr.write("Running tests against Cython %s\n" % version)
1141 sys.stderr.write("Running tests without Cython.\n")
1143 if options.with_refnanny:
1144 from pyximport.pyxbuild import pyx_to_dll
1145 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1147 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1148 sys.path.insert(0, os.path.split(libpath)[0])
1149 CFLAGS.append("-DCYTHON_REFNANNY=1")
1151 if options.xml_output_dir and options.fork:
1152 # doesn't currently work together
1153 sys.stderr.write("Disabling forked testing to support XML test output\n")
1154 options.fork = False
1156 if WITH_CYTHON and options.language_level == 3:
1157 sys.stderr.write("Using Cython language level 3.\n")
1159 sys.stderr.write("\n")
1163 for ticket_number in options.tickets:
1165 cmd_args.append('.*T%s$' % ticket_number)
1167 for selector in cmd_args:
1168 if selector.startswith('bugs'):
1172 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1174 selectors = [ lambda x:True ]
1176 # Chech which external modules are not present and exclude tests
1177 # which depends on them (by prefix)
1179 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1180 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1181 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1184 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1187 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1189 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1190 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1194 languages.append('c')
1196 languages.append('cpp')
1198 test_suite = unittest.TestSuite()
1200 if options.unittests:
1201 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1203 if options.doctests:
1204 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1206 if options.filetests and languages:
1207 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1208 options.annotate_source, options.cleanup_workdir,
1209 options.cleanup_sharedlibs, options.pyregr,
1210 options.cython_only, languages, test_bugs,
1211 options.fork, options.language_level)
1212 test_suite.addTest(filetests.build_suite())
1214 if options.system_pyregr and languages:
1215 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1216 options.annotate_source, options.cleanup_workdir,
1217 options.cleanup_sharedlibs, True,
1218 options.cython_only, languages, test_bugs,
1219 options.fork, options.language_level)
1221 filetests.handle_directory(
1222 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1225 if options.xml_output_dir:
1226 from Cython.Tests.xmlrunner import XMLTestRunner
1227 test_runner = XMLTestRunner(output=options.xml_output_dir,
1228 verbose=options.verbosity > 0)
1230 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1232 result = test_runner.run(test_suite)
1234 if options.coverage or options.coverage_xml:
1236 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1237 modules = [ module for name, module in sys.modules.items()
1238 if module is not None and
1239 name.startswith('Cython.Compiler.') and
1240 name[len('Cython.Compiler.'):] not in ignored_modules ]
1241 if options.coverage:
1242 coverage.report(modules, show_missing=0)
1243 if options.coverage_xml:
1244 coverage.xml_report(modules, outfile="coverage-report.xml")
1246 if missing_dep_excluder.tests_missing_deps:
1247 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1248 for test in missing_dep_excluder.tests_missing_deps:
1249 sys.stderr.write(" %s\n" % test)
1251 if options.with_refnanny:
1253 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1260 return_code = not result.wasSuccessful()
1263 check_thread_termination(ignore_seen=False)
1264 sys.exit(return_code)
1265 except PendingThreadsError:
1266 # normal program exit won't kill the threads, do it the hard way here
1267 os._exit(return_code)
1269 if __name__ == '__main__':
1272 except SystemExit: # <= Py2.4 ...
1275 traceback.print_exc()
1277 check_thread_termination(ignore_seen=False)
1278 except PendingThreadsError:
1279 # normal program exit won't kill the threads, do it the hard way here