16 from StringIO import StringIO
18 from io import StringIO
21 import cPickle as pickle
26 from io import open as io_open
28 from codecs import open as io_open
32 except ImportError: # No threads, no problems
36 from collections import defaultdict
38 class defaultdict(object):
39 def __init__(self, default_factory=lambda : None):
41 self.default_factory = default_factory
42 def __getitem__(self, key):
43 if key not in self._dict:
44 self._dict[key] = self.default_factory()
45 return self._dict[key]
46 def __setitem__(self, key, value):
47 self._dict[key] = value
49 return repr(self._dict)
54 from distutils.dist import Distribution
55 from distutils.core import Extension
56 from distutils.command.build_ext import build_ext as _build_ext
57 distutils_distro = Distribution()
59 if sys.platform == 'win32':
60 # TODO: Figure out why this hackery (see http://thread.gmane.org/gmane.comp.python.cython.devel/8280/).
61 config_files = distutils_distro.find_config_files()
62 try: config_files.remove('setup.cfg')
63 except ValueError: pass
64 distutils_distro.parse_config_files(config_files)
66 cfgfiles = distutils_distro.find_config_files()
67 try: cfgfiles.remove('setup.cfg')
68 except ValueError: pass
69 distutils_distro.parse_config_files(cfgfiles)
71 # Lists external modules, and a matcher matching tests
72 # which should be excluded if the module is not present.
73 # TODO: use tags for these
75 'numpy' : re.compile('.*\.numpy_.*').match,
76 'pstats' : re.compile('.*\.pstats_.*').match,
77 'posix' : re.compile('.*\.posix_.*').match,
80 def get_numpy_include_dirs():
82 return [numpy.get_include()]
86 # test name matcher , callable returning list
87 (re.compile('numpy_.*').match, get_numpy_include_dirs),
91 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
92 # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
93 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
96 (2,5) : (operator.lt, lambda x: x in ['run.any',
99 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
101 'run.pure_py', # decorators, with statement
103 # The next line should start (3,); but this is a dictionary, so
104 # we can only have one (3,) key. Since 2.7 is supposed to be the
105 # last 2.x release, things would have to change drastically for this
107 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
108 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
109 'compile.extsetslice',
110 'compile.extdelslice',
111 'run.special_methods_T561_py2']),
114 # files that should not be converted to Python 3 code with 2to3
116 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
117 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
118 os.path.join('Cython', 'Debugger', 'libcython.py'),
119 os.path.join('Cython', 'Debugger', 'libpython.py'),
123 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
124 CFLAGS = os.getenv('CFLAGS', '').split()
127 uncomputed = object()
130 res = f._cache.get(args, uncomputed)
131 if res is uncomputed:
132 res = f._cache[args] = f(*args)
136 def parse_tags(filepath):
137 tags = defaultdict(list)
138 f = io_open(filepath, encoding='ISO-8859-1', errors='replace')
148 tag = line[1:ix].strip()
149 values = line[ix+1:].split(',')
150 tags[tag].extend([value.strip() for value in values])
155 parse_tags = memoize(parse_tags)
158 class build_ext(_build_ext):
159 def build_extension(self, ext):
160 if ext.language == 'c++':
162 try: # Py2.7+ & Py3.2+
163 compiler_obj = self.compiler_obj
164 except AttributeError:
165 compiler_obj = self.compiler
166 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
169 _build_ext.build_extension(self, ext)
171 class ErrorWriter(object):
172 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
175 self.write = self.output.append
177 def _collect(self, collect_errors, collect_warnings):
178 s = ''.join(self.output)
180 for line in s.split('\n'):
181 match = self.match_error(line)
183 is_warning, line, column, message = match.groups()
184 if (is_warning and collect_warnings) or \
185 (not is_warning and collect_errors):
186 result.append( (int(line), int(column), message.strip()) )
188 return [ "%d:%d: %s" % values for values in result ]
191 return self._collect(True, False)
193 def getwarnings(self):
194 return self._collect(False, True)
197 return self._collect(True, True)
199 class TestBuilder(object):
200 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
201 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
202 languages, test_bugs, fork, language_level):
203 self.rootdir = rootdir
204 self.workdir = workdir
205 self.selectors = selectors
206 self.exclude_selectors = exclude_selectors
207 self.annotate = annotate
208 self.cleanup_workdir = cleanup_workdir
209 self.cleanup_sharedlibs = cleanup_sharedlibs
210 self.with_pyregr = with_pyregr
211 self.cython_only = cython_only
212 self.languages = languages
213 self.test_bugs = test_bugs
215 self.language_level = language_level
217 def build_suite(self):
218 suite = unittest.TestSuite()
219 filenames = os.listdir(self.rootdir)
221 for filename in filenames:
222 path = os.path.join(self.rootdir, filename)
223 if os.path.isdir(path):
224 if filename == 'pyregr' and not self.with_pyregr:
226 if filename == 'broken' and not self.test_bugs:
229 self.handle_directory(path, filename))
230 if sys.platform not in ['win32']:
231 # Non-Windows makefile.
232 if [1 for selector in self.selectors if selector("embedded")] \
233 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
234 suite.addTest(unittest.makeSuite(EmbedTest))
237 def handle_directory(self, path, context):
238 workdir = os.path.join(self.workdir, context)
239 if not os.path.exists(workdir):
242 suite = unittest.TestSuite()
243 filenames = os.listdir(path)
245 for filename in filenames:
246 filepath = os.path.join(path, filename)
247 module, ext = os.path.splitext(filename)
248 if ext not in ('.py', '.pyx', '.srctree'):
250 if filename.startswith('.'):
251 continue # certain emacs backup files
252 tags = parse_tags(filepath)
253 fqmodule = "%s.%s" % (context, module)
254 if not [ 1 for match in self.selectors
255 if match(fqmodule, tags) ]:
257 if self.exclude_selectors:
258 if [1 for match in self.exclude_selectors
259 if match(fqmodule, tags)]:
262 mode = 'run' # default
264 mode = tags['mode'][0]
265 elif context == 'pyregr':
268 if ext == '.srctree':
269 suite.addTest(EndToEndTest(filepath, workdir, self.cleanup_workdir))
272 # Choose the test suite.
274 if not filename.startswith('test_'):
276 test_class = CythonPyregrTestCase
278 if module.startswith("test_"):
279 test_class = CythonUnitTestCase
281 test_class = CythonRunTestCase
283 test_class = CythonCompileTestCase
285 for test in self.build_tests(test_class, path, workdir,
286 module, mode == 'error', tags):
288 if mode == 'run' and ext == '.py':
289 # additionally test file in real Python
290 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
294 def build_tests(self, test_class, path, workdir, module, expect_errors, tags):
296 if 'cpp' in tags['tag'] and 'cpp' in self.languages:
299 languages = self.languages[:1]
301 languages = self.languages
302 if 'cpp' in tags['tag'] and 'c' in languages:
303 languages = list(languages)
304 languages.remove('c')
305 tests = [ self.build_test(test_class, path, workdir, module,
306 language, expect_errors)
307 for language in languages ]
310 def build_test(self, test_class, path, workdir, module,
311 language, expect_errors):
312 workdir = os.path.join(workdir, language)
313 if not os.path.exists(workdir):
315 return test_class(path, workdir, module,
317 expect_errors=expect_errors,
318 annotate=self.annotate,
319 cleanup_workdir=self.cleanup_workdir,
320 cleanup_sharedlibs=self.cleanup_sharedlibs,
321 cython_only=self.cython_only,
323 language_level=self.language_level)
325 class CythonCompileTestCase(unittest.TestCase):
326 def __init__(self, test_directory, workdir, module, language='c',
327 expect_errors=False, annotate=False, cleanup_workdir=True,
328 cleanup_sharedlibs=True, cython_only=False, fork=True,
330 self.test_directory = test_directory
331 self.workdir = workdir
333 self.language = language
334 self.expect_errors = expect_errors
335 self.annotate = annotate
336 self.cleanup_workdir = cleanup_workdir
337 self.cleanup_sharedlibs = cleanup_sharedlibs
338 self.cython_only = cython_only
340 self.language_level = language_level
341 unittest.TestCase.__init__(self)
343 def shortDescription(self):
344 return "compiling (%s) %s" % (self.language, self.module)
347 if self.workdir not in sys.path:
348 sys.path.insert(0, self.workdir)
352 sys.path.remove(self.workdir)
356 del sys.modules[self.module]
359 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
360 cleanup_lib_files = self.cleanup_sharedlibs
361 if os.path.exists(self.workdir):
362 for rmfile in os.listdir(self.workdir):
363 if not cleanup_c_files:
364 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
366 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
368 if self.annotate and rmfile.endswith(".html"):
371 rmfile = os.path.join(self.workdir, rmfile)
372 if os.path.isdir(rmfile):
373 shutil.rmtree(rmfile, ignore_errors=True)
379 os.makedirs(self.workdir)
382 self.runCompileTest()
384 def runCompileTest(self):
385 self.compile(self.test_directory, self.module, self.workdir,
386 self.test_directory, self.expect_errors, self.annotate)
388 def find_module_source_file(self, source_file):
389 if not os.path.exists(source_file):
390 source_file = source_file[:-1]
393 def build_target_filename(self, module_name):
394 target = '%s.%s' % (module_name, self.language)
397 def copy_related_files(self, test_directory, target_directory, module_name):
398 is_related = re.compile('%s_.*[.].*' % module_name).match
399 for filename in os.listdir(test_directory):
400 if is_related(filename):
401 shutil.copy(os.path.join(test_directory, filename),
404 def find_source_files(self, workdir, module_name):
405 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
406 return [self.build_target_filename(module_name)] + [
407 filename for filename in os.listdir(workdir)
408 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
410 def split_source_and_output(self, test_directory, module, workdir):
411 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
412 source_and_output = io_open(source_file, 'rU', encoding='ISO-8859-1')
414 out = io_open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
415 'w', encoding='ISO-8859-1')
416 for line in source_and_output:
418 if line.startswith("_ERRORS"):
424 source_and_output.close()
426 geterrors = out.geterrors
427 except AttributeError:
433 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
434 extra_compile_options=None):
435 include_dirs = INCLUDE_DIRS[:]
437 include_dirs.append(incdir)
438 source = self.find_module_source_file(
439 os.path.join(test_directory, module + '.pyx'))
440 target = os.path.join(targetdir, self.build_target_filename(module))
442 if extra_compile_options is None:
443 extra_compile_options = {}
448 from Cython.Compiler.Main import CompilationOptions
449 from Cython.Compiler.Main import compile as cython_compile
450 from Cython.Compiler.Main import default_options
452 options = CompilationOptions(
454 include_path = include_dirs,
455 output_file = target,
457 use_listing_file = False,
458 cplus = self.language == 'cpp',
459 language_level = self.language_level,
460 generate_pxi = False,
461 evaluate_tree_assertions = True,
462 **extra_compile_options
464 cython_compile(source, options=options,
465 full_module_name=module)
467 def run_distutils(self, test_directory, module, workdir, incdir,
468 extra_extension_args=None):
472 build_extension = build_ext(distutils_distro)
473 build_extension.include_dirs = INCLUDE_DIRS[:]
475 build_extension.include_dirs.append(incdir)
476 build_extension.finalize_options()
478 build_extension.compiler = COMPILER
479 ext_include_dirs = []
480 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
482 ext_include_dirs += get_additional_include_dirs()
483 ext_compile_flags = CFLAGS[:]
484 if build_extension.compiler == 'mingw32':
485 ext_compile_flags.append('-Wno-format')
486 if extra_extension_args is None:
487 extra_extension_args = {}
489 self.copy_related_files(test_directory, workdir, module)
490 extension = Extension(
492 sources = self.find_source_files(workdir, module),
493 include_dirs = ext_include_dirs,
494 extra_compile_args = ext_compile_flags,
495 **extra_extension_args
497 if self.language == 'cpp':
498 extension.language = 'c++'
499 build_extension.extensions = [extension]
500 build_extension.build_temp = workdir
501 build_extension.build_lib = workdir
502 build_extension.run()
506 def compile(self, test_directory, module, workdir, incdir,
507 expect_errors, annotate):
508 expected_errors = errors = ()
510 expected_errors = self.split_source_and_output(
511 test_directory, module, workdir)
512 test_directory = workdir
515 old_stderr = sys.stderr
517 sys.stderr = ErrorWriter()
518 self.run_cython(test_directory, module, workdir, incdir, annotate)
519 errors = sys.stderr.geterrors()
521 sys.stderr = old_stderr
523 if errors or expected_errors:
525 for expected, error in zip(expected_errors, errors):
526 self.assertEquals(expected, error)
527 if len(errors) < len(expected_errors):
528 expected_error = expected_errors[len(errors)]
529 self.assertEquals(expected_error, None)
530 elif len(errors) > len(expected_errors):
531 unexpected_error = errors[len(expected_errors)]
532 self.assertEquals(None, unexpected_error)
533 except AssertionError:
534 print("\n=== Expected errors: ===")
535 print('\n'.join(expected_errors))
536 print("\n\n=== Got errors: ===")
537 print('\n'.join(errors))
541 if not self.cython_only:
542 self.run_distutils(test_directory, module, workdir, incdir)
544 class CythonRunTestCase(CythonCompileTestCase):
545 def shortDescription(self):
546 return "compiling (%s) and running %s" % (self.language, self.module)
548 def run(self, result=None):
550 result = self.defaultTestResult()
551 result.startTest(self)
555 self.runCompileTest()
556 self.run_tests(result)
558 check_thread_termination()
560 result.addError(self, sys.exc_info())
561 result.stopTest(self)
567 def run_tests(self, result):
568 if not self.cython_only:
569 self.run_doctests(self.module, result)
571 def run_doctests(self, module_name, result):
572 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
573 doctest.DocTestSuite(module_name).run(result)
577 # fork to make sure we do not keep the tested module loaded
578 result_handle, result_file = tempfile.mkstemp()
579 os.close(result_handle)
587 partial_result = PartialTestResult(result)
588 tests = doctest.DocTestSuite(module_name)
589 tests.run(partial_result)
593 # importing failed, try to fake a test class
595 failureException=sys.exc_info()[1],
596 _shortDescription=self.shortDescription(),
598 partial_result.addError(tests, sys.exc_info())
600 output = open(result_file, 'wb')
601 pickle.dump(partial_result.data(), output)
603 traceback.print_exc()
607 os._exit(result_code)
610 cid, result_code = os.waitpid(child_id, 0)
611 # os.waitpid returns the child's result code in the
612 # upper byte of result_code, and the signal it was
613 # killed by in the lower byte
614 if result_code & 255:
615 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
616 (module_name, result_code & 255))
617 result_code = result_code >> 8
618 if result_code in (0,1):
619 input = open(result_file, 'rb')
621 PartialTestResult.join_results(result, pickle.load(input))
625 raise Exception("Tests in module '%s' exited with status %d" %
626 (module_name, result_code))
628 try: os.unlink(result_file)
631 class PureDoctestTestCase(unittest.TestCase):
632 def __init__(self, module_name, module_path):
633 self.module_name = module_name
634 self.module_path = module_path
635 unittest.TestCase.__init__(self, 'run')
637 def shortDescription(self):
638 return "running pure doctests in %s" % self.module_name
640 def run(self, result=None):
642 result = self.defaultTestResult()
643 loaded_module_name = 'pure_doctest__' + self.module_name
644 result.startTest(self)
649 m = imp.load_source(loaded_module_name, self.module_path)
651 doctest.DocTestSuite(m).run(result)
654 if loaded_module_name in sys.modules:
655 del sys.modules[loaded_module_name]
656 check_thread_termination()
658 result.addError(self, sys.exc_info())
659 result.stopTest(self)
665 is_private_field = re.compile('^_[^_]').match
667 class _FakeClass(object):
668 def __init__(self, **kwargs):
669 self._shortDescription = kwargs.get('module_name')
670 self.__dict__.update(kwargs)
671 def shortDescription(self):
672 return self._shortDescription
674 try: # Py2.7+ and Py3.2+
675 from unittest.runner import _TextTestResult
677 from unittest import _TextTestResult
679 class PartialTestResult(_TextTestResult):
680 def __init__(self, base_result):
681 _TextTestResult.__init__(
682 self, self._StringIO(), True,
683 base_result.dots + base_result.showAll*2)
685 def strip_error_results(self, results):
686 for test_case, error in results:
687 for attr_name in filter(is_private_field, dir(test_case)):
688 if attr_name == '_dt_test':
689 test_case._dt_test = _FakeClass(
690 name=test_case._dt_test.name)
691 elif attr_name != '_shortDescription':
692 setattr(test_case, attr_name, None)
695 self.strip_error_results(self.failures)
696 self.strip_error_results(self.errors)
697 return (self.failures, self.errors, self.testsRun,
698 self.stream.getvalue())
700 def join_results(result, data):
701 """Static method for merging the result back into the main
704 failures, errors, tests_run, output = data
706 result.stream.write(output)
707 result.errors.extend(errors)
708 result.failures.extend(failures)
709 result.testsRun += tests_run
711 join_results = staticmethod(join_results)
713 class _StringIO(StringIO):
714 def writeln(self, line):
715 self.write("%s\n" % line)
718 class CythonUnitTestCase(CythonRunTestCase):
719 def shortDescription(self):
720 return "compiling (%s) tests in %s" % (self.language, self.module)
722 def run_tests(self, result):
723 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
726 class CythonPyregrTestCase(CythonRunTestCase):
727 def _run_unittest(self, result, *classes):
728 """Run tests from unittest.TestCase-derived classes."""
729 valid_types = (unittest.TestSuite, unittest.TestCase)
730 suite = unittest.TestSuite()
732 if isinstance(cls, str):
733 if cls in sys.modules:
734 suite.addTest(unittest.findTestCases(sys.modules[cls]))
736 raise ValueError("str arguments must be keys in sys.modules")
737 elif isinstance(cls, valid_types):
740 suite.addTest(unittest.makeSuite(cls))
743 def _run_doctest(self, result, module):
744 self.run_doctests(module, result)
746 def run_tests(self, result):
748 from test import test_support as support
749 except ImportError: # Py3k
750 from test import support
752 def run_unittest(*classes):
753 return self._run_unittest(result, *classes)
754 def run_doctest(module, verbosity=None):
755 return self._run_doctest(result, module)
757 support.run_unittest = run_unittest
758 support.run_doctest = run_doctest
761 module = __import__(self.module)
762 if hasattr(module, 'test_main'):
764 except (unittest.SkipTest, support.ResourceDenied):
765 result.addSkip(self, 'ok')
767 include_debugger = sys.version_info[:2] > (2, 5)
769 def collect_unittests(path, module_prefix, suite, selectors):
770 def file_matches(filename):
771 return filename.startswith("Test") and filename.endswith(".py")
773 def package_matches(dirname):
774 return dirname == "Tests"
776 loader = unittest.TestLoader()
781 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
783 for dirpath, dirnames, filenames in os.walk(path):
784 if dirpath != path and "__init__.py" not in filenames:
785 skipped_dirs.append(dirpath + os.path.sep)
788 for dir in skipped_dirs:
789 if dirpath.startswith(dir):
793 parentname = os.path.split(dirpath)[-1]
794 if package_matches(parentname):
797 filepath = os.path.join(dirpath, f)[:-len(".py")]
798 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
799 if not [ 1 for match in selectors if match(modulename) ]:
801 module = __import__(modulename)
802 for x in modulename.split('.')[1:]:
803 module = getattr(module, x)
804 suite.addTests([loader.loadTestsFromModule(module)])
808 def collect_doctests(path, module_prefix, suite, selectors):
809 def package_matches(dirname):
810 if dirname == 'Debugger' and not include_debugger:
812 return dirname not in ("Mac", "Distutils", "Plex")
813 def file_matches(filename):
814 filename, ext = os.path.splitext(filename)
815 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
817 return (ext == '.py' and not
818 '~' in filename and not
819 '#' in filename and not
820 filename.startswith('.') and not
821 filename in blacklist)
822 import doctest, types
823 for dirpath, dirnames, filenames in os.walk(path):
824 for dir in list(dirnames):
825 if not package_matches(dir):
829 if not f.endswith('.py'): continue
830 filepath = os.path.join(dirpath, f)
831 if os.path.getsize(filepath) == 0: continue
832 filepath = filepath[:-len(".py")]
833 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
834 if not [ 1 for match in selectors if match(modulename) ]:
836 if 'in_gdb' in modulename:
837 # These should only be imported from gdb.
839 module = __import__(modulename)
840 for x in modulename.split('.')[1:]:
841 module = getattr(module, x)
842 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
844 suite.addTest(doctest.DocTestSuite(module))
845 except ValueError: # no tests
849 class EndToEndTest(unittest.TestCase):
851 This is a test of build/*.srctree files, where srctree defines a full
852 directory structure and its header gives a list of commands to run.
854 cython_root = os.path.dirname(os.path.abspath(__file__))
856 def __init__(self, treefile, workdir, cleanup_workdir=True):
857 self.name = os.path.splitext(os.path.basename(treefile))[0]
858 self.treefile = treefile
859 self.workdir = os.path.join(workdir, self.name)
860 self.cleanup_workdir = cleanup_workdir
861 cython_syspath = self.cython_root
862 for path in sys.path[::-1]:
863 if path.startswith(self.cython_root):
864 # Py3 installation and refnanny build prepend their
865 # fixed paths to sys.path => prefer that over the
867 cython_syspath = path + os.pathsep + cython_syspath
868 self.cython_syspath = cython_syspath
869 unittest.TestCase.__init__(self)
871 def shortDescription(self):
872 return "End-to-end %s" % self.name
875 from Cython.TestUtils import unpack_source_tree
876 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
877 self.old_dir = os.getcwd()
878 os.chdir(self.workdir)
879 if self.workdir not in sys.path:
880 sys.path.insert(0, self.workdir)
883 if self.cleanup_workdir:
884 for trial in range(5):
886 shutil.rmtree(self.workdir)
891 os.chdir(self.old_dir)
894 commands = (self.commands
895 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
896 .replace("PYTHON", sys.executable))
898 old_path = os.environ.get('PYTHONPATH')
899 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
900 for command in commands.split('\n'):
901 if sys.version_info[:2] >= (2,4):
903 p = subprocess.Popen(commands,
904 stderr=subprocess.PIPE,
905 stdout=subprocess.PIPE,
907 out, err = p.communicate()
914 res = os.system(command)
915 self.assertEqual(0, res, "non-zero exit status")
918 os.environ['PYTHONPATH'] = old_path
920 del os.environ['PYTHONPATH']
923 # TODO: Support cython_freeze needed here as well.
924 # TODO: Windows support.
926 class EmbedTest(unittest.TestCase):
928 working_dir = "Demos/embed"
931 self.old_dir = os.getcwd()
932 os.chdir(self.working_dir)
934 "make PYTHON='%s' clean > /dev/null" % sys.executable)
939 "make PYTHON='%s' clean > /dev/null" % sys.executable)
942 os.chdir(self.old_dir)
944 def test_embed(self):
945 from distutils import sysconfig
946 libname = sysconfig.get_config_var('LIBRARY')
947 libdir = sysconfig.get_config_var('LIBDIR')
948 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
949 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
950 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
951 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
952 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
953 # report the error for the original directory
954 libdir = sysconfig.get_config_var('LIBDIR')
956 if sys.version_info[0] >=3 and CY3_DIR:
957 cython = os.path.join(CY3_DIR, cython)
958 cython = os.path.abspath(os.path.join('..', '..', cython))
959 self.assert_(os.system(
960 "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
962 os.remove('make.output')
966 class MissingDependencyExcluder:
967 def __init__(self, deps):
968 # deps: { module name : matcher func }
969 self.exclude_matchers = []
970 for mod, matcher in deps.items():
974 self.exclude_matchers.append(matcher)
975 self.tests_missing_deps = []
976 def __call__(self, testname, tags=None):
977 for matcher in self.exclude_matchers:
978 if matcher(testname):
979 self.tests_missing_deps.append(testname)
983 class VersionDependencyExcluder:
984 def __init__(self, deps):
985 # deps: { version : matcher func }
986 from sys import version_info
987 self.exclude_matchers = []
988 for ver, (compare, matcher) in deps.items():
989 if compare(version_info, ver):
990 self.exclude_matchers.append(matcher)
991 self.tests_missing_deps = []
992 def __call__(self, testname, tags=None):
993 for matcher in self.exclude_matchers:
994 if matcher(testname):
995 self.tests_missing_deps.append(testname)
999 class FileListExcluder:
1001 def __init__(self, list_file):
1005 for line in f.readlines():
1007 if line and line[0] != '#':
1008 self.excludes[line.split()[0]] = True
1012 def __call__(self, testname, tags=None):
1013 return testname in self.excludes or testname.split('.')[-1] in self.excludes
1017 def __init__(self, tag, value):
1021 def __call__(self, testname, tags=None):
1025 return self.value in tags[self.tag]
1027 class RegExSelector:
1029 def __init__(self, pattern_string):
1030 self.pattern = re.compile(pattern_string, re.I|re.U)
1032 def __call__(self, testname, tags=None):
1033 return self.pattern.search(testname)
1035 def string_selector(s):
1038 return RegExSelector(s)
1040 return TagsSelector(s[:ix], s[ix+1:])
1043 def refactor_for_py3(distdir, cy3_dir):
1044 # need to convert Cython sources first
1045 import lib2to3.refactor
1046 from distutils.util import copydir_run_2to3
1047 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
1048 if fix.split('fix_')[-1] not in ('next',)
1050 if not os.path.exists(cy3_dir):
1051 os.makedirs(cy3_dir)
1052 import distutils.log as dlog
1053 dlog.set_threshold(dlog.INFO)
1054 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1058 recursive-exclude Cython *
1059 recursive-include Cython *.py *.pyx *.pxd
1060 recursive-include Cython/Debugger/Tests *
1064 sys.path.insert(0, cy3_dir)
1066 for keep_2x_file in KEEP_2X_FILES:
1067 destfile = os.path.join(cy3_dir, keep_2x_file)
1068 shutil.copy(keep_2x_file, destfile)
1070 class PendingThreadsError(RuntimeError):
1075 def check_thread_termination(ignore_seen=True):
1076 if threading is None: # no threading enabled in CPython
1078 current = threading.currentThread()
1079 blocking_threads = []
1080 for t in threading.enumerate():
1081 if not t.isAlive() or t == current:
1086 blocking_threads.append(t)
1088 for seen in threads_seen:
1092 threads_seen.append(t)
1093 blocking_threads.append(t)
1094 if not blocking_threads:
1096 sys.stderr.write("warning: left-over threads found after running test:\n")
1097 for t in blocking_threads:
1098 sys.stderr.write('...%s\n' % repr(t))
1099 raise PendingThreadsError("left-over threads found after running test")
1103 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1105 from optparse import OptionParser
1106 parser = OptionParser()
1107 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1108 action="store_false", default=True,
1109 help="do not delete the generated C files (allows passing --no-cython on next run)")
1110 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1111 action="store_false", default=True,
1112 help="do not delete the generated shared libary files (allows manual module experimentation)")
1113 parser.add_option("--no-cython", dest="with_cython",
1114 action="store_false", default=True,
1115 help="do not run the Cython compiler, only the C compiler")
1116 parser.add_option("--compiler", dest="compiler", default=None,
1117 help="C compiler type")
1118 parser.add_option("--no-c", dest="use_c",
1119 action="store_false", default=True,
1120 help="do not test C compilation")
1121 parser.add_option("--no-cpp", dest="use_cpp",
1122 action="store_false", default=True,
1123 help="do not test C++ compilation")
1124 parser.add_option("--no-unit", dest="unittests",
1125 action="store_false", default=True,
1126 help="do not run the unit tests")
1127 parser.add_option("--no-doctest", dest="doctests",
1128 action="store_false", default=True,
1129 help="do not run the doctests")
1130 parser.add_option("--no-file", dest="filetests",
1131 action="store_false", default=True,
1132 help="do not run the file based tests")
1133 parser.add_option("--no-pyregr", dest="pyregr",
1134 action="store_false", default=True,
1135 help="do not run the regression tests of CPython in tests/pyregr/")
1136 parser.add_option("--cython-only", dest="cython_only",
1137 action="store_true", default=False,
1138 help="only compile pyx to c, do not run C compiler or run the tests")
1139 parser.add_option("--no-refnanny", dest="with_refnanny",
1140 action="store_false", default=True,
1141 help="do not regression test reference counting")
1142 parser.add_option("--no-fork", dest="fork",
1143 action="store_false", default=True,
1144 help="do not fork to run tests")
1145 parser.add_option("--sys-pyregr", dest="system_pyregr",
1146 action="store_true", default=False,
1147 help="run the regression tests of the CPython installation")
1148 parser.add_option("-x", "--exclude", dest="exclude",
1149 action="append", metavar="PATTERN",
1150 help="exclude tests matching the PATTERN")
1151 parser.add_option("-C", "--coverage", dest="coverage",
1152 action="store_true", default=False,
1153 help="collect source coverage data for the Compiler")
1154 parser.add_option("--coverage-xml", dest="coverage_xml",
1155 action="store_true", default=False,
1156 help="collect source coverage data for the Compiler in XML format")
1157 parser.add_option("-A", "--annotate", dest="annotate_source",
1158 action="store_true", default=True,
1159 help="generate annotated HTML versions of the test source files")
1160 parser.add_option("--no-annotate", dest="annotate_source",
1161 action="store_false",
1162 help="do not generate annotated HTML versions of the test source files")
1163 parser.add_option("-v", "--verbose", dest="verbosity",
1164 action="count", default=0,
1165 help="display test progress, pass twice to print test names")
1166 parser.add_option("-T", "--ticket", dest="tickets",
1168 help="a bug ticket number to run the respective test in 'tests/*'")
1169 parser.add_option("-3", dest="language_level",
1170 action="store_const", const=3, default=2,
1171 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1172 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1173 help="write test results in XML to directory DIR")
1174 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1175 action="store_true",
1176 help="exit without error code even on test failures")
1177 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1178 help="working directory")
1179 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1180 help="working directory")
1182 options, cmd_args = parser.parse_args()
1184 ROOTDIR = os.path.abspath(options.root_dir)
1185 WORKDIR = os.path.abspath(options.work_dir)
1187 if sys.version_info[0] >= 3:
1188 options.doctests = False
1189 if options.with_cython:
1191 # try if Cython is installed in a Py3 version
1192 import Cython.Compiler.Main
1194 # back out anything the import process loaded, then
1195 # 2to3 the Cython sources to make them re-importable
1196 cy_modules = [ name for name in sys.modules
1197 if name == 'Cython' or name.startswith('Cython.') ]
1198 for name in cy_modules:
1199 del sys.modules[name]
1200 # hasn't been refactored yet - do it now
1202 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1203 if sys.version_info >= (3,1):
1204 refactor_for_py3(DISTDIR, cy3_dir)
1205 elif os.path.isdir(cy3_dir):
1206 sys.path.insert(0, cy3_dir)
1208 options.with_cython = False
1210 WITH_CYTHON = options.with_cython
1212 if options.coverage or options.coverage_xml:
1214 options.coverage = options.coverage_xml = False
1216 from coverage import coverage as _coverage
1217 coverage = _coverage(branch=True)
1222 global CompilationOptions, pyrex_default_options, cython_compile
1223 from Cython.Compiler.Main import \
1224 CompilationOptions, \
1225 default_options as pyrex_default_options, \
1226 compile as cython_compile
1227 from Cython.Compiler import Errors
1228 Errors.LEVEL = 0 # show all warnings
1229 from Cython.Compiler import Options
1230 Options.generate_cleanup_code = 3 # complete cleanup code
1231 from Cython.Compiler import DebugFlags
1232 DebugFlags.debug_temp_code_comments = 1
1235 UNITTEST_MODULE = "Cython"
1236 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1238 if os.path.exists(WORKDIR):
1239 for path in os.listdir(WORKDIR):
1240 if path in ("support", "Cy3"): continue
1241 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1242 if not os.path.exists(WORKDIR):
1243 os.makedirs(WORKDIR)
1245 sys.stderr.write("Python %s\n" % sys.version)
1246 sys.stderr.write("\n")
1248 from Cython.Compiler.Version import version
1249 sys.stderr.write("Running tests against Cython %s\n" % version)
1251 sys.stderr.write("Running tests without Cython.\n")
1253 if options.with_refnanny:
1254 from pyximport.pyxbuild import pyx_to_dll
1255 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1257 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1258 sys.path.insert(0, os.path.split(libpath)[0])
1259 CFLAGS.append("-DCYTHON_REFNANNY=1")
1261 if options.xml_output_dir and options.fork:
1262 # doesn't currently work together
1263 sys.stderr.write("Disabling forked testing to support XML test output\n")
1264 options.fork = False
1266 if WITH_CYTHON and options.language_level == 3:
1267 sys.stderr.write("Using Cython language level 3.\n")
1269 sys.stderr.write("\n")
1273 for ticket_number in options.tickets:
1275 cmd_args.append('.*T%s$' % ticket_number)
1277 for selector in cmd_args:
1278 if selector.startswith('bugs'):
1282 selectors = [ string_selector(r) for r in cmd_args ]
1284 selectors = [ lambda x, tags=None: True ]
1286 # Chech which external modules are not present and exclude tests
1287 # which depends on them (by prefix)
1289 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1290 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1291 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1294 exclude_selectors += [ string_selector(r) for r in options.exclude ]
1297 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1299 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1300 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1303 if options.compiler:
1304 COMPILER = options.compiler
1307 languages.append('c')
1309 languages.append('cpp')
1311 test_suite = unittest.TestSuite()
1313 if options.unittests:
1314 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1316 if options.doctests:
1317 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1319 if options.filetests and languages:
1320 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1321 options.annotate_source, options.cleanup_workdir,
1322 options.cleanup_sharedlibs, options.pyregr,
1323 options.cython_only, languages, test_bugs,
1324 options.fork, options.language_level)
1325 test_suite.addTest(filetests.build_suite())
1327 if options.system_pyregr and languages:
1328 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1329 options.annotate_source, options.cleanup_workdir,
1330 options.cleanup_sharedlibs, True,
1331 options.cython_only, languages, test_bugs,
1332 options.fork, options.language_level)
1334 filetests.handle_directory(
1335 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1338 if options.xml_output_dir:
1339 from Cython.Tests.xmlrunner import XMLTestRunner
1340 test_runner = XMLTestRunner(output=options.xml_output_dir,
1341 verbose=options.verbosity > 0)
1343 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1345 result = test_runner.run(test_suite)
1347 if options.coverage or options.coverage_xml:
1349 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1350 modules = [ module for name, module in sys.modules.items()
1351 if module is not None and
1352 name.startswith('Cython.Compiler.') and
1353 name[len('Cython.Compiler.'):] not in ignored_modules ]
1354 if options.coverage:
1355 coverage.report(modules, show_missing=0)
1356 if options.coverage_xml:
1357 coverage.xml_report(modules, outfile="coverage-report.xml")
1359 if missing_dep_excluder.tests_missing_deps:
1360 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1361 for test in missing_dep_excluder.tests_missing_deps:
1362 sys.stderr.write(" %s\n" % test)
1364 if options.with_refnanny:
1366 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1373 return_code = not result.wasSuccessful()
1376 check_thread_termination(ignore_seen=False)
1377 sys.exit(return_code)
1378 except PendingThreadsError:
1379 # normal program exit won't kill the threads, do it the hard way here
1380 os._exit(return_code)
1382 if __name__ == '__main__':
1385 except SystemExit: # <= Py2.4 ...
1388 traceback.print_exc()
1390 check_thread_termination(ignore_seen=False)
1391 except PendingThreadsError:
1392 # normal program exit won't kill the threads, do it the hard way here