16 from StringIO import StringIO
18 from io import StringIO
21 import cPickle as pickle
27 except ImportError: # No threads, no problems
31 from collections import defaultdict
33 class defaultdict(object):
34 def __init__(self, default_factory=lambda : None):
36 self.default_factory = default_factory
37 def __getitem__(self, key):
38 if key not in self._dict:
39 self._dict[key] = self.default_factory()
40 return self._dict[key]
41 def __setitem__(self, key, value):
42 self._dict[key] = value
44 return repr(self._dict)
49 from distutils.dist import Distribution
50 from distutils.core import Extension
51 from distutils.command.build_ext import build_ext as _build_ext
52 distutils_distro = Distribution()
54 if sys.platform == 'win32':
55 # TODO: Figure out why this hackery (see http://thread.gmane.org/gmane.comp.python.cython.devel/8280/).
56 config_files = distutils_distro.find_config_files()
57 try: config_files.remove('setup.cfg')
58 except ValueError: pass
59 distutils_distro.parse_config_files(config_files)
61 cfgfiles = distutils_distro.find_config_files()
62 try: cfgfiles.remove('setup.cfg')
63 except ValueError: pass
64 distutils_distro.parse_config_files(cfgfiles)
66 # Lists external modules, and a matcher matching tests
67 # which should be excluded if the module is not present.
68 # TODO: use tags for these
70 'numpy' : re.compile('.*\.numpy_.*').match,
71 'pstats' : re.compile('.*\.pstats_.*').match,
72 'posix' : re.compile('.*\.posix_.*').match,
75 def get_numpy_include_dirs():
77 return [numpy.get_include()]
81 # test name matcher , callable returning list
82 (re.compile('numpy_.*').match, get_numpy_include_dirs),
86 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
87 # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
88 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
91 (2,5) : (operator.lt, lambda x: x in ['run.any',
94 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
96 'run.pure_py', # decorators, with statement
98 # The next line should start (3,); but this is a dictionary, so
99 # we can only have one (3,) key. Since 2.7 is supposed to be the
100 # last 2.x release, things would have to change drastically for this
102 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
103 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
104 'compile.extsetslice',
105 'compile.extdelslice',
106 'run.special_methods_T561_py2']),
109 # files that should not be converted to Python 3 code with 2to3
111 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
112 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
113 os.path.join('Cython', 'Debugger', 'libcython.py'),
114 os.path.join('Cython', 'Debugger', 'libpython.py'),
118 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
119 CFLAGS = os.getenv('CFLAGS', '').split()
122 uncomputed = object()
125 res = f._cache.get(args, uncomputed)
126 if res is uncomputed:
127 res = f._cache[args] = f(*args)
131 def parse_tags(filepath):
132 tags = defaultdict(list)
133 for line in open(filepath):
141 tag = line[1:ix].strip()
142 values = line[ix+1:].split(',')
143 tags[tag].extend([value.strip() for value in values])
146 parse_tags = memoize(parse_tags)
149 class build_ext(_build_ext):
150 def build_extension(self, ext):
151 if ext.language == 'c++':
153 try: # Py2.7+ & Py3.2+
154 compiler_obj = self.compiler_obj
155 except AttributeError:
156 compiler_obj = self.compiler
157 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
160 _build_ext.build_extension(self, ext)
162 class ErrorWriter(object):
163 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
166 self.write = self.output.append
168 def _collect(self, collect_errors, collect_warnings):
169 s = ''.join(self.output)
171 for line in s.split('\n'):
172 match = self.match_error(line)
174 is_warning, line, column, message = match.groups()
175 if (is_warning and collect_warnings) or \
176 (not is_warning and collect_errors):
177 result.append( (int(line), int(column), message.strip()) )
179 return [ "%d:%d: %s" % values for values in result ]
182 return self._collect(True, False)
184 def getwarnings(self):
185 return self._collect(False, True)
188 return self._collect(True, True)
190 class TestBuilder(object):
191 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
192 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
193 languages, test_bugs, fork, language_level):
194 self.rootdir = rootdir
195 self.workdir = workdir
196 self.selectors = selectors
197 self.exclude_selectors = exclude_selectors
198 self.annotate = annotate
199 self.cleanup_workdir = cleanup_workdir
200 self.cleanup_sharedlibs = cleanup_sharedlibs
201 self.with_pyregr = with_pyregr
202 self.cython_only = cython_only
203 self.languages = languages
204 self.test_bugs = test_bugs
206 self.language_level = language_level
208 def build_suite(self):
209 suite = unittest.TestSuite()
210 filenames = os.listdir(self.rootdir)
212 for filename in filenames:
213 path = os.path.join(self.rootdir, filename)
214 if os.path.isdir(path):
215 if filename == 'pyregr' and not self.with_pyregr:
217 if filename == 'broken' and not self.test_bugs:
220 self.handle_directory(path, filename))
221 if sys.platform not in ['win32']:
222 # Non-Windows makefile.
223 if [1 for selector in self.selectors if selector("embedded")] \
224 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
225 suite.addTest(unittest.makeSuite(EmbedTest))
228 def handle_directory(self, path, context):
229 workdir = os.path.join(self.workdir, context)
230 if not os.path.exists(workdir):
233 suite = unittest.TestSuite()
234 filenames = os.listdir(path)
236 for filename in filenames:
237 filepath = os.path.join(path, filename)
238 module, ext = os.path.splitext(filename)
239 if ext not in ('.py', '.pyx', '.srctree'):
241 if filename.startswith('.'):
242 continue # certain emacs backup files
243 tags = parse_tags(filepath)
244 fqmodule = "%s.%s" % (context, module)
245 if not [ 1 for match in self.selectors
246 if match(fqmodule, tags) ]:
248 if self.exclude_selectors:
249 if [1 for match in self.exclude_selectors
250 if match(fqmodule, tags)]:
253 mode = 'run' # default
255 mode = tags['mode'][0]
256 elif context == 'pyregr':
259 if ext == '.srctree':
260 suite.addTest(EndToEndTest(filepath, workdir, self.cleanup_workdir))
263 # Choose the test suite.
265 if not filename.startswith('test_'):
267 test_class = CythonPyregrTestCase
269 if module.startswith("test_"):
270 test_class = CythonUnitTestCase
272 test_class = CythonRunTestCase
274 test_class = CythonCompileTestCase
276 for test in self.build_tests(test_class, path, workdir,
277 module, mode == 'error', tags):
279 if mode == 'run' and ext == '.py':
280 # additionally test file in real Python
281 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
285 def build_tests(self, test_class, path, workdir, module, expect_errors, tags):
287 if 'cpp' in tags['tag'] and 'cpp' in self.languages:
290 languages = self.languages[:1]
292 languages = self.languages
293 if 'cpp' in tags['tag'] and 'c' in languages:
294 languages = list(languages)
295 languages.remove('c')
296 tests = [ self.build_test(test_class, path, workdir, module,
297 language, expect_errors)
298 for language in languages ]
301 def build_test(self, test_class, path, workdir, module,
302 language, expect_errors):
303 workdir = os.path.join(workdir, language)
304 if not os.path.exists(workdir):
306 return test_class(path, workdir, module,
308 expect_errors=expect_errors,
309 annotate=self.annotate,
310 cleanup_workdir=self.cleanup_workdir,
311 cleanup_sharedlibs=self.cleanup_sharedlibs,
312 cython_only=self.cython_only,
314 language_level=self.language_level)
316 class CythonCompileTestCase(unittest.TestCase):
317 def __init__(self, test_directory, workdir, module, language='c',
318 expect_errors=False, annotate=False, cleanup_workdir=True,
319 cleanup_sharedlibs=True, cython_only=False, fork=True,
321 self.test_directory = test_directory
322 self.workdir = workdir
324 self.language = language
325 self.expect_errors = expect_errors
326 self.annotate = annotate
327 self.cleanup_workdir = cleanup_workdir
328 self.cleanup_sharedlibs = cleanup_sharedlibs
329 self.cython_only = cython_only
331 self.language_level = language_level
332 unittest.TestCase.__init__(self)
334 def shortDescription(self):
335 return "compiling (%s) %s" % (self.language, self.module)
338 if self.workdir not in sys.path:
339 sys.path.insert(0, self.workdir)
343 sys.path.remove(self.workdir)
347 del sys.modules[self.module]
350 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
351 cleanup_lib_files = self.cleanup_sharedlibs
352 if os.path.exists(self.workdir):
353 for rmfile in os.listdir(self.workdir):
354 if not cleanup_c_files:
355 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
357 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
359 if self.annotate and rmfile.endswith(".html"):
362 rmfile = os.path.join(self.workdir, rmfile)
363 if os.path.isdir(rmfile):
364 shutil.rmtree(rmfile, ignore_errors=True)
370 os.makedirs(self.workdir)
373 self.runCompileTest()
375 def runCompileTest(self):
376 self.compile(self.test_directory, self.module, self.workdir,
377 self.test_directory, self.expect_errors, self.annotate)
379 def find_module_source_file(self, source_file):
380 if not os.path.exists(source_file):
381 source_file = source_file[:-1]
384 def build_target_filename(self, module_name):
385 target = '%s.%s' % (module_name, self.language)
388 def copy_related_files(self, test_directory, target_directory, module_name):
389 is_related = re.compile('%s_.*[.].*' % module_name).match
390 for filename in os.listdir(test_directory):
391 if is_related(filename):
392 shutil.copy(os.path.join(test_directory, filename),
395 def find_source_files(self, workdir, module_name):
396 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
397 return [self.build_target_filename(module_name)] + [
398 filename for filename in os.listdir(workdir)
399 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
401 def split_source_and_output(self, test_directory, module, workdir):
402 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
403 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
405 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
407 for line in source_and_output:
409 if line.startswith("_ERRORS"):
415 source_and_output.close()
417 geterrors = out.geterrors
418 except AttributeError:
424 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
425 extra_compile_options=None):
426 include_dirs = INCLUDE_DIRS[:]
428 include_dirs.append(incdir)
429 source = self.find_module_source_file(
430 os.path.join(test_directory, module + '.pyx'))
431 target = os.path.join(targetdir, self.build_target_filename(module))
433 if extra_compile_options is None:
434 extra_compile_options = {}
439 from Cython.Compiler.Main import CompilationOptions
440 from Cython.Compiler.Main import compile as cython_compile
441 from Cython.Compiler.Main import default_options
443 options = CompilationOptions(
445 include_path = include_dirs,
446 output_file = target,
448 use_listing_file = False,
449 cplus = self.language == 'cpp',
450 language_level = self.language_level,
451 generate_pxi = False,
452 evaluate_tree_assertions = True,
453 **extra_compile_options
455 cython_compile(source, options=options,
456 full_module_name=module)
458 def run_distutils(self, test_directory, module, workdir, incdir,
459 extra_extension_args=None):
463 build_extension = build_ext(distutils_distro)
464 build_extension.include_dirs = INCLUDE_DIRS[:]
466 build_extension.include_dirs.append(incdir)
467 build_extension.finalize_options()
469 build_extension.compiler = COMPILER
470 ext_include_dirs = []
471 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
473 ext_include_dirs += get_additional_include_dirs()
474 ext_compile_flags = CFLAGS[:]
475 if build_extension.compiler == 'mingw32':
476 ext_compile_flags.append('-Wno-format')
477 if extra_extension_args is None:
478 extra_extension_args = {}
480 self.copy_related_files(test_directory, workdir, module)
481 extension = Extension(
483 sources = self.find_source_files(workdir, module),
484 include_dirs = ext_include_dirs,
485 extra_compile_args = ext_compile_flags,
486 **extra_extension_args
488 if self.language == 'cpp':
489 extension.language = 'c++'
490 build_extension.extensions = [extension]
491 build_extension.build_temp = workdir
492 build_extension.build_lib = workdir
493 build_extension.run()
497 def compile(self, test_directory, module, workdir, incdir,
498 expect_errors, annotate):
499 expected_errors = errors = ()
501 expected_errors = self.split_source_and_output(
502 test_directory, module, workdir)
503 test_directory = workdir
506 old_stderr = sys.stderr
508 sys.stderr = ErrorWriter()
509 self.run_cython(test_directory, module, workdir, incdir, annotate)
510 errors = sys.stderr.geterrors()
512 sys.stderr = old_stderr
514 if errors or expected_errors:
516 for expected, error in zip(expected_errors, errors):
517 self.assertEquals(expected, error)
518 if len(errors) < len(expected_errors):
519 expected_error = expected_errors[len(errors)]
520 self.assertEquals(expected_error, None)
521 elif len(errors) > len(expected_errors):
522 unexpected_error = errors[len(expected_errors)]
523 self.assertEquals(None, unexpected_error)
524 except AssertionError:
525 print("\n=== Expected errors: ===")
526 print('\n'.join(expected_errors))
527 print("\n\n=== Got errors: ===")
528 print('\n'.join(errors))
532 if not self.cython_only:
533 self.run_distutils(test_directory, module, workdir, incdir)
535 class CythonRunTestCase(CythonCompileTestCase):
536 def shortDescription(self):
537 return "compiling (%s) and running %s" % (self.language, self.module)
539 def run(self, result=None):
541 result = self.defaultTestResult()
542 result.startTest(self)
546 self.runCompileTest()
547 self.run_tests(result)
549 check_thread_termination()
551 result.addError(self, sys.exc_info())
552 result.stopTest(self)
558 def run_tests(self, result):
559 if not self.cython_only:
560 self.run_doctests(self.module, result)
562 def run_doctests(self, module_name, result):
563 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
564 doctest.DocTestSuite(module_name).run(result)
568 # fork to make sure we do not keep the tested module loaded
569 result_handle, result_file = tempfile.mkstemp()
570 os.close(result_handle)
578 partial_result = PartialTestResult(result)
579 tests = doctest.DocTestSuite(module_name)
580 tests.run(partial_result)
584 # importing failed, try to fake a test class
586 failureException=sys.exc_info()[1],
587 _shortDescription=self.shortDescription(),
589 partial_result.addError(tests, sys.exc_info())
591 output = open(result_file, 'wb')
592 pickle.dump(partial_result.data(), output)
594 traceback.print_exc()
598 os._exit(result_code)
601 cid, result_code = os.waitpid(child_id, 0)
602 # os.waitpid returns the child's result code in the
603 # upper byte of result_code, and the signal it was
604 # killed by in the lower byte
605 if result_code & 255:
606 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
607 (module_name, result_code & 255))
608 result_code = result_code >> 8
609 if result_code in (0,1):
610 input = open(result_file, 'rb')
612 PartialTestResult.join_results(result, pickle.load(input))
616 raise Exception("Tests in module '%s' exited with status %d" %
617 (module_name, result_code))
619 try: os.unlink(result_file)
622 class PureDoctestTestCase(unittest.TestCase):
623 def __init__(self, module_name, module_path):
624 self.module_name = module_name
625 self.module_path = module_path
626 unittest.TestCase.__init__(self, 'run')
628 def shortDescription(self):
629 return "running pure doctests in %s" % self.module_name
631 def run(self, result=None):
633 result = self.defaultTestResult()
634 loaded_module_name = 'pure_doctest__' + self.module_name
635 result.startTest(self)
640 m = imp.load_source(loaded_module_name, self.module_path)
642 doctest.DocTestSuite(m).run(result)
645 if loaded_module_name in sys.modules:
646 del sys.modules[loaded_module_name]
647 check_thread_termination()
649 result.addError(self, sys.exc_info())
650 result.stopTest(self)
656 is_private_field = re.compile('^_[^_]').match
658 class _FakeClass(object):
659 def __init__(self, **kwargs):
660 self._shortDescription = kwargs.get('module_name')
661 self.__dict__.update(kwargs)
662 def shortDescription(self):
663 return self._shortDescription
665 try: # Py2.7+ and Py3.2+
666 from unittest.runner import _TextTestResult
668 from unittest import _TextTestResult
670 class PartialTestResult(_TextTestResult):
671 def __init__(self, base_result):
672 _TextTestResult.__init__(
673 self, self._StringIO(), True,
674 base_result.dots + base_result.showAll*2)
676 def strip_error_results(self, results):
677 for test_case, error in results:
678 for attr_name in filter(is_private_field, dir(test_case)):
679 if attr_name == '_dt_test':
680 test_case._dt_test = _FakeClass(
681 name=test_case._dt_test.name)
682 elif attr_name != '_shortDescription':
683 setattr(test_case, attr_name, None)
686 self.strip_error_results(self.failures)
687 self.strip_error_results(self.errors)
688 return (self.failures, self.errors, self.testsRun,
689 self.stream.getvalue())
691 def join_results(result, data):
692 """Static method for merging the result back into the main
695 failures, errors, tests_run, output = data
697 result.stream.write(output)
698 result.errors.extend(errors)
699 result.failures.extend(failures)
700 result.testsRun += tests_run
702 join_results = staticmethod(join_results)
704 class _StringIO(StringIO):
705 def writeln(self, line):
706 self.write("%s\n" % line)
709 class CythonUnitTestCase(CythonRunTestCase):
710 def shortDescription(self):
711 return "compiling (%s) tests in %s" % (self.language, self.module)
713 def run_tests(self, result):
714 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
717 class CythonPyregrTestCase(CythonRunTestCase):
718 def _run_unittest(self, result, *classes):
719 """Run tests from unittest.TestCase-derived classes."""
720 valid_types = (unittest.TestSuite, unittest.TestCase)
721 suite = unittest.TestSuite()
723 if isinstance(cls, str):
724 if cls in sys.modules:
725 suite.addTest(unittest.findTestCases(sys.modules[cls]))
727 raise ValueError("str arguments must be keys in sys.modules")
728 elif isinstance(cls, valid_types):
731 suite.addTest(unittest.makeSuite(cls))
734 def _run_doctest(self, result, module):
735 self.run_doctests(module, result)
737 def run_tests(self, result):
739 from test import test_support as support
740 except ImportError: # Py3k
741 from test import support
743 def run_unittest(*classes):
744 return self._run_unittest(result, *classes)
745 def run_doctest(module, verbosity=None):
746 return self._run_doctest(result, module)
748 support.run_unittest = run_unittest
749 support.run_doctest = run_doctest
752 module = __import__(self.module)
753 if hasattr(module, 'test_main'):
755 except (unittest.SkipTest, support.ResourceDenied):
756 result.addSkip(self, 'ok')
758 include_debugger = sys.version_info[:2] > (2, 5)
760 def collect_unittests(path, module_prefix, suite, selectors):
761 def file_matches(filename):
762 return filename.startswith("Test") and filename.endswith(".py")
764 def package_matches(dirname):
765 return dirname == "Tests"
767 loader = unittest.TestLoader()
772 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
774 for dirpath, dirnames, filenames in os.walk(path):
775 if dirpath != path and "__init__.py" not in filenames:
776 skipped_dirs.append(dirpath + os.path.sep)
779 for dir in skipped_dirs:
780 if dirpath.startswith(dir):
784 parentname = os.path.split(dirpath)[-1]
785 if package_matches(parentname):
788 filepath = os.path.join(dirpath, f)[:-len(".py")]
789 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
790 if not [ 1 for match in selectors if match(modulename) ]:
792 module = __import__(modulename)
793 for x in modulename.split('.')[1:]:
794 module = getattr(module, x)
795 suite.addTests([loader.loadTestsFromModule(module)])
799 def collect_doctests(path, module_prefix, suite, selectors):
800 def package_matches(dirname):
801 if dirname == 'Debugger' and not include_debugger:
803 return dirname not in ("Mac", "Distutils", "Plex")
804 def file_matches(filename):
805 filename, ext = os.path.splitext(filename)
806 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
808 return (ext == '.py' and not
809 '~' in filename and not
810 '#' in filename and not
811 filename.startswith('.') and not
812 filename in blacklist)
813 import doctest, types
814 for dirpath, dirnames, filenames in os.walk(path):
815 for dir in list(dirnames):
816 if not package_matches(dir):
820 if not f.endswith('.py'): continue
821 filepath = os.path.join(dirpath, f)
822 if os.path.getsize(filepath) == 0: continue
823 filepath = filepath[:-len(".py")]
824 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
825 if not [ 1 for match in selectors if match(modulename) ]:
827 if 'in_gdb' in modulename:
828 # These should only be imported from gdb.
830 module = __import__(modulename)
831 for x in modulename.split('.')[1:]:
832 module = getattr(module, x)
833 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
835 suite.addTest(doctest.DocTestSuite(module))
836 except ValueError: # no tests
840 class EndToEndTest(unittest.TestCase):
842 This is a test of build/*.srctree files, where srctree defines a full
843 directory structure and its header gives a list of commands to run.
845 cython_root = os.path.dirname(os.path.abspath(__file__))
847 def __init__(self, treefile, workdir, cleanup_workdir=True):
848 self.name = os.path.splitext(os.path.basename(treefile))[0]
849 self.treefile = treefile
850 self.workdir = os.path.join(workdir, self.name)
851 self.cleanup_workdir = cleanup_workdir
852 cython_syspath = self.cython_root
853 for path in sys.path[::-1]:
854 if path.startswith(self.cython_root):
855 # Py3 installation and refnanny build prepend their
856 # fixed paths to sys.path => prefer that over the
858 cython_syspath = path + os.pathsep + cython_syspath
859 self.cython_syspath = cython_syspath
860 unittest.TestCase.__init__(self)
862 def shortDescription(self):
863 return "End-to-end %s" % self.name
866 from Cython.TestUtils import unpack_source_tree
867 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
868 self.old_dir = os.getcwd()
869 os.chdir(self.workdir)
870 if self.workdir not in sys.path:
871 sys.path.insert(0, self.workdir)
874 if self.cleanup_workdir:
875 for trial in range(5):
877 shutil.rmtree(self.workdir)
882 os.chdir(self.old_dir)
885 commands = (self.commands
886 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
887 .replace("PYTHON", sys.executable))
889 old_path = os.environ.get('PYTHONPATH')
890 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
891 for command in commands.split('\n'):
892 if sys.version_info[:2] >= (2,4):
894 p = subprocess.Popen(commands,
895 stderr=subprocess.PIPE,
896 stdout=subprocess.PIPE,
898 out, err = p.communicate()
905 res = os.system(command)
906 self.assertEqual(0, res, "non-zero exit status")
909 os.environ['PYTHONPATH'] = old_path
911 del os.environ['PYTHONPATH']
914 # TODO: Support cython_freeze needed here as well.
915 # TODO: Windows support.
917 class EmbedTest(unittest.TestCase):
919 working_dir = "Demos/embed"
922 self.old_dir = os.getcwd()
923 os.chdir(self.working_dir)
925 "make PYTHON='%s' clean > /dev/null" % sys.executable)
930 "make PYTHON='%s' clean > /dev/null" % sys.executable)
933 os.chdir(self.old_dir)
935 def test_embed(self):
936 from distutils import sysconfig
937 libname = sysconfig.get_config_var('LIBRARY')
938 libdir = sysconfig.get_config_var('LIBDIR')
939 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
940 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
941 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
942 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
943 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
944 # report the error for the original directory
945 libdir = sysconfig.get_config_var('LIBDIR')
947 if sys.version_info[0] >=3 and CY3_DIR:
948 cython = os.path.join(CY3_DIR, cython)
949 cython = os.path.abspath(os.path.join('..', '..', cython))
950 self.assert_(os.system(
951 "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
953 os.remove('make.output')
957 class MissingDependencyExcluder:
958 def __init__(self, deps):
959 # deps: { module name : matcher func }
960 self.exclude_matchers = []
961 for mod, matcher in deps.items():
965 self.exclude_matchers.append(matcher)
966 self.tests_missing_deps = []
967 def __call__(self, testname, tags=None):
968 for matcher in self.exclude_matchers:
969 if matcher(testname):
970 self.tests_missing_deps.append(testname)
974 class VersionDependencyExcluder:
975 def __init__(self, deps):
976 # deps: { version : matcher func }
977 from sys import version_info
978 self.exclude_matchers = []
979 for ver, (compare, matcher) in deps.items():
980 if compare(version_info, ver):
981 self.exclude_matchers.append(matcher)
982 self.tests_missing_deps = []
983 def __call__(self, testname, tags=None):
984 for matcher in self.exclude_matchers:
985 if matcher(testname):
986 self.tests_missing_deps.append(testname)
990 class FileListExcluder:
992 def __init__(self, list_file):
996 for line in f.readlines():
998 if line and line[0] != '#':
999 self.excludes[line.split()[0]] = True
1003 def __call__(self, testname, tags=None):
1005 return testname in self.excludes or testname.split('.')[-1] in self.excludes
1009 def __init__(self, tag, value):
1013 def __call__(self, testname, tags=None):
1017 return self.value in tags[self.tag]
1019 class RegExSelector:
1021 def __init__(self, pattern_string):
1022 self.pattern = re.compile(pattern_string, re.I|re.U)
1024 def __call__(self, testname, tags=None):
1025 return self.pattern.search(testname)
1027 def string_selector(s):
1030 return RegExSelector(s)
1032 return TagsSelector(s[:ix], s[ix+1:])
1035 def refactor_for_py3(distdir, cy3_dir):
1036 # need to convert Cython sources first
1037 import lib2to3.refactor
1038 from distutils.util import copydir_run_2to3
1039 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
1040 if fix.split('fix_')[-1] not in ('next',)
1042 if not os.path.exists(cy3_dir):
1043 os.makedirs(cy3_dir)
1044 import distutils.log as dlog
1045 dlog.set_threshold(dlog.INFO)
1046 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1050 recursive-exclude Cython *
1051 recursive-include Cython *.py *.pyx *.pxd
1052 recursive-include Cython/Debugger/Tests *
1056 sys.path.insert(0, cy3_dir)
1058 for keep_2x_file in KEEP_2X_FILES:
1059 destfile = os.path.join(cy3_dir, keep_2x_file)
1060 shutil.copy(keep_2x_file, destfile)
1062 class PendingThreadsError(RuntimeError):
1067 def check_thread_termination(ignore_seen=True):
1068 if threading is None: # no threading enabled in CPython
1070 current = threading.currentThread()
1071 blocking_threads = []
1072 for t in threading.enumerate():
1073 if not t.isAlive() or t == current:
1078 blocking_threads.append(t)
1080 for seen in threads_seen:
1084 threads_seen.append(t)
1085 blocking_threads.append(t)
1086 if not blocking_threads:
1088 sys.stderr.write("warning: left-over threads found after running test:\n")
1089 for t in blocking_threads:
1090 sys.stderr.write('...%s\n' % repr(t))
1091 raise PendingThreadsError("left-over threads found after running test")
1095 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1097 from optparse import OptionParser
1098 parser = OptionParser()
1099 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1100 action="store_false", default=True,
1101 help="do not delete the generated C files (allows passing --no-cython on next run)")
1102 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1103 action="store_false", default=True,
1104 help="do not delete the generated shared libary files (allows manual module experimentation)")
1105 parser.add_option("--no-cython", dest="with_cython",
1106 action="store_false", default=True,
1107 help="do not run the Cython compiler, only the C compiler")
1108 parser.add_option("--compiler", dest="compiler", default=None,
1109 help="C compiler type")
1110 parser.add_option("--no-c", dest="use_c",
1111 action="store_false", default=True,
1112 help="do not test C compilation")
1113 parser.add_option("--no-cpp", dest="use_cpp",
1114 action="store_false", default=True,
1115 help="do not test C++ compilation")
1116 parser.add_option("--no-unit", dest="unittests",
1117 action="store_false", default=True,
1118 help="do not run the unit tests")
1119 parser.add_option("--no-doctest", dest="doctests",
1120 action="store_false", default=True,
1121 help="do not run the doctests")
1122 parser.add_option("--no-file", dest="filetests",
1123 action="store_false", default=True,
1124 help="do not run the file based tests")
1125 parser.add_option("--no-pyregr", dest="pyregr",
1126 action="store_false", default=True,
1127 help="do not run the regression tests of CPython in tests/pyregr/")
1128 parser.add_option("--cython-only", dest="cython_only",
1129 action="store_true", default=False,
1130 help="only compile pyx to c, do not run C compiler or run the tests")
1131 parser.add_option("--no-refnanny", dest="with_refnanny",
1132 action="store_false", default=True,
1133 help="do not regression test reference counting")
1134 parser.add_option("--no-fork", dest="fork",
1135 action="store_false", default=True,
1136 help="do not fork to run tests")
1137 parser.add_option("--sys-pyregr", dest="system_pyregr",
1138 action="store_true", default=False,
1139 help="run the regression tests of the CPython installation")
1140 parser.add_option("-x", "--exclude", dest="exclude",
1141 action="append", metavar="PATTERN",
1142 help="exclude tests matching the PATTERN")
1143 parser.add_option("-C", "--coverage", dest="coverage",
1144 action="store_true", default=False,
1145 help="collect source coverage data for the Compiler")
1146 parser.add_option("--coverage-xml", dest="coverage_xml",
1147 action="store_true", default=False,
1148 help="collect source coverage data for the Compiler in XML format")
1149 parser.add_option("-A", "--annotate", dest="annotate_source",
1150 action="store_true", default=True,
1151 help="generate annotated HTML versions of the test source files")
1152 parser.add_option("--no-annotate", dest="annotate_source",
1153 action="store_false",
1154 help="do not generate annotated HTML versions of the test source files")
1155 parser.add_option("-v", "--verbose", dest="verbosity",
1156 action="count", default=0,
1157 help="display test progress, pass twice to print test names")
1158 parser.add_option("-T", "--ticket", dest="tickets",
1160 help="a bug ticket number to run the respective test in 'tests/*'")
1161 parser.add_option("-3", dest="language_level",
1162 action="store_const", const=3, default=2,
1163 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1164 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1165 help="write test results in XML to directory DIR")
1166 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1167 action="store_true",
1168 help="exit without error code even on test failures")
1169 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1170 help="working directory")
1171 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1172 help="working directory")
1174 options, cmd_args = parser.parse_args()
1176 ROOTDIR = os.path.abspath(options.root_dir)
1177 WORKDIR = os.path.abspath(options.work_dir)
1179 if sys.version_info[0] >= 3:
1180 options.doctests = False
1181 if options.with_cython:
1183 # try if Cython is installed in a Py3 version
1184 import Cython.Compiler.Main
1186 # back out anything the import process loaded, then
1187 # 2to3 the Cython sources to make them re-importable
1188 cy_modules = [ name for name in sys.modules
1189 if name == 'Cython' or name.startswith('Cython.') ]
1190 for name in cy_modules:
1191 del sys.modules[name]
1192 # hasn't been refactored yet - do it now
1194 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1195 if sys.version_info >= (3,1):
1196 refactor_for_py3(DISTDIR, cy3_dir)
1197 elif os.path.isdir(cy3_dir):
1198 sys.path.insert(0, cy3_dir)
1200 options.with_cython = False
1202 WITH_CYTHON = options.with_cython
1204 if options.coverage or options.coverage_xml:
1206 options.coverage = options.coverage_xml = False
1208 from coverage import coverage as _coverage
1209 coverage = _coverage(branch=True)
1214 global CompilationOptions, pyrex_default_options, cython_compile
1215 from Cython.Compiler.Main import \
1216 CompilationOptions, \
1217 default_options as pyrex_default_options, \
1218 compile as cython_compile
1219 from Cython.Compiler import Errors
1220 Errors.LEVEL = 0 # show all warnings
1221 from Cython.Compiler import Options
1222 Options.generate_cleanup_code = 3 # complete cleanup code
1223 from Cython.Compiler import DebugFlags
1224 DebugFlags.debug_temp_code_comments = 1
1227 UNITTEST_MODULE = "Cython"
1228 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1230 if os.path.exists(WORKDIR):
1231 for path in os.listdir(WORKDIR):
1232 if path in ("support", "Cy3"): continue
1233 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1234 if not os.path.exists(WORKDIR):
1235 os.makedirs(WORKDIR)
1237 sys.stderr.write("Python %s\n" % sys.version)
1238 sys.stderr.write("\n")
1240 from Cython.Compiler.Version import version
1241 sys.stderr.write("Running tests against Cython %s\n" % version)
1243 sys.stderr.write("Running tests without Cython.\n")
1245 if options.with_refnanny:
1246 from pyximport.pyxbuild import pyx_to_dll
1247 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1249 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1250 sys.path.insert(0, os.path.split(libpath)[0])
1251 CFLAGS.append("-DCYTHON_REFNANNY=1")
1253 if options.xml_output_dir and options.fork:
1254 # doesn't currently work together
1255 sys.stderr.write("Disabling forked testing to support XML test output\n")
1256 options.fork = False
1258 if WITH_CYTHON and options.language_level == 3:
1259 sys.stderr.write("Using Cython language level 3.\n")
1261 sys.stderr.write("\n")
1265 for ticket_number in options.tickets:
1267 cmd_args.append('.*T%s$' % ticket_number)
1269 for selector in cmd_args:
1270 if selector.startswith('bugs'):
1274 selectors = [ string_selector(r) for r in cmd_args ]
1276 selectors = [ lambda x, tags=None: True ]
1278 # Chech which external modules are not present and exclude tests
1279 # which depends on them (by prefix)
1281 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1282 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1283 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1286 exclude_selectors += [ string_selector(r) for r in options.exclude ]
1289 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1291 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1292 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1295 if options.compiler:
1296 COMPILER = options.compiler
1299 languages.append('c')
1301 languages.append('cpp')
1303 test_suite = unittest.TestSuite()
1305 if options.unittests:
1306 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1308 if options.doctests:
1309 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1311 if options.filetests and languages:
1312 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1313 options.annotate_source, options.cleanup_workdir,
1314 options.cleanup_sharedlibs, options.pyregr,
1315 options.cython_only, languages, test_bugs,
1316 options.fork, options.language_level)
1317 test_suite.addTest(filetests.build_suite())
1319 if options.system_pyregr and languages:
1320 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1321 options.annotate_source, options.cleanup_workdir,
1322 options.cleanup_sharedlibs, True,
1323 options.cython_only, languages, test_bugs,
1324 options.fork, options.language_level)
1326 filetests.handle_directory(
1327 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1330 if options.xml_output_dir:
1331 from Cython.Tests.xmlrunner import XMLTestRunner
1332 test_runner = XMLTestRunner(output=options.xml_output_dir,
1333 verbose=options.verbosity > 0)
1335 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1337 result = test_runner.run(test_suite)
1339 if options.coverage or options.coverage_xml:
1341 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1342 modules = [ module for name, module in sys.modules.items()
1343 if module is not None and
1344 name.startswith('Cython.Compiler.') and
1345 name[len('Cython.Compiler.'):] not in ignored_modules ]
1346 if options.coverage:
1347 coverage.report(modules, show_missing=0)
1348 if options.coverage_xml:
1349 coverage.xml_report(modules, outfile="coverage-report.xml")
1351 if missing_dep_excluder.tests_missing_deps:
1352 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1353 for test in missing_dep_excluder.tests_missing_deps:
1354 sys.stderr.write(" %s\n" % test)
1356 if options.with_refnanny:
1358 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1365 return_code = not result.wasSuccessful()
1368 check_thread_termination(ignore_seen=False)
1369 sys.exit(return_code)
1370 except PendingThreadsError:
1371 # normal program exit won't kill the threads, do it the hard way here
1372 os._exit(return_code)
1374 if __name__ == '__main__':
1377 except SystemExit: # <= Py2.4 ...
1380 traceback.print_exc()
1382 check_thread_termination(ignore_seen=False)
1383 except PendingThreadsError:
1384 # normal program exit won't kill the threads, do it the hard way here