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 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr', 'build']
67 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
69 # Lists external modules, and a matcher matching tests
70 # which should be excluded if the module is not present.
72 'numpy' : re.compile('.*\.numpy_.*').match,
73 'pstats' : re.compile('.*\.pstats_.*').match,
74 'posix' : re.compile('.*\.posix_.*').match,
77 def get_numpy_include_dirs():
79 return [numpy.get_include()]
82 # test name matcher , callable returning list
83 (re.compile('numpy_.*').match, get_numpy_include_dirs),
87 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
88 # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
89 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
92 (2,5) : (operator.lt, lambda x: x in ['run.any',
95 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
97 'run.pure_py', # decorators, with statement
99 # The next line should start (3,); but this is a dictionary, so
100 # we can only have one (3,) key. Since 2.7 is supposed to be the
101 # last 2.x release, things would have to change drastically for this
103 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
104 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
105 'compile.extsetslice',
106 'compile.extdelslice',
107 'run.special_methods_T561_py2']),
110 # files that should not be converted to Python 3 code with 2to3
112 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
113 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
114 os.path.join('Cython', 'Debugger', 'libcython.py'),
115 os.path.join('Cython', 'Debugger', 'libpython.py'),
119 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
120 CFLAGS = os.getenv('CFLAGS', '').split()
122 def parse_tags(filepath):
123 tags = defaultdict(list)
124 for line in open(filepath):
132 tag = line[1:ix].strip()
133 values = line[ix+1:].split(',')
134 tags[tag].extend([value.strip() for value in values])
137 class build_ext(_build_ext):
138 def build_extension(self, ext):
139 if ext.language == 'c++':
141 try: # Py2.7+ & Py3.2+
142 compiler_obj = self.compiler_obj
143 except AttributeError:
144 compiler_obj = self.compiler
145 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
148 _build_ext.build_extension(self, ext)
150 class ErrorWriter(object):
151 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
154 self.write = self.output.append
156 def _collect(self, collect_errors, collect_warnings):
157 s = ''.join(self.output)
159 for line in s.split('\n'):
160 match = self.match_error(line)
162 is_warning, line, column, message = match.groups()
163 if (is_warning and collect_warnings) or \
164 (not is_warning and collect_errors):
165 result.append( (int(line), int(column), message.strip()) )
167 return [ "%d:%d: %s" % values for values in result ]
170 return self._collect(True, False)
172 def getwarnings(self):
173 return self._collect(False, True)
176 return self._collect(True, True)
178 class TestBuilder(object):
179 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
180 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
181 languages, test_bugs, fork, language_level):
182 self.rootdir = rootdir
183 self.workdir = workdir
184 self.selectors = selectors
185 self.exclude_selectors = exclude_selectors
186 self.annotate = annotate
187 self.cleanup_workdir = cleanup_workdir
188 self.cleanup_sharedlibs = cleanup_sharedlibs
189 self.with_pyregr = with_pyregr
190 self.cython_only = cython_only
191 self.languages = languages
192 self.test_bugs = test_bugs
194 self.language_level = language_level
196 def build_suite(self):
197 suite = unittest.TestSuite()
198 test_dirs = TEST_DIRS
199 filenames = os.listdir(self.rootdir)
201 for filename in filenames:
202 if not WITH_CYTHON and filename == "errors":
203 # we won't get any errors without running Cython
205 path = os.path.join(self.rootdir, filename)
206 if os.path.isdir(path) and filename in test_dirs:
207 if filename == 'pyregr' and not self.with_pyregr:
210 self.handle_directory(path, filename))
211 if sys.platform not in ['win32']:
212 # Non-Windows makefile.
213 if [1 for selector in self.selectors if selector("embedded")] \
214 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
215 suite.addTest(unittest.makeSuite(EmbedTest))
218 def handle_directory(self, path, context):
219 workdir = os.path.join(self.workdir, context)
220 if not os.path.exists(workdir):
223 expect_errors = (context == 'errors')
224 suite = unittest.TestSuite()
225 filenames = os.listdir(path)
227 for filename in filenames:
228 if filename.endswith(".srctree"):
229 if not [ 1 for match in self.selectors if match(filename) ]:
231 if self.exclude_selectors:
232 if [1 for match in self.exclude_selectors if match(filename)]:
234 suite.addTest(EndToEndTest(os.path.join(path, filename), workdir, self.cleanup_workdir))
236 if not (filename.endswith(".pyx") or filename.endswith(".py")):
238 if filename.startswith('.'): continue # certain emacs backup files
239 if context == 'pyregr' and not filename.startswith('test_'):
241 module = os.path.splitext(filename)[0]
242 fqmodule = "%s.%s" % (context, module)
243 if not [ 1 for match in self.selectors
244 if match(fqmodule) ]:
246 if self.exclude_selectors:
247 if [1 for match in self.exclude_selectors if match(fqmodule)]:
249 if context == 'pyregr':
250 test_class = CythonPyregrTestCase
251 elif context in TEST_RUN_DIRS:
252 if module.startswith("test_"):
253 test_class = CythonUnitTestCase
255 test_class = CythonRunTestCase
257 test_class = CythonCompileTestCase
258 for test in self.build_tests(test_class, path, workdir,
259 module, expect_errors):
261 if context == 'run' and filename.endswith('.py'):
262 # additionally test file in real Python
263 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
266 def build_tests(self, test_class, path, workdir, module, expect_errors):
268 if 'cpp' in module and 'cpp' in self.languages:
271 languages = self.languages[:1]
273 languages = self.languages
274 if 'cpp' in module and 'c' in languages:
275 languages = list(languages)
276 languages.remove('c')
277 tests = [ self.build_test(test_class, path, workdir, module,
278 language, expect_errors)
279 for language in languages ]
282 def build_test(self, test_class, path, workdir, module,
283 language, expect_errors):
284 workdir = os.path.join(workdir, language)
285 if not os.path.exists(workdir):
287 return test_class(path, workdir, module,
289 expect_errors=expect_errors,
290 annotate=self.annotate,
291 cleanup_workdir=self.cleanup_workdir,
292 cleanup_sharedlibs=self.cleanup_sharedlibs,
293 cython_only=self.cython_only,
295 language_level=self.language_level)
297 class CythonCompileTestCase(unittest.TestCase):
298 def __init__(self, test_directory, workdir, module, language='c',
299 expect_errors=False, annotate=False, cleanup_workdir=True,
300 cleanup_sharedlibs=True, cython_only=False, fork=True,
302 self.test_directory = test_directory
303 self.workdir = workdir
305 self.language = language
306 self.expect_errors = expect_errors
307 self.annotate = annotate
308 self.cleanup_workdir = cleanup_workdir
309 self.cleanup_sharedlibs = cleanup_sharedlibs
310 self.cython_only = cython_only
312 self.language_level = language_level
313 unittest.TestCase.__init__(self)
315 def shortDescription(self):
316 return "compiling (%s) %s" % (self.language, self.module)
319 if self.workdir not in sys.path:
320 sys.path.insert(0, self.workdir)
324 sys.path.remove(self.workdir)
328 del sys.modules[self.module]
331 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
332 cleanup_lib_files = self.cleanup_sharedlibs
333 if os.path.exists(self.workdir):
334 for rmfile in os.listdir(self.workdir):
335 if not cleanup_c_files:
336 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
338 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
340 if self.annotate and rmfile.endswith(".html"):
343 rmfile = os.path.join(self.workdir, rmfile)
344 if os.path.isdir(rmfile):
345 shutil.rmtree(rmfile, ignore_errors=True)
351 os.makedirs(self.workdir)
354 self.runCompileTest()
356 def runCompileTest(self):
357 self.compile(self.test_directory, self.module, self.workdir,
358 self.test_directory, self.expect_errors, self.annotate)
360 def find_module_source_file(self, source_file):
361 if not os.path.exists(source_file):
362 source_file = source_file[:-1]
365 def build_target_filename(self, module_name):
366 target = '%s.%s' % (module_name, self.language)
369 def copy_related_files(self, test_directory, target_directory, module_name):
370 is_related = re.compile('%s_.*[.].*' % module_name).match
371 for filename in os.listdir(test_directory):
372 if is_related(filename):
373 shutil.copy(os.path.join(test_directory, filename),
376 def find_source_files(self, workdir, module_name):
377 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
378 return [self.build_target_filename(module_name)] + [
379 filename for filename in os.listdir(workdir)
380 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
382 def split_source_and_output(self, test_directory, module, workdir):
383 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
384 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
386 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
388 for line in source_and_output:
390 if line.startswith("_ERRORS"):
396 source_and_output.close()
398 geterrors = out.geterrors
399 except AttributeError:
405 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
406 extra_compile_options=None):
407 include_dirs = INCLUDE_DIRS[:]
409 include_dirs.append(incdir)
410 source = self.find_module_source_file(
411 os.path.join(test_directory, module + '.pyx'))
412 target = os.path.join(targetdir, self.build_target_filename(module))
414 if extra_compile_options is None:
415 extra_compile_options = {}
420 from Cython.Compiler.Main import CompilationOptions
421 from Cython.Compiler.Main import compile as cython_compile
422 from Cython.Compiler.Main import default_options
424 options = CompilationOptions(
426 include_path = include_dirs,
427 output_file = target,
429 use_listing_file = False,
430 cplus = self.language == 'cpp',
431 language_level = self.language_level,
432 generate_pxi = False,
433 evaluate_tree_assertions = True,
434 **extra_compile_options
436 cython_compile(source, options=options,
437 full_module_name=module)
439 def run_distutils(self, test_directory, module, workdir, incdir,
440 extra_extension_args=None):
444 build_extension = build_ext(distutils_distro)
445 build_extension.include_dirs = INCLUDE_DIRS[:]
447 build_extension.include_dirs.append(incdir)
448 build_extension.finalize_options()
450 build_extension.compiler = COMPILER
451 ext_include_dirs = []
452 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
454 ext_include_dirs += get_additional_include_dirs()
455 ext_compile_flags = CFLAGS[:]
456 if build_extension.compiler == 'mingw32':
457 ext_compile_flags.append('-Wno-format')
458 if extra_extension_args is None:
459 extra_extension_args = {}
461 self.copy_related_files(test_directory, workdir, module)
462 extension = Extension(
464 sources = self.find_source_files(workdir, module),
465 include_dirs = ext_include_dirs,
466 extra_compile_args = ext_compile_flags,
467 **extra_extension_args
469 if self.language == 'cpp':
470 extension.language = 'c++'
471 build_extension.extensions = [extension]
472 build_extension.build_temp = workdir
473 build_extension.build_lib = workdir
474 build_extension.run()
478 def compile(self, test_directory, module, workdir, incdir,
479 expect_errors, annotate):
480 expected_errors = errors = ()
482 expected_errors = self.split_source_and_output(
483 test_directory, module, workdir)
484 test_directory = workdir
487 old_stderr = sys.stderr
489 sys.stderr = ErrorWriter()
490 self.run_cython(test_directory, module, workdir, incdir, annotate)
491 errors = sys.stderr.geterrors()
493 sys.stderr = old_stderr
495 if errors or expected_errors:
497 for expected, error in zip(expected_errors, errors):
498 self.assertEquals(expected, error)
499 if len(errors) < len(expected_errors):
500 expected_error = expected_errors[len(errors)]
501 self.assertEquals(expected_error, None)
502 elif len(errors) > len(expected_errors):
503 unexpected_error = errors[len(expected_errors)]
504 self.assertEquals(None, unexpected_error)
505 except AssertionError:
506 print("\n=== Expected errors: ===")
507 print('\n'.join(expected_errors))
508 print("\n\n=== Got errors: ===")
509 print('\n'.join(errors))
513 if not self.cython_only:
514 self.run_distutils(test_directory, module, workdir, incdir)
516 class CythonRunTestCase(CythonCompileTestCase):
517 def shortDescription(self):
518 return "compiling (%s) and running %s" % (self.language, self.module)
520 def run(self, result=None):
522 result = self.defaultTestResult()
523 result.startTest(self)
527 self.runCompileTest()
528 self.run_tests(result)
530 check_thread_termination()
532 result.addError(self, sys.exc_info())
533 result.stopTest(self)
539 def run_tests(self, result):
540 if not self.cython_only:
541 self.run_doctests(self.module, result)
543 def run_doctests(self, module_name, result):
544 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
545 doctest.DocTestSuite(module_name).run(result)
549 # fork to make sure we do not keep the tested module loaded
550 result_handle, result_file = tempfile.mkstemp()
551 os.close(result_handle)
559 partial_result = PartialTestResult(result)
560 tests = doctest.DocTestSuite(module_name)
561 tests.run(partial_result)
565 # importing failed, try to fake a test class
567 failureException=sys.exc_info()[1],
568 _shortDescription=self.shortDescription(),
570 partial_result.addError(tests, sys.exc_info())
572 output = open(result_file, 'wb')
573 pickle.dump(partial_result.data(), output)
575 traceback.print_exc()
579 os._exit(result_code)
582 cid, result_code = os.waitpid(child_id, 0)
583 # os.waitpid returns the child's result code in the
584 # upper byte of result_code, and the signal it was
585 # killed by in the lower byte
586 if result_code & 255:
587 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
588 (module_name, result_code & 255))
589 result_code = result_code >> 8
590 if result_code in (0,1):
591 input = open(result_file, 'rb')
593 PartialTestResult.join_results(result, pickle.load(input))
597 raise Exception("Tests in module '%s' exited with status %d" %
598 (module_name, result_code))
600 try: os.unlink(result_file)
603 class PureDoctestTestCase(unittest.TestCase):
604 def __init__(self, module_name, module_path):
605 self.module_name = module_name
606 self.module_path = module_path
607 unittest.TestCase.__init__(self, 'run')
609 def shortDescription(self):
610 return "running pure doctests in %s" % self.module_name
612 def run(self, result=None):
614 result = self.defaultTestResult()
615 loaded_module_name = 'pure_doctest__' + self.module_name
616 result.startTest(self)
621 m = imp.load_source(loaded_module_name, self.module_path)
623 doctest.DocTestSuite(m).run(result)
626 if loaded_module_name in sys.modules:
627 del sys.modules[loaded_module_name]
628 check_thread_termination()
630 result.addError(self, sys.exc_info())
631 result.stopTest(self)
637 is_private_field = re.compile('^_[^_]').match
639 class _FakeClass(object):
640 def __init__(self, **kwargs):
641 self._shortDescription = kwargs.get('module_name')
642 self.__dict__.update(kwargs)
643 def shortDescription(self):
644 return self._shortDescription
646 try: # Py2.7+ and Py3.2+
647 from unittest.runner import _TextTestResult
649 from unittest import _TextTestResult
651 class PartialTestResult(_TextTestResult):
652 def __init__(self, base_result):
653 _TextTestResult.__init__(
654 self, self._StringIO(), True,
655 base_result.dots + base_result.showAll*2)
657 def strip_error_results(self, results):
658 for test_case, error in results:
659 for attr_name in filter(is_private_field, dir(test_case)):
660 if attr_name == '_dt_test':
661 test_case._dt_test = _FakeClass(
662 name=test_case._dt_test.name)
663 elif attr_name != '_shortDescription':
664 setattr(test_case, attr_name, None)
667 self.strip_error_results(self.failures)
668 self.strip_error_results(self.errors)
669 return (self.failures, self.errors, self.testsRun,
670 self.stream.getvalue())
672 def join_results(result, data):
673 """Static method for merging the result back into the main
676 failures, errors, tests_run, output = data
678 result.stream.write(output)
679 result.errors.extend(errors)
680 result.failures.extend(failures)
681 result.testsRun += tests_run
683 join_results = staticmethod(join_results)
685 class _StringIO(StringIO):
686 def writeln(self, line):
687 self.write("%s\n" % line)
690 class CythonUnitTestCase(CythonRunTestCase):
691 def shortDescription(self):
692 return "compiling (%s) tests in %s" % (self.language, self.module)
694 def run_tests(self, result):
695 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
698 class CythonPyregrTestCase(CythonRunTestCase):
699 def _run_unittest(self, result, *classes):
700 """Run tests from unittest.TestCase-derived classes."""
701 valid_types = (unittest.TestSuite, unittest.TestCase)
702 suite = unittest.TestSuite()
704 if isinstance(cls, str):
705 if cls in sys.modules:
706 suite.addTest(unittest.findTestCases(sys.modules[cls]))
708 raise ValueError("str arguments must be keys in sys.modules")
709 elif isinstance(cls, valid_types):
712 suite.addTest(unittest.makeSuite(cls))
715 def _run_doctest(self, result, module):
716 self.run_doctests(module, result)
718 def run_tests(self, result):
720 from test import test_support as support
721 except ImportError: # Py3k
722 from test import support
724 def run_unittest(*classes):
725 return self._run_unittest(result, *classes)
726 def run_doctest(module, verbosity=None):
727 return self._run_doctest(result, module)
729 support.run_unittest = run_unittest
730 support.run_doctest = run_doctest
733 module = __import__(self.module)
734 if hasattr(module, 'test_main'):
736 except (unittest.SkipTest, support.ResourceDenied):
737 result.addSkip(self, 'ok')
739 include_debugger = sys.version_info[:2] > (2, 5)
741 def collect_unittests(path, module_prefix, suite, selectors):
742 def file_matches(filename):
743 return filename.startswith("Test") and filename.endswith(".py")
745 def package_matches(dirname):
746 return dirname == "Tests"
748 loader = unittest.TestLoader()
753 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
755 for dirpath, dirnames, filenames in os.walk(path):
756 if dirpath != path and "__init__.py" not in filenames:
757 skipped_dirs.append(dirpath + os.path.sep)
760 for dir in skipped_dirs:
761 if dirpath.startswith(dir):
765 parentname = os.path.split(dirpath)[-1]
766 if package_matches(parentname):
769 filepath = os.path.join(dirpath, f)[:-len(".py")]
770 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
771 if not [ 1 for match in selectors if match(modulename) ]:
773 module = __import__(modulename)
774 for x in modulename.split('.')[1:]:
775 module = getattr(module, x)
776 suite.addTests([loader.loadTestsFromModule(module)])
780 def collect_doctests(path, module_prefix, suite, selectors):
781 def package_matches(dirname):
782 if dirname == 'Debugger' and not include_debugger:
784 return dirname not in ("Mac", "Distutils", "Plex")
785 def file_matches(filename):
786 filename, ext = os.path.splitext(filename)
787 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
789 return (ext == '.py' and not
790 '~' in filename and not
791 '#' in filename and not
792 filename.startswith('.') and not
793 filename in blacklist)
794 import doctest, types
795 for dirpath, dirnames, filenames in os.walk(path):
796 for dir in list(dirnames):
797 if not package_matches(dir):
801 if not f.endswith('.py'): continue
802 filepath = os.path.join(dirpath, f)
803 if os.path.getsize(filepath) == 0: continue
804 filepath = filepath[:-len(".py")]
805 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
806 if not [ 1 for match in selectors if match(modulename) ]:
808 if 'in_gdb' in modulename:
809 # These should only be imported from gdb.
811 module = __import__(modulename)
812 for x in modulename.split('.')[1:]:
813 module = getattr(module, x)
814 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
816 suite.addTest(doctest.DocTestSuite(module))
817 except ValueError: # no tests
821 class EndToEndTest(unittest.TestCase):
823 This is a test of build/*.srctree files, where srctree defines a full
824 directory structure and its header gives a list of commands to run.
826 cython_root = os.path.dirname(os.path.abspath(__file__))
828 def __init__(self, treefile, workdir, cleanup_workdir=True):
829 self.name = os.path.splitext(os.path.basename(treefile))[0]
830 self.treefile = treefile
831 self.workdir = os.path.join(workdir, self.name)
832 self.cleanup_workdir = cleanup_workdir
833 cython_syspath = self.cython_root
834 for path in sys.path[::-1]:
835 if path.startswith(self.cython_root):
836 # Py3 installation and refnanny build prepend their
837 # fixed paths to sys.path => prefer that over the
839 cython_syspath = path + os.pathsep + cython_syspath
840 self.cython_syspath = cython_syspath
841 unittest.TestCase.__init__(self)
843 def shortDescription(self):
844 return "End-to-end %s" % self.name
847 from Cython.TestUtils import unpack_source_tree
848 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
849 self.old_dir = os.getcwd()
850 os.chdir(self.workdir)
851 if self.workdir not in sys.path:
852 sys.path.insert(0, self.workdir)
855 if self.cleanup_workdir:
856 for trial in range(5):
858 shutil.rmtree(self.workdir)
863 os.chdir(self.old_dir)
866 commands = (self.commands
867 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
868 .replace("PYTHON", sys.executable))
870 old_path = os.environ.get('PYTHONPATH')
871 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
872 for command in commands.split('\n'):
873 if sys.version_info[:2] >= (2,4):
875 p = subprocess.Popen(commands,
876 stderr=subprocess.PIPE,
877 stdout=subprocess.PIPE,
879 out, err = p.communicate()
886 res = os.system(command)
887 self.assertEqual(0, res, "non-zero exit status")
890 os.environ['PYTHONPATH'] = old_path
892 del os.environ['PYTHONPATH']
895 # TODO: Support cython_freeze needed here as well.
896 # TODO: Windows support.
898 class EmbedTest(unittest.TestCase):
900 working_dir = "Demos/embed"
903 self.old_dir = os.getcwd()
904 os.chdir(self.working_dir)
906 "make PYTHON='%s' clean > /dev/null" % sys.executable)
911 "make PYTHON='%s' clean > /dev/null" % sys.executable)
914 os.chdir(self.old_dir)
916 def test_embed(self):
917 from distutils import sysconfig
918 libname = sysconfig.get_config_var('LIBRARY')
919 libdir = sysconfig.get_config_var('LIBDIR')
920 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
921 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
922 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
923 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
924 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
925 # report the error for the original directory
926 libdir = sysconfig.get_config_var('LIBDIR')
928 if sys.version_info[0] >=3 and CY3_DIR:
929 cython = os.path.join(CY3_DIR, cython)
930 cython = os.path.abspath(os.path.join('..', '..', cython))
931 self.assert_(os.system(
932 "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
934 os.remove('make.output')
938 class MissingDependencyExcluder:
939 def __init__(self, deps):
940 # deps: { module name : matcher func }
941 self.exclude_matchers = []
942 for mod, matcher in deps.items():
946 self.exclude_matchers.append(matcher)
947 self.tests_missing_deps = []
948 def __call__(self, testname):
949 for matcher in self.exclude_matchers:
950 if matcher(testname):
951 self.tests_missing_deps.append(testname)
955 class VersionDependencyExcluder:
956 def __init__(self, deps):
957 # deps: { version : matcher func }
958 from sys import version_info
959 self.exclude_matchers = []
960 for ver, (compare, matcher) in deps.items():
961 if compare(version_info, ver):
962 self.exclude_matchers.append(matcher)
963 self.tests_missing_deps = []
964 def __call__(self, testname):
965 for matcher in self.exclude_matchers:
966 if matcher(testname):
967 self.tests_missing_deps.append(testname)
971 class FileListExcluder:
973 def __init__(self, list_file):
977 for line in f.readlines():
979 if line and line[0] != '#':
980 self.excludes[line.split()[0]] = True
984 def __call__(self, testname):
985 return testname in self.excludes or testname.split('.')[-1] in self.excludes
987 def refactor_for_py3(distdir, cy3_dir):
988 # need to convert Cython sources first
989 import lib2to3.refactor
990 from distutils.util import copydir_run_2to3
991 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
992 if fix.split('fix_')[-1] not in ('next',)
994 if not os.path.exists(cy3_dir):
996 import distutils.log as dlog
997 dlog.set_threshold(dlog.INFO)
998 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1002 recursive-exclude Cython *
1003 recursive-include Cython *.py *.pyx *.pxd
1004 recursive-include Cython/Debugger/Tests *
1008 sys.path.insert(0, cy3_dir)
1010 for keep_2x_file in KEEP_2X_FILES:
1011 destfile = os.path.join(cy3_dir, keep_2x_file)
1012 shutil.copy(keep_2x_file, destfile)
1014 class PendingThreadsError(RuntimeError):
1019 def check_thread_termination(ignore_seen=True):
1020 if threading is None: # no threading enabled in CPython
1022 current = threading.currentThread()
1023 blocking_threads = []
1024 for t in threading.enumerate():
1025 if not t.isAlive() or t == current:
1030 blocking_threads.append(t)
1032 for seen in threads_seen:
1036 threads_seen.append(t)
1037 blocking_threads.append(t)
1038 if not blocking_threads:
1040 sys.stderr.write("warning: left-over threads found after running test:\n")
1041 for t in blocking_threads:
1042 sys.stderr.write('...%s\n' % repr(t))
1043 raise PendingThreadsError("left-over threads found after running test")
1047 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1049 from optparse import OptionParser
1050 parser = OptionParser()
1051 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1052 action="store_false", default=True,
1053 help="do not delete the generated C files (allows passing --no-cython on next run)")
1054 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1055 action="store_false", default=True,
1056 help="do not delete the generated shared libary files (allows manual module experimentation)")
1057 parser.add_option("--no-cython", dest="with_cython",
1058 action="store_false", default=True,
1059 help="do not run the Cython compiler, only the C compiler")
1060 parser.add_option("--compiler", dest="compiler", default=None,
1061 help="C compiler type")
1062 parser.add_option("--no-c", dest="use_c",
1063 action="store_false", default=True,
1064 help="do not test C compilation")
1065 parser.add_option("--no-cpp", dest="use_cpp",
1066 action="store_false", default=True,
1067 help="do not test C++ compilation")
1068 parser.add_option("--no-unit", dest="unittests",
1069 action="store_false", default=True,
1070 help="do not run the unit tests")
1071 parser.add_option("--no-doctest", dest="doctests",
1072 action="store_false", default=True,
1073 help="do not run the doctests")
1074 parser.add_option("--no-file", dest="filetests",
1075 action="store_false", default=True,
1076 help="do not run the file based tests")
1077 parser.add_option("--no-pyregr", dest="pyregr",
1078 action="store_false", default=True,
1079 help="do not run the regression tests of CPython in tests/pyregr/")
1080 parser.add_option("--cython-only", dest="cython_only",
1081 action="store_true", default=False,
1082 help="only compile pyx to c, do not run C compiler or run the tests")
1083 parser.add_option("--no-refnanny", dest="with_refnanny",
1084 action="store_false", default=True,
1085 help="do not regression test reference counting")
1086 parser.add_option("--no-fork", dest="fork",
1087 action="store_false", default=True,
1088 help="do not fork to run tests")
1089 parser.add_option("--sys-pyregr", dest="system_pyregr",
1090 action="store_true", default=False,
1091 help="run the regression tests of the CPython installation")
1092 parser.add_option("-x", "--exclude", dest="exclude",
1093 action="append", metavar="PATTERN",
1094 help="exclude tests matching the PATTERN")
1095 parser.add_option("-C", "--coverage", dest="coverage",
1096 action="store_true", default=False,
1097 help="collect source coverage data for the Compiler")
1098 parser.add_option("--coverage-xml", dest="coverage_xml",
1099 action="store_true", default=False,
1100 help="collect source coverage data for the Compiler in XML format")
1101 parser.add_option("-A", "--annotate", dest="annotate_source",
1102 action="store_true", default=True,
1103 help="generate annotated HTML versions of the test source files")
1104 parser.add_option("--no-annotate", dest="annotate_source",
1105 action="store_false",
1106 help="do not generate annotated HTML versions of the test source files")
1107 parser.add_option("-v", "--verbose", dest="verbosity",
1108 action="count", default=0,
1109 help="display test progress, pass twice to print test names")
1110 parser.add_option("-T", "--ticket", dest="tickets",
1112 help="a bug ticket number to run the respective test in 'tests/*'")
1113 parser.add_option("-3", dest="language_level",
1114 action="store_const", const=3, default=2,
1115 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1116 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1117 help="write test results in XML to directory DIR")
1118 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1119 action="store_true",
1120 help="exit without error code even on test failures")
1121 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1122 help="working directory")
1123 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1124 help="working directory")
1126 options, cmd_args = parser.parse_args()
1128 ROOTDIR = os.path.abspath(options.root_dir)
1129 WORKDIR = os.path.abspath(options.work_dir)
1131 if sys.version_info[0] >= 3:
1132 options.doctests = False
1133 if options.with_cython:
1135 # try if Cython is installed in a Py3 version
1136 import Cython.Compiler.Main
1138 # back out anything the import process loaded, then
1139 # 2to3 the Cython sources to make them re-importable
1140 cy_modules = [ name for name in sys.modules
1141 if name == 'Cython' or name.startswith('Cython.') ]
1142 for name in cy_modules:
1143 del sys.modules[name]
1144 # hasn't been refactored yet - do it now
1146 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1147 if sys.version_info >= (3,1):
1148 refactor_for_py3(DISTDIR, cy3_dir)
1149 elif os.path.isdir(cy3_dir):
1150 sys.path.insert(0, cy3_dir)
1152 options.with_cython = False
1154 WITH_CYTHON = options.with_cython
1156 if options.coverage or options.coverage_xml:
1158 options.coverage = options.coverage_xml = False
1160 from coverage import coverage as _coverage
1161 coverage = _coverage(branch=True)
1166 global CompilationOptions, pyrex_default_options, cython_compile
1167 from Cython.Compiler.Main import \
1168 CompilationOptions, \
1169 default_options as pyrex_default_options, \
1170 compile as cython_compile
1171 from Cython.Compiler import Errors
1172 Errors.LEVEL = 0 # show all warnings
1173 from Cython.Compiler import Options
1174 Options.generate_cleanup_code = 3 # complete cleanup code
1175 from Cython.Compiler import DebugFlags
1176 DebugFlags.debug_temp_code_comments = 1
1179 UNITTEST_MODULE = "Cython"
1180 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1182 if os.path.exists(WORKDIR):
1183 for path in os.listdir(WORKDIR):
1184 if path in ("support", "Cy3"): continue
1185 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1186 if not os.path.exists(WORKDIR):
1187 os.makedirs(WORKDIR)
1189 sys.stderr.write("Python %s\n" % sys.version)
1190 sys.stderr.write("\n")
1192 from Cython.Compiler.Version import version
1193 sys.stderr.write("Running tests against Cython %s\n" % version)
1195 sys.stderr.write("Running tests without Cython.\n")
1197 if options.with_refnanny:
1198 from pyximport.pyxbuild import pyx_to_dll
1199 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1201 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1202 sys.path.insert(0, os.path.split(libpath)[0])
1203 CFLAGS.append("-DCYTHON_REFNANNY=1")
1205 if options.xml_output_dir and options.fork:
1206 # doesn't currently work together
1207 sys.stderr.write("Disabling forked testing to support XML test output\n")
1208 options.fork = False
1210 if WITH_CYTHON and options.language_level == 3:
1211 sys.stderr.write("Using Cython language level 3.\n")
1213 sys.stderr.write("\n")
1217 for ticket_number in options.tickets:
1219 cmd_args.append('.*T%s$' % ticket_number)
1221 for selector in cmd_args:
1222 if selector.startswith('bugs'):
1226 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1228 selectors = [ lambda x:True ]
1230 # Chech which external modules are not present and exclude tests
1231 # which depends on them (by prefix)
1233 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1234 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1235 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1238 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1241 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1243 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1244 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1247 if options.compiler:
1248 COMPILER = options.compiler
1251 languages.append('c')
1253 languages.append('cpp')
1255 test_suite = unittest.TestSuite()
1257 if options.unittests:
1258 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1260 if options.doctests:
1261 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1263 if options.filetests and languages:
1264 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1265 options.annotate_source, options.cleanup_workdir,
1266 options.cleanup_sharedlibs, options.pyregr,
1267 options.cython_only, languages, test_bugs,
1268 options.fork, options.language_level)
1269 test_suite.addTest(filetests.build_suite())
1271 if options.system_pyregr and languages:
1272 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1273 options.annotate_source, options.cleanup_workdir,
1274 options.cleanup_sharedlibs, True,
1275 options.cython_only, languages, test_bugs,
1276 options.fork, options.language_level)
1278 filetests.handle_directory(
1279 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1282 if options.xml_output_dir:
1283 from Cython.Tests.xmlrunner import XMLTestRunner
1284 test_runner = XMLTestRunner(output=options.xml_output_dir,
1285 verbose=options.verbosity > 0)
1287 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1289 result = test_runner.run(test_suite)
1291 if options.coverage or options.coverage_xml:
1293 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1294 modules = [ module for name, module in sys.modules.items()
1295 if module is not None and
1296 name.startswith('Cython.Compiler.') and
1297 name[len('Cython.Compiler.'):] not in ignored_modules ]
1298 if options.coverage:
1299 coverage.report(modules, show_missing=0)
1300 if options.coverage_xml:
1301 coverage.xml_report(modules, outfile="coverage-report.xml")
1303 if missing_dep_excluder.tests_missing_deps:
1304 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1305 for test in missing_dep_excluder.tests_missing_deps:
1306 sys.stderr.write(" %s\n" % test)
1308 if options.with_refnanny:
1310 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1317 return_code = not result.wasSuccessful()
1320 check_thread_termination(ignore_seen=False)
1321 sys.exit(return_code)
1322 except PendingThreadsError:
1323 # normal program exit won't kill the threads, do it the hard way here
1324 os._exit(return_code)
1326 if __name__ == '__main__':
1329 except SystemExit: # <= Py2.4 ...
1332 traceback.print_exc()
1334 check_thread_termination(ignore_seen=False)
1335 except PendingThreadsError:
1336 # normal program exit won't kill the threads, do it the hard way here