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 # TODO: use tags for these
85 # test name matcher , callable returning list
86 (re.compile('numpy_.*').match, get_numpy_include_dirs),
90 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
91 # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
92 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
95 (2,5) : (operator.lt, lambda x: x in ['run.any',
98 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
100 'run.pure_py', # decorators, with statement
102 # The next line should start (3,); but this is a dictionary, so
103 # we can only have one (3,) key. Since 2.7 is supposed to be the
104 # last 2.x release, things would have to change drastically for this
106 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
107 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
108 'compile.extsetslice',
109 'compile.extdelslice',
110 'run.special_methods_T561_py2']),
113 # files that should not be converted to Python 3 code with 2to3
115 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
116 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
117 os.path.join('Cython', 'Debugger', 'libcython.py'),
118 os.path.join('Cython', 'Debugger', 'libpython.py'),
122 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
123 CFLAGS = os.getenv('CFLAGS', '').split()
126 uncomputed = object()
129 res = f._cache.get(args, uncomputed)
130 if res is uncomputed:
131 res = f._cache[args] = f(*args)
136 def parse_tags(filepath):
137 tags = defaultdict(list)
138 for line in open(filepath):
146 tag = line[1:ix].strip()
147 values = line[ix+1:].split(',')
148 tags[tag].extend([value.strip() for value in values])
151 class build_ext(_build_ext):
152 def build_extension(self, ext):
153 if ext.language == 'c++':
155 try: # Py2.7+ & Py3.2+
156 compiler_obj = self.compiler_obj
157 except AttributeError:
158 compiler_obj = self.compiler
159 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
162 _build_ext.build_extension(self, ext)
164 class ErrorWriter(object):
165 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
168 self.write = self.output.append
170 def _collect(self, collect_errors, collect_warnings):
171 s = ''.join(self.output)
173 for line in s.split('\n'):
174 match = self.match_error(line)
176 is_warning, line, column, message = match.groups()
177 if (is_warning and collect_warnings) or \
178 (not is_warning and collect_errors):
179 result.append( (int(line), int(column), message.strip()) )
181 return [ "%d:%d: %s" % values for values in result ]
184 return self._collect(True, False)
186 def getwarnings(self):
187 return self._collect(False, True)
190 return self._collect(True, True)
192 class TestBuilder(object):
193 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
194 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
195 languages, test_bugs, fork, language_level):
196 self.rootdir = rootdir
197 self.workdir = workdir
198 self.selectors = selectors
199 self.exclude_selectors = exclude_selectors
200 self.annotate = annotate
201 self.cleanup_workdir = cleanup_workdir
202 self.cleanup_sharedlibs = cleanup_sharedlibs
203 self.with_pyregr = with_pyregr
204 self.cython_only = cython_only
205 self.languages = languages
206 self.test_bugs = test_bugs
208 self.language_level = language_level
210 def build_suite(self):
211 suite = unittest.TestSuite()
212 test_dirs = TEST_DIRS
213 filenames = os.listdir(self.rootdir)
215 for filename in filenames:
216 path = os.path.join(self.rootdir, filename)
217 if os.path.isdir(path) and filename in test_dirs:
218 if filename == 'pyregr' and not self.with_pyregr:
221 self.handle_directory(path, filename))
222 if sys.platform not in ['win32']:
223 # Non-Windows makefile.
224 if [1 for selector in self.selectors if selector("embedded")] \
225 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
226 suite.addTest(unittest.makeSuite(EmbedTest))
229 def handle_directory(self, path, context):
230 workdir = os.path.join(self.workdir, context)
231 if not os.path.exists(workdir):
234 suite = unittest.TestSuite()
235 filenames = os.listdir(path)
237 for filename in filenames:
238 filepath = os.path.join(path, filename)
239 module, ext = os.path.splitext(filename)
240 if ext not in ('.py', '.pyx', '.srctree'):
242 if filename.startswith('.'):
243 continue # certain emacs backup files
244 tags = parse_tags(filepath)
245 fqmodule = "%s.%s" % (context, module)
246 if not [ 1 for match in self.selectors
247 if match(fqmodule, tags) ]:
249 if self.exclude_selectors:
250 if [1 for match in self.exclude_selectors
251 if match(fqmodule, tags)]:
254 mode = 'run' # default
256 mode = tags['mode'][0]
257 elif context == 'pyregr':
260 if ext == '.srctree':
261 suite.addTest(EndToEndTest(filepath, workdir, self.cleanup_workdir))
264 # Choose the test suite.
266 if not filename.startswith('test_'):
268 test_class = CythonPyregrTestCase
270 if module.startswith("test_"):
271 test_class = CythonUnitTestCase
273 test_class = CythonRunTestCase
275 test_class = CythonCompileTestCase
277 for test in self.build_tests(test_class, path, workdir,
278 module, mode == 'error', tags):
280 if mode == 'run' and ext == '.py':
281 # additionally test file in real Python
282 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
286 def build_tests(self, test_class, path, workdir, module, expect_errors, tags):
288 if 'cpp' in tags['tag'] and 'cpp' in self.languages:
291 languages = self.languages[:1]
293 languages = self.languages
294 if 'cpp' in tags['tag'] and 'c' in languages:
295 languages = list(languages)
296 languages.remove('c')
297 tests = [ self.build_test(test_class, path, workdir, module,
298 language, expect_errors)
299 for language in languages ]
302 def build_test(self, test_class, path, workdir, module,
303 language, expect_errors):
304 workdir = os.path.join(workdir, language)
305 if not os.path.exists(workdir):
307 return test_class(path, workdir, module,
309 expect_errors=expect_errors,
310 annotate=self.annotate,
311 cleanup_workdir=self.cleanup_workdir,
312 cleanup_sharedlibs=self.cleanup_sharedlibs,
313 cython_only=self.cython_only,
315 language_level=self.language_level)
317 class CythonCompileTestCase(unittest.TestCase):
318 def __init__(self, test_directory, workdir, module, language='c',
319 expect_errors=False, annotate=False, cleanup_workdir=True,
320 cleanup_sharedlibs=True, cython_only=False, fork=True,
322 self.test_directory = test_directory
323 self.workdir = workdir
325 self.language = language
326 self.expect_errors = expect_errors
327 self.annotate = annotate
328 self.cleanup_workdir = cleanup_workdir
329 self.cleanup_sharedlibs = cleanup_sharedlibs
330 self.cython_only = cython_only
332 self.language_level = language_level
333 unittest.TestCase.__init__(self)
335 def shortDescription(self):
336 return "compiling (%s) %s" % (self.language, self.module)
339 if self.workdir not in sys.path:
340 sys.path.insert(0, self.workdir)
344 sys.path.remove(self.workdir)
348 del sys.modules[self.module]
351 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
352 cleanup_lib_files = self.cleanup_sharedlibs
353 if os.path.exists(self.workdir):
354 for rmfile in os.listdir(self.workdir):
355 if not cleanup_c_files:
356 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
358 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
360 if self.annotate and rmfile.endswith(".html"):
363 rmfile = os.path.join(self.workdir, rmfile)
364 if os.path.isdir(rmfile):
365 shutil.rmtree(rmfile, ignore_errors=True)
371 os.makedirs(self.workdir)
374 self.runCompileTest()
376 def runCompileTest(self):
377 self.compile(self.test_directory, self.module, self.workdir,
378 self.test_directory, self.expect_errors, self.annotate)
380 def find_module_source_file(self, source_file):
381 if not os.path.exists(source_file):
382 source_file = source_file[:-1]
385 def build_target_filename(self, module_name):
386 target = '%s.%s' % (module_name, self.language)
389 def copy_related_files(self, test_directory, target_directory, module_name):
390 is_related = re.compile('%s_.*[.].*' % module_name).match
391 for filename in os.listdir(test_directory):
392 if is_related(filename):
393 shutil.copy(os.path.join(test_directory, filename),
396 def find_source_files(self, workdir, module_name):
397 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
398 return [self.build_target_filename(module_name)] + [
399 filename for filename in os.listdir(workdir)
400 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
402 def split_source_and_output(self, test_directory, module, workdir):
403 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
404 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
406 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
408 for line in source_and_output:
410 if line.startswith("_ERRORS"):
416 source_and_output.close()
418 geterrors = out.geterrors
419 except AttributeError:
425 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
426 extra_compile_options=None):
427 include_dirs = INCLUDE_DIRS[:]
429 include_dirs.append(incdir)
430 source = self.find_module_source_file(
431 os.path.join(test_directory, module + '.pyx'))
432 target = os.path.join(targetdir, self.build_target_filename(module))
434 if extra_compile_options is None:
435 extra_compile_options = {}
440 from Cython.Compiler.Main import CompilationOptions
441 from Cython.Compiler.Main import compile as cython_compile
442 from Cython.Compiler.Main import default_options
444 options = CompilationOptions(
446 include_path = include_dirs,
447 output_file = target,
449 use_listing_file = False,
450 cplus = self.language == 'cpp',
451 language_level = self.language_level,
452 generate_pxi = False,
453 evaluate_tree_assertions = True,
454 **extra_compile_options
456 cython_compile(source, options=options,
457 full_module_name=module)
459 def run_distutils(self, test_directory, module, workdir, incdir,
460 extra_extension_args=None):
464 build_extension = build_ext(distutils_distro)
465 build_extension.include_dirs = INCLUDE_DIRS[:]
467 build_extension.include_dirs.append(incdir)
468 build_extension.finalize_options()
470 build_extension.compiler = COMPILER
471 ext_include_dirs = []
472 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
474 ext_include_dirs += get_additional_include_dirs()
475 ext_compile_flags = CFLAGS[:]
476 if build_extension.compiler == 'mingw32':
477 ext_compile_flags.append('-Wno-format')
478 if extra_extension_args is None:
479 extra_extension_args = {}
481 self.copy_related_files(test_directory, workdir, module)
482 extension = Extension(
484 sources = self.find_source_files(workdir, module),
485 include_dirs = ext_include_dirs,
486 extra_compile_args = ext_compile_flags,
487 **extra_extension_args
489 if self.language == 'cpp':
490 extension.language = 'c++'
491 build_extension.extensions = [extension]
492 build_extension.build_temp = workdir
493 build_extension.build_lib = workdir
494 build_extension.run()
498 def compile(self, test_directory, module, workdir, incdir,
499 expect_errors, annotate):
500 expected_errors = errors = ()
502 expected_errors = self.split_source_and_output(
503 test_directory, module, workdir)
504 test_directory = workdir
507 old_stderr = sys.stderr
509 sys.stderr = ErrorWriter()
510 self.run_cython(test_directory, module, workdir, incdir, annotate)
511 errors = sys.stderr.geterrors()
513 sys.stderr = old_stderr
515 if errors or expected_errors:
517 for expected, error in zip(expected_errors, errors):
518 self.assertEquals(expected, error)
519 if len(errors) < len(expected_errors):
520 expected_error = expected_errors[len(errors)]
521 self.assertEquals(expected_error, None)
522 elif len(errors) > len(expected_errors):
523 unexpected_error = errors[len(expected_errors)]
524 self.assertEquals(None, unexpected_error)
525 except AssertionError:
526 print("\n=== Expected errors: ===")
527 print('\n'.join(expected_errors))
528 print("\n\n=== Got errors: ===")
529 print('\n'.join(errors))
533 if not self.cython_only:
534 self.run_distutils(test_directory, module, workdir, incdir)
536 class CythonRunTestCase(CythonCompileTestCase):
537 def shortDescription(self):
538 return "compiling (%s) and running %s" % (self.language, self.module)
540 def run(self, result=None):
542 result = self.defaultTestResult()
543 result.startTest(self)
547 self.runCompileTest()
548 self.run_tests(result)
550 check_thread_termination()
552 result.addError(self, sys.exc_info())
553 result.stopTest(self)
559 def run_tests(self, result):
560 if not self.cython_only:
561 self.run_doctests(self.module, result)
563 def run_doctests(self, module_name, result):
564 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
565 doctest.DocTestSuite(module_name).run(result)
569 # fork to make sure we do not keep the tested module loaded
570 result_handle, result_file = tempfile.mkstemp()
571 os.close(result_handle)
579 partial_result = PartialTestResult(result)
580 tests = doctest.DocTestSuite(module_name)
581 tests.run(partial_result)
585 # importing failed, try to fake a test class
587 failureException=sys.exc_info()[1],
588 _shortDescription=self.shortDescription(),
590 partial_result.addError(tests, sys.exc_info())
592 output = open(result_file, 'wb')
593 pickle.dump(partial_result.data(), output)
595 traceback.print_exc()
599 os._exit(result_code)
602 cid, result_code = os.waitpid(child_id, 0)
603 # os.waitpid returns the child's result code in the
604 # upper byte of result_code, and the signal it was
605 # killed by in the lower byte
606 if result_code & 255:
607 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
608 (module_name, result_code & 255))
609 result_code = result_code >> 8
610 if result_code in (0,1):
611 input = open(result_file, 'rb')
613 PartialTestResult.join_results(result, pickle.load(input))
617 raise Exception("Tests in module '%s' exited with status %d" %
618 (module_name, result_code))
620 try: os.unlink(result_file)
623 class PureDoctestTestCase(unittest.TestCase):
624 def __init__(self, module_name, module_path):
625 self.module_name = module_name
626 self.module_path = module_path
627 unittest.TestCase.__init__(self, 'run')
629 def shortDescription(self):
630 return "running pure doctests in %s" % self.module_name
632 def run(self, result=None):
634 result = self.defaultTestResult()
635 loaded_module_name = 'pure_doctest__' + self.module_name
636 result.startTest(self)
641 m = imp.load_source(loaded_module_name, self.module_path)
643 doctest.DocTestSuite(m).run(result)
646 if loaded_module_name in sys.modules:
647 del sys.modules[loaded_module_name]
648 check_thread_termination()
650 result.addError(self, sys.exc_info())
651 result.stopTest(self)
657 is_private_field = re.compile('^_[^_]').match
659 class _FakeClass(object):
660 def __init__(self, **kwargs):
661 self._shortDescription = kwargs.get('module_name')
662 self.__dict__.update(kwargs)
663 def shortDescription(self):
664 return self._shortDescription
666 try: # Py2.7+ and Py3.2+
667 from unittest.runner import _TextTestResult
669 from unittest import _TextTestResult
671 class PartialTestResult(_TextTestResult):
672 def __init__(self, base_result):
673 _TextTestResult.__init__(
674 self, self._StringIO(), True,
675 base_result.dots + base_result.showAll*2)
677 def strip_error_results(self, results):
678 for test_case, error in results:
679 for attr_name in filter(is_private_field, dir(test_case)):
680 if attr_name == '_dt_test':
681 test_case._dt_test = _FakeClass(
682 name=test_case._dt_test.name)
683 elif attr_name != '_shortDescription':
684 setattr(test_case, attr_name, None)
687 self.strip_error_results(self.failures)
688 self.strip_error_results(self.errors)
689 return (self.failures, self.errors, self.testsRun,
690 self.stream.getvalue())
692 def join_results(result, data):
693 """Static method for merging the result back into the main
696 failures, errors, tests_run, output = data
698 result.stream.write(output)
699 result.errors.extend(errors)
700 result.failures.extend(failures)
701 result.testsRun += tests_run
703 join_results = staticmethod(join_results)
705 class _StringIO(StringIO):
706 def writeln(self, line):
707 self.write("%s\n" % line)
710 class CythonUnitTestCase(CythonRunTestCase):
711 def shortDescription(self):
712 return "compiling (%s) tests in %s" % (self.language, self.module)
714 def run_tests(self, result):
715 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
718 class CythonPyregrTestCase(CythonRunTestCase):
719 def _run_unittest(self, result, *classes):
720 """Run tests from unittest.TestCase-derived classes."""
721 valid_types = (unittest.TestSuite, unittest.TestCase)
722 suite = unittest.TestSuite()
724 if isinstance(cls, str):
725 if cls in sys.modules:
726 suite.addTest(unittest.findTestCases(sys.modules[cls]))
728 raise ValueError("str arguments must be keys in sys.modules")
729 elif isinstance(cls, valid_types):
732 suite.addTest(unittest.makeSuite(cls))
735 def _run_doctest(self, result, module):
736 self.run_doctests(module, result)
738 def run_tests(self, result):
740 from test import test_support as support
741 except ImportError: # Py3k
742 from test import support
744 def run_unittest(*classes):
745 return self._run_unittest(result, *classes)
746 def run_doctest(module, verbosity=None):
747 return self._run_doctest(result, module)
749 support.run_unittest = run_unittest
750 support.run_doctest = run_doctest
753 module = __import__(self.module)
754 if hasattr(module, 'test_main'):
756 except (unittest.SkipTest, support.ResourceDenied):
757 result.addSkip(self, 'ok')
759 include_debugger = sys.version_info[:2] > (2, 5)
761 def collect_unittests(path, module_prefix, suite, selectors):
762 def file_matches(filename):
763 return filename.startswith("Test") and filename.endswith(".py")
765 def package_matches(dirname):
766 return dirname == "Tests"
768 loader = unittest.TestLoader()
773 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
775 for dirpath, dirnames, filenames in os.walk(path):
776 if dirpath != path and "__init__.py" not in filenames:
777 skipped_dirs.append(dirpath + os.path.sep)
780 for dir in skipped_dirs:
781 if dirpath.startswith(dir):
785 parentname = os.path.split(dirpath)[-1]
786 if package_matches(parentname):
789 filepath = os.path.join(dirpath, f)[:-len(".py")]
790 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
791 if not [ 1 for match in selectors if match(modulename) ]:
793 module = __import__(modulename)
794 for x in modulename.split('.')[1:]:
795 module = getattr(module, x)
796 suite.addTests([loader.loadTestsFromModule(module)])
800 def collect_doctests(path, module_prefix, suite, selectors):
801 def package_matches(dirname):
802 if dirname == 'Debugger' and not include_debugger:
804 return dirname not in ("Mac", "Distutils", "Plex")
805 def file_matches(filename):
806 filename, ext = os.path.splitext(filename)
807 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
809 return (ext == '.py' and not
810 '~' in filename and not
811 '#' in filename and not
812 filename.startswith('.') and not
813 filename in blacklist)
814 import doctest, types
815 for dirpath, dirnames, filenames in os.walk(path):
816 for dir in list(dirnames):
817 if not package_matches(dir):
821 if not f.endswith('.py'): continue
822 filepath = os.path.join(dirpath, f)
823 if os.path.getsize(filepath) == 0: continue
824 filepath = filepath[:-len(".py")]
825 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
826 if not [ 1 for match in selectors if match(modulename) ]:
828 if 'in_gdb' in modulename:
829 # These should only be imported from gdb.
831 module = __import__(modulename)
832 for x in modulename.split('.')[1:]:
833 module = getattr(module, x)
834 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
836 suite.addTest(doctest.DocTestSuite(module))
837 except ValueError: # no tests
841 class EndToEndTest(unittest.TestCase):
843 This is a test of build/*.srctree files, where srctree defines a full
844 directory structure and its header gives a list of commands to run.
846 cython_root = os.path.dirname(os.path.abspath(__file__))
848 def __init__(self, treefile, workdir, cleanup_workdir=True):
849 self.name = os.path.splitext(os.path.basename(treefile))[0]
850 self.treefile = treefile
851 self.workdir = os.path.join(workdir, self.name)
852 self.cleanup_workdir = cleanup_workdir
853 cython_syspath = self.cython_root
854 for path in sys.path[::-1]:
855 if path.startswith(self.cython_root):
856 # Py3 installation and refnanny build prepend their
857 # fixed paths to sys.path => prefer that over the
859 cython_syspath = path + os.pathsep + cython_syspath
860 self.cython_syspath = cython_syspath
861 unittest.TestCase.__init__(self)
863 def shortDescription(self):
864 return "End-to-end %s" % self.name
867 from Cython.TestUtils import unpack_source_tree
868 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
869 self.old_dir = os.getcwd()
870 os.chdir(self.workdir)
871 if self.workdir not in sys.path:
872 sys.path.insert(0, self.workdir)
875 if self.cleanup_workdir:
876 for trial in range(5):
878 shutil.rmtree(self.workdir)
883 os.chdir(self.old_dir)
886 commands = (self.commands
887 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
888 .replace("PYTHON", sys.executable))
890 old_path = os.environ.get('PYTHONPATH')
891 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
892 for command in commands.split('\n'):
893 if sys.version_info[:2] >= (2,4):
895 p = subprocess.Popen(commands,
896 stderr=subprocess.PIPE,
897 stdout=subprocess.PIPE,
899 out, err = p.communicate()
906 res = os.system(command)
907 self.assertEqual(0, res, "non-zero exit status")
910 os.environ['PYTHONPATH'] = old_path
912 del os.environ['PYTHONPATH']
915 # TODO: Support cython_freeze needed here as well.
916 # TODO: Windows support.
918 class EmbedTest(unittest.TestCase):
920 working_dir = "Demos/embed"
923 self.old_dir = os.getcwd()
924 os.chdir(self.working_dir)
926 "make PYTHON='%s' clean > /dev/null" % sys.executable)
931 "make PYTHON='%s' clean > /dev/null" % sys.executable)
934 os.chdir(self.old_dir)
936 def test_embed(self):
937 from distutils import sysconfig
938 libname = sysconfig.get_config_var('LIBRARY')
939 libdir = sysconfig.get_config_var('LIBDIR')
940 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
941 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
942 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
943 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
944 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
945 # report the error for the original directory
946 libdir = sysconfig.get_config_var('LIBDIR')
948 if sys.version_info[0] >=3 and CY3_DIR:
949 cython = os.path.join(CY3_DIR, cython)
950 cython = os.path.abspath(os.path.join('..', '..', cython))
951 self.assert_(os.system(
952 "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
954 os.remove('make.output')
958 class MissingDependencyExcluder:
959 def __init__(self, deps):
960 # deps: { module name : matcher func }
961 self.exclude_matchers = []
962 for mod, matcher in deps.items():
966 self.exclude_matchers.append(matcher)
967 self.tests_missing_deps = []
968 def __call__(self, testname, tags=None):
969 for matcher in self.exclude_matchers:
970 if matcher(testname):
971 self.tests_missing_deps.append(testname)
975 class VersionDependencyExcluder:
976 def __init__(self, deps):
977 # deps: { version : matcher func }
978 from sys import version_info
979 self.exclude_matchers = []
980 for ver, (compare, matcher) in deps.items():
981 if compare(version_info, ver):
982 self.exclude_matchers.append(matcher)
983 self.tests_missing_deps = []
984 def __call__(self, testname, tags=None):
985 for matcher in self.exclude_matchers:
986 if matcher(testname):
987 self.tests_missing_deps.append(testname)
991 class FileListExcluder:
993 def __init__(self, list_file):
997 for line in f.readlines():
999 if line and line[0] != '#':
1000 self.excludes[line.split()[0]] = True
1004 def __call__(self, testname, tags=None):
1006 return testname in self.excludes or testname.split('.')[-1] in self.excludes
1010 def __init__(self, tag, value):
1014 def __call__(self, testname, tags=None):
1018 return self.value in tags[self.tag]
1020 class RegExSelector:
1022 def __init__(self, pattern_string):
1023 self.pattern = re.compile(pattern_string, re.I|re.U)
1025 def __call__(self, testname, tags=None):
1026 return self.pattern.search(testname)
1028 def string_selector(s):
1031 return RegExSelector(s)
1033 return TagsSelector(s[:ix], s[ix+1:])
1036 def refactor_for_py3(distdir, cy3_dir):
1037 # need to convert Cython sources first
1038 import lib2to3.refactor
1039 from distutils.util import copydir_run_2to3
1040 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
1041 if fix.split('fix_')[-1] not in ('next',)
1043 if not os.path.exists(cy3_dir):
1044 os.makedirs(cy3_dir)
1045 import distutils.log as dlog
1046 dlog.set_threshold(dlog.INFO)
1047 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1051 recursive-exclude Cython *
1052 recursive-include Cython *.py *.pyx *.pxd
1053 recursive-include Cython/Debugger/Tests *
1057 sys.path.insert(0, cy3_dir)
1059 for keep_2x_file in KEEP_2X_FILES:
1060 destfile = os.path.join(cy3_dir, keep_2x_file)
1061 shutil.copy(keep_2x_file, destfile)
1063 class PendingThreadsError(RuntimeError):
1068 def check_thread_termination(ignore_seen=True):
1069 if threading is None: # no threading enabled in CPython
1071 current = threading.currentThread()
1072 blocking_threads = []
1073 for t in threading.enumerate():
1074 if not t.isAlive() or t == current:
1079 blocking_threads.append(t)
1081 for seen in threads_seen:
1085 threads_seen.append(t)
1086 blocking_threads.append(t)
1087 if not blocking_threads:
1089 sys.stderr.write("warning: left-over threads found after running test:\n")
1090 for t in blocking_threads:
1091 sys.stderr.write('...%s\n' % repr(t))
1092 raise PendingThreadsError("left-over threads found after running test")
1096 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1098 from optparse import OptionParser
1099 parser = OptionParser()
1100 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1101 action="store_false", default=True,
1102 help="do not delete the generated C files (allows passing --no-cython on next run)")
1103 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1104 action="store_false", default=True,
1105 help="do not delete the generated shared libary files (allows manual module experimentation)")
1106 parser.add_option("--no-cython", dest="with_cython",
1107 action="store_false", default=True,
1108 help="do not run the Cython compiler, only the C compiler")
1109 parser.add_option("--compiler", dest="compiler", default=None,
1110 help="C compiler type")
1111 parser.add_option("--no-c", dest="use_c",
1112 action="store_false", default=True,
1113 help="do not test C compilation")
1114 parser.add_option("--no-cpp", dest="use_cpp",
1115 action="store_false", default=True,
1116 help="do not test C++ compilation")
1117 parser.add_option("--no-unit", dest="unittests",
1118 action="store_false", default=True,
1119 help="do not run the unit tests")
1120 parser.add_option("--no-doctest", dest="doctests",
1121 action="store_false", default=True,
1122 help="do not run the doctests")
1123 parser.add_option("--no-file", dest="filetests",
1124 action="store_false", default=True,
1125 help="do not run the file based tests")
1126 parser.add_option("--no-pyregr", dest="pyregr",
1127 action="store_false", default=True,
1128 help="do not run the regression tests of CPython in tests/pyregr/")
1129 parser.add_option("--cython-only", dest="cython_only",
1130 action="store_true", default=False,
1131 help="only compile pyx to c, do not run C compiler or run the tests")
1132 parser.add_option("--no-refnanny", dest="with_refnanny",
1133 action="store_false", default=True,
1134 help="do not regression test reference counting")
1135 parser.add_option("--no-fork", dest="fork",
1136 action="store_false", default=True,
1137 help="do not fork to run tests")
1138 parser.add_option("--sys-pyregr", dest="system_pyregr",
1139 action="store_true", default=False,
1140 help="run the regression tests of the CPython installation")
1141 parser.add_option("-x", "--exclude", dest="exclude",
1142 action="append", metavar="PATTERN",
1143 help="exclude tests matching the PATTERN")
1144 parser.add_option("-C", "--coverage", dest="coverage",
1145 action="store_true", default=False,
1146 help="collect source coverage data for the Compiler")
1147 parser.add_option("--coverage-xml", dest="coverage_xml",
1148 action="store_true", default=False,
1149 help="collect source coverage data for the Compiler in XML format")
1150 parser.add_option("-A", "--annotate", dest="annotate_source",
1151 action="store_true", default=True,
1152 help="generate annotated HTML versions of the test source files")
1153 parser.add_option("--no-annotate", dest="annotate_source",
1154 action="store_false",
1155 help="do not generate annotated HTML versions of the test source files")
1156 parser.add_option("-v", "--verbose", dest="verbosity",
1157 action="count", default=0,
1158 help="display test progress, pass twice to print test names")
1159 parser.add_option("-T", "--ticket", dest="tickets",
1161 help="a bug ticket number to run the respective test in 'tests/*'")
1162 parser.add_option("-3", dest="language_level",
1163 action="store_const", const=3, default=2,
1164 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1165 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1166 help="write test results in XML to directory DIR")
1167 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1168 action="store_true",
1169 help="exit without error code even on test failures")
1170 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1171 help="working directory")
1172 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1173 help="working directory")
1175 options, cmd_args = parser.parse_args()
1177 ROOTDIR = os.path.abspath(options.root_dir)
1178 WORKDIR = os.path.abspath(options.work_dir)
1180 if sys.version_info[0] >= 3:
1181 options.doctests = False
1182 if options.with_cython:
1184 # try if Cython is installed in a Py3 version
1185 import Cython.Compiler.Main
1187 # back out anything the import process loaded, then
1188 # 2to3 the Cython sources to make them re-importable
1189 cy_modules = [ name for name in sys.modules
1190 if name == 'Cython' or name.startswith('Cython.') ]
1191 for name in cy_modules:
1192 del sys.modules[name]
1193 # hasn't been refactored yet - do it now
1195 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1196 if sys.version_info >= (3,1):
1197 refactor_for_py3(DISTDIR, cy3_dir)
1198 elif os.path.isdir(cy3_dir):
1199 sys.path.insert(0, cy3_dir)
1201 options.with_cython = False
1203 WITH_CYTHON = options.with_cython
1205 if options.coverage or options.coverage_xml:
1207 options.coverage = options.coverage_xml = False
1209 from coverage import coverage as _coverage
1210 coverage = _coverage(branch=True)
1215 global CompilationOptions, pyrex_default_options, cython_compile
1216 from Cython.Compiler.Main import \
1217 CompilationOptions, \
1218 default_options as pyrex_default_options, \
1219 compile as cython_compile
1220 from Cython.Compiler import Errors
1221 Errors.LEVEL = 0 # show all warnings
1222 from Cython.Compiler import Options
1223 Options.generate_cleanup_code = 3 # complete cleanup code
1224 from Cython.Compiler import DebugFlags
1225 DebugFlags.debug_temp_code_comments = 1
1228 UNITTEST_MODULE = "Cython"
1229 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1231 if os.path.exists(WORKDIR):
1232 for path in os.listdir(WORKDIR):
1233 if path in ("support", "Cy3"): continue
1234 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1235 if not os.path.exists(WORKDIR):
1236 os.makedirs(WORKDIR)
1238 sys.stderr.write("Python %s\n" % sys.version)
1239 sys.stderr.write("\n")
1241 from Cython.Compiler.Version import version
1242 sys.stderr.write("Running tests against Cython %s\n" % version)
1244 sys.stderr.write("Running tests without Cython.\n")
1246 if options.with_refnanny:
1247 from pyximport.pyxbuild import pyx_to_dll
1248 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1250 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1251 sys.path.insert(0, os.path.split(libpath)[0])
1252 CFLAGS.append("-DCYTHON_REFNANNY=1")
1254 if options.xml_output_dir and options.fork:
1255 # doesn't currently work together
1256 sys.stderr.write("Disabling forked testing to support XML test output\n")
1257 options.fork = False
1259 if WITH_CYTHON and options.language_level == 3:
1260 sys.stderr.write("Using Cython language level 3.\n")
1262 sys.stderr.write("\n")
1266 for ticket_number in options.tickets:
1268 cmd_args.append('.*T%s$' % ticket_number)
1270 for selector in cmd_args:
1271 if selector.startswith('bugs'):
1275 selectors = [ string_selector(r) for r in cmd_args ]
1277 selectors = [ lambda x, tags=None: True ]
1279 # Chech which external modules are not present and exclude tests
1280 # which depends on them (by prefix)
1282 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1283 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1284 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1287 exclude_selectors += [ string_selector(r) for r in options.exclude ]
1290 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1292 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1293 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1296 if options.compiler:
1297 COMPILER = options.compiler
1300 languages.append('c')
1302 languages.append('cpp')
1304 test_suite = unittest.TestSuite()
1306 if options.unittests:
1307 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1309 if options.doctests:
1310 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1312 if options.filetests and languages:
1313 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1314 options.annotate_source, options.cleanup_workdir,
1315 options.cleanup_sharedlibs, options.pyregr,
1316 options.cython_only, languages, test_bugs,
1317 options.fork, options.language_level)
1318 test_suite.addTest(filetests.build_suite())
1320 if options.system_pyregr and languages:
1321 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1322 options.annotate_source, options.cleanup_workdir,
1323 options.cleanup_sharedlibs, True,
1324 options.cython_only, languages, test_bugs,
1325 options.fork, options.language_level)
1327 filetests.handle_directory(
1328 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1331 if options.xml_output_dir:
1332 from Cython.Tests.xmlrunner import XMLTestRunner
1333 test_runner = XMLTestRunner(output=options.xml_output_dir,
1334 verbose=options.verbosity > 0)
1336 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1338 result = test_runner.run(test_suite)
1340 if options.coverage or options.coverage_xml:
1342 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1343 modules = [ module for name, module in sys.modules.items()
1344 if module is not None and
1345 name.startswith('Cython.Compiler.') and
1346 name[len('Cython.Compiler.'):] not in ignored_modules ]
1347 if options.coverage:
1348 coverage.report(modules, show_missing=0)
1349 if options.coverage_xml:
1350 coverage.xml_report(modules, outfile="coverage-report.xml")
1352 if missing_dep_excluder.tests_missing_deps:
1353 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1354 for test in missing_dep_excluder.tests_missing_deps:
1355 sys.stderr.write(" %s\n" % test)
1357 if options.with_refnanny:
1359 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1366 return_code = not result.wasSuccessful()
1369 check_thread_termination(ignore_seen=False)
1370 sys.exit(return_code)
1371 except PendingThreadsError:
1372 # normal program exit won't kill the threads, do it the hard way here
1373 os._exit(return_code)
1375 if __name__ == '__main__':
1378 except SystemExit: # <= Py2.4 ...
1381 traceback.print_exc()
1383 check_thread_termination(ignore_seen=False)
1384 except PendingThreadsError:
1385 # normal program exit won't kill the threads, do it the hard way here