16 from StringIO import StringIO
18 from io import StringIO
21 import cPickle as pickle
27 except ImportError: # No threads, no problems
33 from distutils.dist import Distribution
34 from distutils.core import Extension
35 from distutils.command.build_ext import build_ext as _build_ext
36 distutils_distro = Distribution()
38 if sys.platform == 'win32':
39 # TODO: Figure out why this hackery (see http://thread.gmane.org/gmane.comp.python.cython.devel/8280/).
40 config_files = distutils_distro.find_config_files()
41 try: config_files.remove('setup.cfg')
42 except ValueError: pass
43 distutils_distro.parse_config_files(config_files)
45 cfgfiles = distutils_distro.find_config_files()
46 try: cfgfiles.remove('setup.cfg')
47 except ValueError: pass
48 distutils_distro.parse_config_files(cfgfiles)
50 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr', 'build']
51 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
53 # Lists external modules, and a matcher matching tests
54 # which should be excluded if the module is not present.
56 'numpy' : re.compile('.*\.numpy_.*').match,
57 'pstats' : re.compile('.*\.pstats_.*').match,
58 'posix' : re.compile('.*\.posix_.*').match,
61 def get_numpy_include_dirs():
63 return [numpy.get_include()]
66 # test name matcher , callable returning list
67 (re.compile('numpy_.*').match, get_numpy_include_dirs),
71 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
72 # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
73 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
76 (2,5) : (operator.lt, lambda x: x in ['run.any',
79 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
81 'run.pure_py', # decorators, with statement
83 # The next line should start (3,); but this is a dictionary, so
84 # we can only have one (3,) key. Since 2.7 is supposed to be the
85 # last 2.x release, things would have to change drastically for this
87 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
88 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
89 'compile.extsetslice',
90 'compile.extdelslice',
91 'run.special_methods_T561_py2']),
94 # files that should not be converted to Python 3 code with 2to3
96 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
97 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
98 os.path.join('Cython', 'Debugger', 'libcython.py'),
99 os.path.join('Cython', 'Debugger', 'libpython.py'),
103 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
104 CFLAGS = os.getenv('CFLAGS', '').split()
106 class build_ext(_build_ext):
107 def build_extension(self, ext):
108 if ext.language == 'c++':
110 try: # Py2.7+ & Py3.2+
111 compiler_obj = self.compiler_obj
112 except AttributeError:
113 compiler_obj = self.compiler
114 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
117 _build_ext.build_extension(self, ext)
119 class ErrorWriter(object):
120 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
123 self.write = self.output.append
125 def _collect(self, collect_errors, collect_warnings):
126 s = ''.join(self.output)
128 for line in s.split('\n'):
129 match = self.match_error(line)
131 is_warning, line, column, message = match.groups()
132 if (is_warning and collect_warnings) or \
133 (not is_warning and collect_errors):
134 result.append( (int(line), int(column), message.strip()) )
136 return [ "%d:%d: %s" % values for values in result ]
139 return self._collect(True, False)
141 def getwarnings(self):
142 return self._collect(False, True)
145 return self._collect(True, True)
147 class TestBuilder(object):
148 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
149 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
150 languages, test_bugs, fork, language_level):
151 self.rootdir = rootdir
152 self.workdir = workdir
153 self.selectors = selectors
154 self.exclude_selectors = exclude_selectors
155 self.annotate = annotate
156 self.cleanup_workdir = cleanup_workdir
157 self.cleanup_sharedlibs = cleanup_sharedlibs
158 self.with_pyregr = with_pyregr
159 self.cython_only = cython_only
160 self.languages = languages
161 self.test_bugs = test_bugs
163 self.language_level = language_level
165 def build_suite(self):
166 suite = unittest.TestSuite()
167 test_dirs = TEST_DIRS
168 filenames = os.listdir(self.rootdir)
170 for filename in filenames:
171 if not WITH_CYTHON and filename == "errors":
172 # we won't get any errors without running Cython
174 path = os.path.join(self.rootdir, filename)
175 if os.path.isdir(path) and filename in test_dirs:
176 if filename == 'pyregr' and not self.with_pyregr:
179 self.handle_directory(path, filename))
180 if sys.platform not in ['win32']:
181 # Non-Windows makefile.
182 if [1 for selector in self.selectors if selector("embedded")] \
183 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
184 suite.addTest(unittest.makeSuite(EmbedTest))
187 def handle_directory(self, path, context):
188 workdir = os.path.join(self.workdir, context)
189 if not os.path.exists(workdir):
192 expect_errors = (context == 'errors')
193 suite = unittest.TestSuite()
194 filenames = os.listdir(path)
196 for filename in filenames:
197 if filename.endswith(".srctree"):
198 if not [ 1 for match in self.selectors if match(filename) ]:
200 if self.exclude_selectors:
201 if [1 for match in self.exclude_selectors if match(filename)]:
203 suite.addTest(EndToEndTest(os.path.join(path, filename), workdir, self.cleanup_workdir))
205 if not (filename.endswith(".pyx") or filename.endswith(".py")):
207 if filename.startswith('.'): continue # certain emacs backup files
208 if context == 'pyregr' and not filename.startswith('test_'):
210 module = os.path.splitext(filename)[0]
211 fqmodule = "%s.%s" % (context, module)
212 if not [ 1 for match in self.selectors
213 if match(fqmodule) ]:
215 if self.exclude_selectors:
216 if [1 for match in self.exclude_selectors if match(fqmodule)]:
218 if context == 'pyregr':
219 test_class = CythonPyregrTestCase
220 elif context in TEST_RUN_DIRS:
221 if module.startswith("test_"):
222 test_class = CythonUnitTestCase
224 test_class = CythonRunTestCase
226 test_class = CythonCompileTestCase
227 for test in self.build_tests(test_class, path, workdir,
228 module, expect_errors):
230 if context == 'run' and filename.endswith('.py'):
231 # additionally test file in real Python
232 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
235 def build_tests(self, test_class, path, workdir, module, expect_errors):
237 if 'cpp' in module and 'cpp' in self.languages:
240 languages = self.languages[:1]
242 languages = self.languages
243 if 'cpp' in module and 'c' in languages:
244 languages = list(languages)
245 languages.remove('c')
246 tests = [ self.build_test(test_class, path, workdir, module,
247 language, expect_errors)
248 for language in languages ]
251 def build_test(self, test_class, path, workdir, module,
252 language, expect_errors):
253 workdir = os.path.join(workdir, language)
254 if not os.path.exists(workdir):
256 return test_class(path, workdir, module,
258 expect_errors=expect_errors,
259 annotate=self.annotate,
260 cleanup_workdir=self.cleanup_workdir,
261 cleanup_sharedlibs=self.cleanup_sharedlibs,
262 cython_only=self.cython_only,
264 language_level=self.language_level)
266 class CythonCompileTestCase(unittest.TestCase):
267 def __init__(self, test_directory, workdir, module, language='c',
268 expect_errors=False, annotate=False, cleanup_workdir=True,
269 cleanup_sharedlibs=True, cython_only=False, fork=True,
271 self.test_directory = test_directory
272 self.workdir = workdir
274 self.language = language
275 self.expect_errors = expect_errors
276 self.annotate = annotate
277 self.cleanup_workdir = cleanup_workdir
278 self.cleanup_sharedlibs = cleanup_sharedlibs
279 self.cython_only = cython_only
281 self.language_level = language_level
282 unittest.TestCase.__init__(self)
284 def shortDescription(self):
285 return "compiling (%s) %s" % (self.language, self.module)
288 if self.workdir not in sys.path:
289 sys.path.insert(0, self.workdir)
293 sys.path.remove(self.workdir)
297 del sys.modules[self.module]
300 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
301 cleanup_lib_files = self.cleanup_sharedlibs
302 if os.path.exists(self.workdir):
303 for rmfile in os.listdir(self.workdir):
304 if not cleanup_c_files:
305 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
307 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
309 if self.annotate and rmfile.endswith(".html"):
312 rmfile = os.path.join(self.workdir, rmfile)
313 if os.path.isdir(rmfile):
314 shutil.rmtree(rmfile, ignore_errors=True)
320 os.makedirs(self.workdir)
323 self.runCompileTest()
325 def runCompileTest(self):
326 self.compile(self.test_directory, self.module, self.workdir,
327 self.test_directory, self.expect_errors, self.annotate)
329 def find_module_source_file(self, source_file):
330 if not os.path.exists(source_file):
331 source_file = source_file[:-1]
334 def build_target_filename(self, module_name):
335 target = '%s.%s' % (module_name, self.language)
338 def copy_related_files(self, test_directory, target_directory, module_name):
339 is_related = re.compile('%s_.*[.].*' % module_name).match
340 for filename in os.listdir(test_directory):
341 if is_related(filename):
342 shutil.copy(os.path.join(test_directory, filename),
345 def find_source_files(self, workdir, module_name):
346 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
347 return [self.build_target_filename(module_name)] + [
348 filename for filename in os.listdir(workdir)
349 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
351 def split_source_and_output(self, test_directory, module, workdir):
352 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
353 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
355 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
357 for line in source_and_output:
359 if line.startswith("_ERRORS"):
365 source_and_output.close()
367 geterrors = out.geterrors
368 except AttributeError:
374 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
375 extra_compile_options=None):
376 include_dirs = INCLUDE_DIRS[:]
378 include_dirs.append(incdir)
379 source = self.find_module_source_file(
380 os.path.join(test_directory, module + '.pyx'))
381 target = os.path.join(targetdir, self.build_target_filename(module))
383 if extra_compile_options is None:
384 extra_compile_options = {}
389 from Cython.Compiler.Main import CompilationOptions
390 from Cython.Compiler.Main import compile as cython_compile
391 from Cython.Compiler.Main import default_options
393 options = CompilationOptions(
395 include_path = include_dirs,
396 output_file = target,
398 use_listing_file = False,
399 cplus = self.language == 'cpp',
400 language_level = self.language_level,
401 generate_pxi = False,
402 evaluate_tree_assertions = True,
403 **extra_compile_options
405 cython_compile(source, options=options,
406 full_module_name=module)
408 def run_distutils(self, test_directory, module, workdir, incdir,
409 extra_extension_args=None):
413 build_extension = build_ext(distutils_distro)
414 build_extension.include_dirs = INCLUDE_DIRS[:]
416 build_extension.include_dirs.append(incdir)
417 build_extension.finalize_options()
419 build_extension.compiler = COMPILER
420 ext_include_dirs = []
421 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
423 ext_include_dirs += get_additional_include_dirs()
424 ext_compile_flags = CFLAGS[:]
425 if build_extension.compiler == 'mingw32':
426 ext_compile_flags.append('-Wno-format')
427 if extra_extension_args is None:
428 extra_extension_args = {}
430 self.copy_related_files(test_directory, workdir, module)
431 extension = Extension(
433 sources = self.find_source_files(workdir, module),
434 include_dirs = ext_include_dirs,
435 extra_compile_args = ext_compile_flags,
436 **extra_extension_args
438 if self.language == 'cpp':
439 extension.language = 'c++'
440 build_extension.extensions = [extension]
441 build_extension.build_temp = workdir
442 build_extension.build_lib = workdir
443 build_extension.run()
447 def compile(self, test_directory, module, workdir, incdir,
448 expect_errors, annotate):
449 expected_errors = errors = ()
451 expected_errors = self.split_source_and_output(
452 test_directory, module, workdir)
453 test_directory = workdir
456 old_stderr = sys.stderr
458 sys.stderr = ErrorWriter()
459 self.run_cython(test_directory, module, workdir, incdir, annotate)
460 errors = sys.stderr.geterrors()
462 sys.stderr = old_stderr
464 if errors or expected_errors:
466 for expected, error in zip(expected_errors, errors):
467 self.assertEquals(expected, error)
468 if len(errors) < len(expected_errors):
469 expected_error = expected_errors[len(errors)]
470 self.assertEquals(expected_error, None)
471 elif len(errors) > len(expected_errors):
472 unexpected_error = errors[len(expected_errors)]
473 self.assertEquals(None, unexpected_error)
474 except AssertionError:
475 print("\n=== Expected errors: ===")
476 print('\n'.join(expected_errors))
477 print("\n\n=== Got errors: ===")
478 print('\n'.join(errors))
482 if not self.cython_only:
483 self.run_distutils(test_directory, module, workdir, incdir)
485 class CythonRunTestCase(CythonCompileTestCase):
486 def shortDescription(self):
487 return "compiling (%s) and running %s" % (self.language, self.module)
489 def run(self, result=None):
491 result = self.defaultTestResult()
492 result.startTest(self)
496 self.runCompileTest()
497 self.run_tests(result)
499 check_thread_termination()
501 result.addError(self, sys.exc_info())
502 result.stopTest(self)
508 def run_tests(self, result):
509 if not self.cython_only:
510 self.run_doctests(self.module, result)
512 def run_doctests(self, module_name, result):
513 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
514 doctest.DocTestSuite(module_name).run(result)
518 # fork to make sure we do not keep the tested module loaded
519 result_handle, result_file = tempfile.mkstemp()
520 os.close(result_handle)
528 partial_result = PartialTestResult(result)
529 tests = doctest.DocTestSuite(module_name)
530 tests.run(partial_result)
534 # importing failed, try to fake a test class
536 failureException=sys.exc_info()[1],
537 _shortDescription=self.shortDescription(),
539 partial_result.addError(tests, sys.exc_info())
541 output = open(result_file, 'wb')
542 pickle.dump(partial_result.data(), output)
544 traceback.print_exc()
548 os._exit(result_code)
551 cid, result_code = os.waitpid(child_id, 0)
552 # os.waitpid returns the child's result code in the
553 # upper byte of result_code, and the signal it was
554 # killed by in the lower byte
555 if result_code & 255:
556 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
557 (module_name, result_code & 255))
558 result_code = result_code >> 8
559 if result_code in (0,1):
560 input = open(result_file, 'rb')
562 PartialTestResult.join_results(result, pickle.load(input))
566 raise Exception("Tests in module '%s' exited with status %d" %
567 (module_name, result_code))
569 try: os.unlink(result_file)
572 class PureDoctestTestCase(unittest.TestCase):
573 def __init__(self, module_name, module_path):
574 self.module_name = module_name
575 self.module_path = module_path
576 unittest.TestCase.__init__(self, 'run')
578 def shortDescription(self):
579 return "running pure doctests in %s" % self.module_name
581 def run(self, result=None):
583 result = self.defaultTestResult()
584 loaded_module_name = 'pure_doctest__' + self.module_name
585 result.startTest(self)
590 m = imp.load_source(loaded_module_name, self.module_path)
592 doctest.DocTestSuite(m).run(result)
595 if loaded_module_name in sys.modules:
596 del sys.modules[loaded_module_name]
597 check_thread_termination()
599 result.addError(self, sys.exc_info())
600 result.stopTest(self)
606 is_private_field = re.compile('^_[^_]').match
608 class _FakeClass(object):
609 def __init__(self, **kwargs):
610 self._shortDescription = kwargs.get('module_name')
611 self.__dict__.update(kwargs)
612 def shortDescription(self):
613 return self._shortDescription
615 try: # Py2.7+ and Py3.2+
616 from unittest.runner import _TextTestResult
618 from unittest import _TextTestResult
620 class PartialTestResult(_TextTestResult):
621 def __init__(self, base_result):
622 _TextTestResult.__init__(
623 self, self._StringIO(), True,
624 base_result.dots + base_result.showAll*2)
626 def strip_error_results(self, results):
627 for test_case, error in results:
628 for attr_name in filter(is_private_field, dir(test_case)):
629 if attr_name == '_dt_test':
630 test_case._dt_test = _FakeClass(
631 name=test_case._dt_test.name)
632 elif attr_name != '_shortDescription':
633 setattr(test_case, attr_name, None)
636 self.strip_error_results(self.failures)
637 self.strip_error_results(self.errors)
638 return (self.failures, self.errors, self.testsRun,
639 self.stream.getvalue())
641 def join_results(result, data):
642 """Static method for merging the result back into the main
645 failures, errors, tests_run, output = data
647 result.stream.write(output)
648 result.errors.extend(errors)
649 result.failures.extend(failures)
650 result.testsRun += tests_run
652 join_results = staticmethod(join_results)
654 class _StringIO(StringIO):
655 def writeln(self, line):
656 self.write("%s\n" % line)
659 class CythonUnitTestCase(CythonRunTestCase):
660 def shortDescription(self):
661 return "compiling (%s) tests in %s" % (self.language, self.module)
663 def run_tests(self, result):
664 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
667 class CythonPyregrTestCase(CythonRunTestCase):
668 def _run_unittest(self, result, *classes):
669 """Run tests from unittest.TestCase-derived classes."""
670 valid_types = (unittest.TestSuite, unittest.TestCase)
671 suite = unittest.TestSuite()
673 if isinstance(cls, str):
674 if cls in sys.modules:
675 suite.addTest(unittest.findTestCases(sys.modules[cls]))
677 raise ValueError("str arguments must be keys in sys.modules")
678 elif isinstance(cls, valid_types):
681 suite.addTest(unittest.makeSuite(cls))
684 def _run_doctest(self, result, module):
685 self.run_doctests(module, result)
687 def run_tests(self, result):
689 from test import test_support as support
690 except ImportError: # Py3k
691 from test import support
693 def run_unittest(*classes):
694 return self._run_unittest(result, *classes)
695 def run_doctest(module, verbosity=None):
696 return self._run_doctest(result, module)
698 support.run_unittest = run_unittest
699 support.run_doctest = run_doctest
702 module = __import__(self.module)
703 if hasattr(module, 'test_main'):
705 except (unittest.SkipTest, support.ResourceDenied):
706 result.addSkip(self, 'ok')
708 include_debugger = sys.version_info[:2] > (2, 5)
710 def collect_unittests(path, module_prefix, suite, selectors):
711 def file_matches(filename):
712 return filename.startswith("Test") and filename.endswith(".py")
714 def package_matches(dirname):
715 return dirname == "Tests"
717 loader = unittest.TestLoader()
722 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
724 for dirpath, dirnames, filenames in os.walk(path):
725 if dirpath != path and "__init__.py" not in filenames:
726 skipped_dirs.append(dirpath + os.path.sep)
729 for dir in skipped_dirs:
730 if dirpath.startswith(dir):
734 parentname = os.path.split(dirpath)[-1]
735 if package_matches(parentname):
738 filepath = os.path.join(dirpath, f)[:-len(".py")]
739 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
740 if not [ 1 for match in selectors if match(modulename) ]:
742 module = __import__(modulename)
743 for x in modulename.split('.')[1:]:
744 module = getattr(module, x)
745 suite.addTests([loader.loadTestsFromModule(module)])
749 def collect_doctests(path, module_prefix, suite, selectors):
750 def package_matches(dirname):
751 if dirname == 'Debugger' and not include_debugger:
753 return dirname not in ("Mac", "Distutils", "Plex")
754 def file_matches(filename):
755 filename, ext = os.path.splitext(filename)
756 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
758 return (ext == '.py' and not
759 '~' in filename and not
760 '#' in filename and not
761 filename.startswith('.') and not
762 filename in blacklist)
763 import doctest, types
764 for dirpath, dirnames, filenames in os.walk(path):
765 for dir in list(dirnames):
766 if not package_matches(dir):
770 if not f.endswith('.py'): continue
771 filepath = os.path.join(dirpath, f)
772 if os.path.getsize(filepath) == 0: continue
773 filepath = filepath[:-len(".py")]
774 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
775 if not [ 1 for match in selectors if match(modulename) ]:
777 if 'in_gdb' in modulename:
778 # These should only be imported from gdb.
780 module = __import__(modulename)
781 for x in modulename.split('.')[1:]:
782 module = getattr(module, x)
783 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
785 suite.addTest(doctest.DocTestSuite(module))
786 except ValueError: # no tests
790 class EndToEndTest(unittest.TestCase):
792 This is a test of build/*.srctree files, where srctree defines a full
793 directory structure and its header gives a list of commands to run.
795 cython_root = os.path.dirname(os.path.abspath(__file__))
797 def __init__(self, treefile, workdir, cleanup_workdir=True):
798 self.name = os.path.splitext(os.path.basename(treefile))[0]
799 self.treefile = treefile
800 self.workdir = os.path.join(workdir, self.name)
801 self.cleanup_workdir = cleanup_workdir
802 cython_syspath = self.cython_root
803 for path in sys.path[::-1]:
804 if path.startswith(self.cython_root):
805 # Py3 installation and refnanny build prepend their
806 # fixed paths to sys.path => prefer that over the
808 cython_syspath = path + os.pathsep + cython_syspath
809 self.cython_syspath = cython_syspath
810 unittest.TestCase.__init__(self)
812 def shortDescription(self):
813 return "End-to-end %s" % self.name
816 from Cython.TestUtils import unpack_source_tree
817 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
818 self.old_dir = os.getcwd()
819 os.chdir(self.workdir)
820 if self.workdir not in sys.path:
821 sys.path.insert(0, self.workdir)
824 if self.cleanup_workdir:
825 for trial in range(5):
827 shutil.rmtree(self.workdir)
832 os.chdir(self.old_dir)
835 commands = (self.commands
836 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
837 .replace("PYTHON", sys.executable))
839 old_path = os.environ.get('PYTHONPATH')
840 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
841 for command in commands.split('\n'):
842 if sys.version_info[:2] >= (2,4):
844 p = subprocess.Popen(commands,
845 stderr=subprocess.PIPE,
846 stdout=subprocess.PIPE,
848 out, err = p.communicate()
855 res = os.system(command)
856 self.assertEqual(0, res, "non-zero exit status")
859 os.environ['PYTHONPATH'] = old_path
861 del os.environ['PYTHONPATH']
864 # TODO: Support cython_freeze needed here as well.
865 # TODO: Windows support.
867 class EmbedTest(unittest.TestCase):
869 working_dir = "Demos/embed"
872 self.old_dir = os.getcwd()
873 os.chdir(self.working_dir)
875 "make PYTHON='%s' clean > /dev/null" % sys.executable)
880 "make PYTHON='%s' clean > /dev/null" % sys.executable)
883 os.chdir(self.old_dir)
885 def test_embed(self):
886 from distutils import sysconfig
887 libname = sysconfig.get_config_var('LIBRARY')
888 libdir = sysconfig.get_config_var('LIBDIR')
889 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
890 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
891 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
892 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
893 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
894 # report the error for the original directory
895 libdir = sysconfig.get_config_var('LIBDIR')
897 if sys.version_info[0] >=3 and CY3_DIR:
898 cython = os.path.join(CY3_DIR, cython)
899 cython = os.path.abspath(os.path.join('..', '..', cython))
900 self.assert_(os.system(
901 "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
903 os.remove('make.output')
907 class MissingDependencyExcluder:
908 def __init__(self, deps):
909 # deps: { module name : matcher func }
910 self.exclude_matchers = []
911 for mod, matcher in deps.items():
915 self.exclude_matchers.append(matcher)
916 self.tests_missing_deps = []
917 def __call__(self, testname):
918 for matcher in self.exclude_matchers:
919 if matcher(testname):
920 self.tests_missing_deps.append(testname)
924 class VersionDependencyExcluder:
925 def __init__(self, deps):
926 # deps: { version : matcher func }
927 from sys import version_info
928 self.exclude_matchers = []
929 for ver, (compare, matcher) in deps.items():
930 if compare(version_info, ver):
931 self.exclude_matchers.append(matcher)
932 self.tests_missing_deps = []
933 def __call__(self, testname):
934 for matcher in self.exclude_matchers:
935 if matcher(testname):
936 self.tests_missing_deps.append(testname)
940 class FileListExcluder:
942 def __init__(self, list_file):
946 for line in f.readlines():
948 if line and line[0] != '#':
949 self.excludes[line.split()[0]] = True
953 def __call__(self, testname):
954 return testname in self.excludes or testname.split('.')[-1] in self.excludes
956 def refactor_for_py3(distdir, cy3_dir):
957 # need to convert Cython sources first
958 import lib2to3.refactor
959 from distutils.util import copydir_run_2to3
960 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
961 if fix.split('fix_')[-1] not in ('next',)
963 if not os.path.exists(cy3_dir):
965 import distutils.log as dlog
966 dlog.set_threshold(dlog.INFO)
967 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
971 recursive-exclude Cython *
972 recursive-include Cython *.py *.pyx *.pxd
973 recursive-include Cython/Debugger/Tests *
977 sys.path.insert(0, cy3_dir)
979 for keep_2x_file in KEEP_2X_FILES:
980 destfile = os.path.join(cy3_dir, keep_2x_file)
981 shutil.copy(keep_2x_file, destfile)
983 class PendingThreadsError(RuntimeError):
988 def check_thread_termination(ignore_seen=True):
989 if threading is None: # no threading enabled in CPython
991 current = threading.currentThread()
992 blocking_threads = []
993 for t in threading.enumerate():
994 if not t.isAlive() or t == current:
999 blocking_threads.append(t)
1001 for seen in threads_seen:
1005 threads_seen.append(t)
1006 blocking_threads.append(t)
1007 if not blocking_threads:
1009 sys.stderr.write("warning: left-over threads found after running test:\n")
1010 for t in blocking_threads:
1011 sys.stderr.write('...%s\n' % repr(t))
1012 raise PendingThreadsError("left-over threads found after running test")
1016 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1018 from optparse import OptionParser
1019 parser = OptionParser()
1020 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1021 action="store_false", default=True,
1022 help="do not delete the generated C files (allows passing --no-cython on next run)")
1023 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1024 action="store_false", default=True,
1025 help="do not delete the generated shared libary files (allows manual module experimentation)")
1026 parser.add_option("--no-cython", dest="with_cython",
1027 action="store_false", default=True,
1028 help="do not run the Cython compiler, only the C compiler")
1029 parser.add_option("--compiler", dest="compiler", default=None,
1030 help="C compiler type")
1031 parser.add_option("--no-c", dest="use_c",
1032 action="store_false", default=True,
1033 help="do not test C compilation")
1034 parser.add_option("--no-cpp", dest="use_cpp",
1035 action="store_false", default=True,
1036 help="do not test C++ compilation")
1037 parser.add_option("--no-unit", dest="unittests",
1038 action="store_false", default=True,
1039 help="do not run the unit tests")
1040 parser.add_option("--no-doctest", dest="doctests",
1041 action="store_false", default=True,
1042 help="do not run the doctests")
1043 parser.add_option("--no-file", dest="filetests",
1044 action="store_false", default=True,
1045 help="do not run the file based tests")
1046 parser.add_option("--no-pyregr", dest="pyregr",
1047 action="store_false", default=True,
1048 help="do not run the regression tests of CPython in tests/pyregr/")
1049 parser.add_option("--cython-only", dest="cython_only",
1050 action="store_true", default=False,
1051 help="only compile pyx to c, do not run C compiler or run the tests")
1052 parser.add_option("--no-refnanny", dest="with_refnanny",
1053 action="store_false", default=True,
1054 help="do not regression test reference counting")
1055 parser.add_option("--no-fork", dest="fork",
1056 action="store_false", default=True,
1057 help="do not fork to run tests")
1058 parser.add_option("--sys-pyregr", dest="system_pyregr",
1059 action="store_true", default=False,
1060 help="run the regression tests of the CPython installation")
1061 parser.add_option("-x", "--exclude", dest="exclude",
1062 action="append", metavar="PATTERN",
1063 help="exclude tests matching the PATTERN")
1064 parser.add_option("-C", "--coverage", dest="coverage",
1065 action="store_true", default=False,
1066 help="collect source coverage data for the Compiler")
1067 parser.add_option("--coverage-xml", dest="coverage_xml",
1068 action="store_true", default=False,
1069 help="collect source coverage data for the Compiler in XML format")
1070 parser.add_option("-A", "--annotate", dest="annotate_source",
1071 action="store_true", default=True,
1072 help="generate annotated HTML versions of the test source files")
1073 parser.add_option("--no-annotate", dest="annotate_source",
1074 action="store_false",
1075 help="do not generate annotated HTML versions of the test source files")
1076 parser.add_option("-v", "--verbose", dest="verbosity",
1077 action="count", default=0,
1078 help="display test progress, pass twice to print test names")
1079 parser.add_option("-T", "--ticket", dest="tickets",
1081 help="a bug ticket number to run the respective test in 'tests/*'")
1082 parser.add_option("-3", dest="language_level",
1083 action="store_const", const=3, default=2,
1084 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1085 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1086 help="write test results in XML to directory DIR")
1087 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1088 action="store_true",
1089 help="exit without error code even on test failures")
1090 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1091 help="working directory")
1092 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1093 help="working directory")
1095 options, cmd_args = parser.parse_args()
1097 ROOTDIR = os.path.abspath(options.root_dir)
1098 WORKDIR = os.path.abspath(options.work_dir)
1100 if sys.version_info[0] >= 3:
1101 options.doctests = False
1102 if options.with_cython:
1104 # try if Cython is installed in a Py3 version
1105 import Cython.Compiler.Main
1107 # back out anything the import process loaded, then
1108 # 2to3 the Cython sources to make them re-importable
1109 cy_modules = [ name for name in sys.modules
1110 if name == 'Cython' or name.startswith('Cython.') ]
1111 for name in cy_modules:
1112 del sys.modules[name]
1113 # hasn't been refactored yet - do it now
1115 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1116 if sys.version_info >= (3,1):
1117 refactor_for_py3(DISTDIR, cy3_dir)
1118 elif os.path.isdir(cy3_dir):
1119 sys.path.insert(0, cy3_dir)
1121 options.with_cython = False
1123 WITH_CYTHON = options.with_cython
1125 if options.coverage or options.coverage_xml:
1127 options.coverage = options.coverage_xml = False
1129 from coverage import coverage as _coverage
1130 coverage = _coverage(branch=True)
1135 global CompilationOptions, pyrex_default_options, cython_compile
1136 from Cython.Compiler.Main import \
1137 CompilationOptions, \
1138 default_options as pyrex_default_options, \
1139 compile as cython_compile
1140 from Cython.Compiler import Errors
1141 Errors.LEVEL = 0 # show all warnings
1142 from Cython.Compiler import Options
1143 Options.generate_cleanup_code = 3 # complete cleanup code
1144 from Cython.Compiler import DebugFlags
1145 DebugFlags.debug_temp_code_comments = 1
1148 UNITTEST_MODULE = "Cython"
1149 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1151 if os.path.exists(WORKDIR):
1152 for path in os.listdir(WORKDIR):
1153 if path in ("support", "Cy3"): continue
1154 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1155 if not os.path.exists(WORKDIR):
1156 os.makedirs(WORKDIR)
1158 sys.stderr.write("Python %s\n" % sys.version)
1159 sys.stderr.write("\n")
1161 from Cython.Compiler.Version import version
1162 sys.stderr.write("Running tests against Cython %s\n" % version)
1164 sys.stderr.write("Running tests without Cython.\n")
1166 if options.with_refnanny:
1167 from pyximport.pyxbuild import pyx_to_dll
1168 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1170 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1171 sys.path.insert(0, os.path.split(libpath)[0])
1172 CFLAGS.append("-DCYTHON_REFNANNY=1")
1174 if options.xml_output_dir and options.fork:
1175 # doesn't currently work together
1176 sys.stderr.write("Disabling forked testing to support XML test output\n")
1177 options.fork = False
1179 if WITH_CYTHON and options.language_level == 3:
1180 sys.stderr.write("Using Cython language level 3.\n")
1182 sys.stderr.write("\n")
1186 for ticket_number in options.tickets:
1188 cmd_args.append('.*T%s$' % ticket_number)
1190 for selector in cmd_args:
1191 if selector.startswith('bugs'):
1195 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1197 selectors = [ lambda x:True ]
1199 # Chech which external modules are not present and exclude tests
1200 # which depends on them (by prefix)
1202 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1203 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1204 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1207 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1210 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1212 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1213 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1216 if options.compiler:
1217 COMPILER = options.compiler
1220 languages.append('c')
1222 languages.append('cpp')
1224 test_suite = unittest.TestSuite()
1226 if options.unittests:
1227 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1229 if options.doctests:
1230 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1232 if options.filetests and languages:
1233 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1234 options.annotate_source, options.cleanup_workdir,
1235 options.cleanup_sharedlibs, options.pyregr,
1236 options.cython_only, languages, test_bugs,
1237 options.fork, options.language_level)
1238 test_suite.addTest(filetests.build_suite())
1240 if options.system_pyregr and languages:
1241 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1242 options.annotate_source, options.cleanup_workdir,
1243 options.cleanup_sharedlibs, True,
1244 options.cython_only, languages, test_bugs,
1245 options.fork, options.language_level)
1247 filetests.handle_directory(
1248 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1251 if options.xml_output_dir:
1252 from Cython.Tests.xmlrunner import XMLTestRunner
1253 test_runner = XMLTestRunner(output=options.xml_output_dir,
1254 verbose=options.verbosity > 0)
1256 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1258 result = test_runner.run(test_suite)
1260 if options.coverage or options.coverage_xml:
1262 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1263 modules = [ module for name, module in sys.modules.items()
1264 if module is not None and
1265 name.startswith('Cython.Compiler.') and
1266 name[len('Cython.Compiler.'):] not in ignored_modules ]
1267 if options.coverage:
1268 coverage.report(modules, show_missing=0)
1269 if options.coverage_xml:
1270 coverage.xml_report(modules, outfile="coverage-report.xml")
1272 if missing_dep_excluder.tests_missing_deps:
1273 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1274 for test in missing_dep_excluder.tests_missing_deps:
1275 sys.stderr.write(" %s\n" % test)
1277 if options.with_refnanny:
1279 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1286 return_code = not result.wasSuccessful()
1289 check_thread_termination(ignore_seen=False)
1290 sys.exit(return_code)
1291 except PendingThreadsError:
1292 # normal program exit won't kill the threads, do it the hard way here
1293 os._exit(return_code)
1295 if __name__ == '__main__':
1298 except SystemExit: # <= Py2.4 ...
1301 traceback.print_exc()
1303 check_thread_termination(ignore_seen=False)
1304 except PendingThreadsError:
1305 # normal program exit won't kill the threads, do it the hard way here