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)
72 'numpy' : 'tag:numpy',
73 'pstats' : 'tag:pstats',
74 'posix' : 'tag:posix',
77 def get_numpy_include_dirs():
79 return [numpy.get_include()]
83 # test name matcher , callable returning list
84 (re.compile('numpy_.*').match, get_numpy_include_dirs),
89 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
90 # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
91 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
94 (2,5) : (operator.lt, lambda x: x in ['run.any',
96 'run.relativeimport_T542',
97 'run.relativeimport_star_T542',
99 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
101 'run.generators_py', # generators, with statement
102 'run.pure_py', # decorators, with statement
104 (2,7) : (operator.lt, lambda x: x in ['run.withstat_py', # multi context with statement
106 # The next line should start (3,); but this is a dictionary, so
107 # we can only have one (3,) key. Since 2.7 is supposed to be the
108 # last 2.x release, things would have to change drastically for this
110 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3',
111 'run.test_raisefrom',
113 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
114 'compile.extsetslice',
115 'compile.extdelslice',
116 'run.special_methods_T561_py2']),
119 # files that should not be converted to Python 3 code with 2to3
121 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
122 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
123 os.path.join('Cython', 'Debugger', 'libcython.py'),
124 os.path.join('Cython', 'Debugger', 'libpython.py'),
128 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
129 CFLAGS = os.getenv('CFLAGS', '').split()
132 uncomputed = object()
135 res = f._cache.get(args, uncomputed)
136 if res is uncomputed:
137 res = f._cache[args] = f(*args)
143 def parse_tags(filepath):
144 tags = defaultdict(list)
145 f = io_open(filepath, encoding='ISO-8859-1', errors='replace')
155 tag = line[1:ix].strip()
156 values = line[ix+1:].split(',')
157 tags[tag].extend([value.strip() for value in values])
162 parse_tags = memoize(parse_tags)
164 list_unchanging_dir = memoize(lambda x: os.listdir(x))
167 class build_ext(_build_ext):
168 def build_extension(self, ext):
169 if ext.language == 'c++':
171 try: # Py2.7+ & Py3.2+
172 compiler_obj = self.compiler_obj
173 except AttributeError:
174 compiler_obj = self.compiler
175 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
178 _build_ext.build_extension(self, ext)
180 class ErrorWriter(object):
181 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
184 self.write = self.output.append
186 def _collect(self, collect_errors, collect_warnings):
187 s = ''.join(self.output)
189 for line in s.split('\n'):
190 match = self.match_error(line)
192 is_warning, line, column, message = match.groups()
193 if (is_warning and collect_warnings) or \
194 (not is_warning and collect_errors):
195 result.append( (int(line), int(column), message.strip()) )
197 return [ "%d:%d: %s" % values for values in result ]
200 return self._collect(True, False)
202 def getwarnings(self):
203 return self._collect(False, True)
206 return self._collect(True, True)
208 class TestBuilder(object):
209 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
210 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
211 languages, test_bugs, fork, language_level):
212 self.rootdir = rootdir
213 self.workdir = workdir
214 self.selectors = selectors
215 self.exclude_selectors = exclude_selectors
216 self.annotate = annotate
217 self.cleanup_workdir = cleanup_workdir
218 self.cleanup_sharedlibs = cleanup_sharedlibs
219 self.with_pyregr = with_pyregr
220 self.cython_only = cython_only
221 self.languages = languages
222 self.test_bugs = test_bugs
224 self.language_level = language_level
226 def build_suite(self):
227 suite = unittest.TestSuite()
228 filenames = os.listdir(self.rootdir)
230 for filename in filenames:
231 path = os.path.join(self.rootdir, filename)
232 if os.path.isdir(path):
233 if filename == 'pyregr' and not self.with_pyregr:
235 if filename == 'broken' and not self.test_bugs:
238 self.handle_directory(path, filename))
239 if sys.platform not in ['win32']:
240 # Non-Windows makefile.
241 if [1 for selector in self.selectors if selector("embedded")] \
242 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
243 suite.addTest(unittest.makeSuite(EmbedTest))
246 def handle_directory(self, path, context):
247 workdir = os.path.join(self.workdir, context)
248 if not os.path.exists(workdir):
251 suite = unittest.TestSuite()
252 filenames = list_unchanging_dir(path)
254 for filename in filenames:
255 filepath = os.path.join(path, filename)
256 module, ext = os.path.splitext(filename)
257 if ext not in ('.py', '.pyx', '.srctree'):
259 if filename.startswith('.'):
260 continue # certain emacs backup files
261 tags = parse_tags(filepath)
262 fqmodule = "%s.%s" % (context, module)
263 if not [ 1 for match in self.selectors
264 if match(fqmodule, tags) ]:
266 if self.exclude_selectors:
267 if [1 for match in self.exclude_selectors
268 if match(fqmodule, tags)]:
271 mode = 'run' # default
273 mode = tags['mode'][0]
274 elif context == 'pyregr':
277 if ext == '.srctree':
278 suite.addTest(EndToEndTest(filepath, workdir, self.cleanup_workdir))
281 # Choose the test suite.
283 if not filename.startswith('test_'):
285 test_class = CythonPyregrTestCase
287 if module.startswith("test_"):
288 test_class = CythonUnitTestCase
290 test_class = CythonRunTestCase
292 test_class = CythonCompileTestCase
294 for test in self.build_tests(test_class, path, workdir,
295 module, mode == 'error', tags):
297 if mode == 'run' and ext == '.py':
298 # additionally test file in real Python
299 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
303 def build_tests(self, test_class, path, workdir, module, expect_errors, tags):
304 if 'werror' in tags['tags']:
305 warning_errors = True
307 warning_errors = False
310 if 'cpp' in tags['tag'] and 'cpp' in self.languages:
313 languages = self.languages[:1]
315 languages = self.languages
316 if 'cpp' in tags['tag'] and 'c' in languages:
317 languages = list(languages)
318 languages.remove('c')
319 tests = [ self.build_test(test_class, path, workdir, module,
320 language, expect_errors, warning_errors)
321 for language in languages ]
324 def build_test(self, test_class, path, workdir, module,
325 language, expect_errors, warning_errors):
326 workdir = os.path.join(workdir, language)
327 if not os.path.exists(workdir):
329 return test_class(path, workdir, module,
331 expect_errors=expect_errors,
332 annotate=self.annotate,
333 cleanup_workdir=self.cleanup_workdir,
334 cleanup_sharedlibs=self.cleanup_sharedlibs,
335 cython_only=self.cython_only,
337 language_level=self.language_level,
338 warning_errors=warning_errors)
340 class CythonCompileTestCase(unittest.TestCase):
341 def __init__(self, test_directory, workdir, module, language='c',
342 expect_errors=False, annotate=False, cleanup_workdir=True,
343 cleanup_sharedlibs=True, cython_only=False, fork=True,
344 language_level=2, warning_errors=False):
345 self.test_directory = test_directory
346 self.workdir = workdir
348 self.language = language
349 self.expect_errors = expect_errors
350 self.annotate = annotate
351 self.cleanup_workdir = cleanup_workdir
352 self.cleanup_sharedlibs = cleanup_sharedlibs
353 self.cython_only = cython_only
355 self.language_level = language_level
356 self.warning_errors = warning_errors
357 unittest.TestCase.__init__(self)
359 def shortDescription(self):
360 return "compiling (%s) %s" % (self.language, self.module)
363 from Cython.Compiler import Options
364 self._saved_options = [ (name, getattr(Options, name))
365 for name in ('warning_errors', 'error_on_unknown_names') ]
366 Options.warning_errors = self.warning_errors
368 if self.workdir not in sys.path:
369 sys.path.insert(0, self.workdir)
372 from Cython.Compiler import Options
373 for name, value in self._saved_options:
374 setattr(Options, name, value)
377 sys.path.remove(self.workdir)
381 del sys.modules[self.module]
384 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
385 cleanup_lib_files = self.cleanup_sharedlibs
386 if os.path.exists(self.workdir):
387 for rmfile in os.listdir(self.workdir):
388 if not cleanup_c_files:
389 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
391 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
393 if self.annotate and rmfile.endswith(".html"):
396 rmfile = os.path.join(self.workdir, rmfile)
397 if os.path.isdir(rmfile):
398 shutil.rmtree(rmfile, ignore_errors=True)
404 os.makedirs(self.workdir)
407 self.runCompileTest()
409 def runCompileTest(self):
410 self.compile(self.test_directory, self.module, self.workdir,
411 self.test_directory, self.expect_errors, self.annotate)
413 def find_module_source_file(self, source_file):
414 if not os.path.exists(source_file):
415 source_file = source_file[:-1]
418 def build_target_filename(self, module_name):
419 target = '%s.%s' % (module_name, self.language)
422 def related_files(self, test_directory, module_name):
423 is_related = re.compile('%s_.*[.].*' % module_name).match
424 return [filename for filename in list_unchanging_dir(test_directory)
425 if is_related(filename)]
427 def copy_files(self, test_directory, target_directory, file_list):
428 for filename in file_list:
429 shutil.copy(os.path.join(test_directory, filename),
432 def source_files(self, workdir, module_name, file_list):
433 return ([self.build_target_filename(module_name)] +
434 [filename for filename in file_list
435 if not os.path.isfile(os.path.join(workdir, filename))])
437 def split_source_and_output(self, test_directory, module, workdir):
438 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
439 source_and_output = io_open(source_file, 'rU', encoding='ISO-8859-1')
441 out = io_open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
442 'w', encoding='ISO-8859-1')
443 for line in source_and_output:
445 if line.startswith("_ERRORS"):
451 source_and_output.close()
453 geterrors = out.geterrors
454 except AttributeError:
460 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
461 extra_compile_options=None):
462 include_dirs = INCLUDE_DIRS[:]
464 include_dirs.append(incdir)
465 source = self.find_module_source_file(
466 os.path.join(test_directory, module + '.pyx'))
467 target = os.path.join(targetdir, self.build_target_filename(module))
469 if extra_compile_options is None:
470 extra_compile_options = {}
475 from Cython.Compiler.Main import CompilationOptions
476 from Cython.Compiler.Main import compile as cython_compile
477 from Cython.Compiler.Main import default_options
479 options = CompilationOptions(
481 include_path = include_dirs,
482 output_file = target,
484 use_listing_file = False,
485 cplus = self.language == 'cpp',
486 language_level = self.language_level,
487 generate_pxi = False,
488 evaluate_tree_assertions = True,
489 **extra_compile_options
491 cython_compile(source, options=options,
492 full_module_name=module)
494 def run_distutils(self, test_directory, module, workdir, incdir,
495 extra_extension_args=None):
499 build_extension = build_ext(distutils_distro)
500 build_extension.include_dirs = INCLUDE_DIRS[:]
502 build_extension.include_dirs.append(incdir)
503 build_extension.finalize_options()
505 build_extension.compiler = COMPILER
506 ext_include_dirs = []
507 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
509 ext_include_dirs += get_additional_include_dirs()
510 ext_compile_flags = CFLAGS[:]
511 if build_extension.compiler == 'mingw32':
512 ext_compile_flags.append('-Wno-format')
513 if extra_extension_args is None:
514 extra_extension_args = {}
516 related_files = self.related_files(test_directory, module)
517 self.copy_files(test_directory, workdir, related_files)
518 extension = Extension(
520 sources = self.source_files(workdir, module, related_files),
521 include_dirs = ext_include_dirs,
522 extra_compile_args = ext_compile_flags,
523 **extra_extension_args
525 if self.language == 'cpp':
526 extension.language = 'c++'
527 build_extension.extensions = [extension]
528 build_extension.build_temp = workdir
529 build_extension.build_lib = workdir
530 build_extension.run()
534 def compile(self, test_directory, module, workdir, incdir,
535 expect_errors, annotate):
536 expected_errors = errors = ()
538 expected_errors = self.split_source_and_output(
539 test_directory, module, workdir)
540 test_directory = workdir
543 old_stderr = sys.stderr
545 sys.stderr = ErrorWriter()
546 self.run_cython(test_directory, module, workdir, incdir, annotate)
547 errors = sys.stderr.geterrors()
549 sys.stderr = old_stderr
551 if errors or expected_errors:
553 for expected, error in zip(expected_errors, errors):
554 self.assertEquals(expected, error)
555 if len(errors) < len(expected_errors):
556 expected_error = expected_errors[len(errors)]
557 self.assertEquals(expected_error, None)
558 elif len(errors) > len(expected_errors):
559 unexpected_error = errors[len(expected_errors)]
560 self.assertEquals(None, unexpected_error)
561 except AssertionError:
562 print("\n=== Expected errors: ===")
563 print('\n'.join(expected_errors))
564 print("\n\n=== Got errors: ===")
565 print('\n'.join(errors))
569 if not self.cython_only:
570 self.run_distutils(test_directory, module, workdir, incdir)
572 class CythonRunTestCase(CythonCompileTestCase):
573 def shortDescription(self):
574 return "compiling (%s) and running %s" % (self.language, self.module)
576 def run(self, result=None):
578 result = self.defaultTestResult()
579 result.startTest(self)
583 self.runCompileTest()
584 self.run_tests(result)
586 check_thread_termination()
588 result.addError(self, sys.exc_info())
589 result.stopTest(self)
595 def run_tests(self, result):
596 if not self.cython_only:
597 self.run_doctests(self.module, result)
599 def run_doctests(self, module_name, result):
600 def run_test(result):
601 tests = doctest.DocTestSuite(module_name)
603 run_forked_test(result, run_test, self.shortDescription(), self.fork)
606 def run_forked_test(result, run_func, test_name, fork=True):
607 if not fork or sys.version_info[0] >= 3 or not hasattr(os, 'fork'):
612 # fork to make sure we do not keep the tested module loaded
613 result_handle, result_file = tempfile.mkstemp()
614 os.close(result_handle)
622 partial_result = PartialTestResult(result)
623 run_func(partial_result)
627 # importing failed, try to fake a test class
629 failureException=sys.exc_info()[1],
630 _shortDescription=test_name,
632 partial_result.addError(tests, sys.exc_info())
634 output = open(result_file, 'wb')
635 pickle.dump(partial_result.data(), output)
637 traceback.print_exc()
641 os._exit(result_code)
644 cid, result_code = os.waitpid(child_id, 0)
645 # os.waitpid returns the child's result code in the
646 # upper byte of result_code, and the signal it was
647 # killed by in the lower byte
648 if result_code & 255:
649 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
650 (module_name, result_code & 255))
651 result_code = result_code >> 8
652 if result_code in (0,1):
653 input = open(result_file, 'rb')
655 PartialTestResult.join_results(result, pickle.load(input))
659 raise Exception("Tests in module '%s' exited with status %d" %
660 (module_name, result_code))
662 try: os.unlink(result_file)
665 class PureDoctestTestCase(unittest.TestCase):
666 def __init__(self, module_name, module_path):
667 self.module_name = module_name
668 self.module_path = module_path
669 unittest.TestCase.__init__(self, 'run')
671 def shortDescription(self):
672 return "running pure doctests in %s" % self.module_name
674 def run(self, result=None):
676 result = self.defaultTestResult()
677 loaded_module_name = 'pure_doctest__' + self.module_name
678 result.startTest(self)
683 m = imp.load_source(loaded_module_name, self.module_path)
685 doctest.DocTestSuite(m).run(result)
688 if loaded_module_name in sys.modules:
689 del sys.modules[loaded_module_name]
690 check_thread_termination()
692 result.addError(self, sys.exc_info())
693 result.stopTest(self)
699 is_private_field = re.compile('^_[^_]').match
701 class _FakeClass(object):
702 def __init__(self, **kwargs):
703 self._shortDescription = kwargs.get('module_name')
704 self.__dict__.update(kwargs)
705 def shortDescription(self):
706 return self._shortDescription
708 try: # Py2.7+ and Py3.2+
709 from unittest.runner import _TextTestResult
711 from unittest import _TextTestResult
713 class PartialTestResult(_TextTestResult):
714 def __init__(self, base_result):
715 _TextTestResult.__init__(
716 self, self._StringIO(), True,
717 base_result.dots + base_result.showAll*2)
719 def strip_error_results(self, results):
720 for test_case, error in results:
721 for attr_name in filter(is_private_field, dir(test_case)):
722 if attr_name == '_dt_test':
723 test_case._dt_test = _FakeClass(
724 name=test_case._dt_test.name)
725 elif attr_name != '_shortDescription':
726 setattr(test_case, attr_name, None)
729 self.strip_error_results(self.failures)
730 self.strip_error_results(self.errors)
731 return (self.failures, self.errors, self.testsRun,
732 self.stream.getvalue())
734 def join_results(result, data):
735 """Static method for merging the result back into the main
738 failures, errors, tests_run, output = data
740 result.stream.write(output)
741 result.errors.extend(errors)
742 result.failures.extend(failures)
743 result.testsRun += tests_run
745 join_results = staticmethod(join_results)
747 class _StringIO(StringIO):
748 def writeln(self, line):
749 self.write("%s\n" % line)
752 class CythonUnitTestCase(CythonRunTestCase):
753 def shortDescription(self):
754 return "compiling (%s) tests in %s" % (self.language, self.module)
756 def run_tests(self, result):
757 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
760 class CythonPyregrTestCase(CythonRunTestCase):
762 CythonRunTestCase.setUp(self)
763 from Cython.Compiler import Options
764 Options.error_on_unknown_names = False
766 def _run_unittest(self, result, *classes):
767 """Run tests from unittest.TestCase-derived classes."""
768 valid_types = (unittest.TestSuite, unittest.TestCase)
769 suite = unittest.TestSuite()
771 if isinstance(cls, str):
772 if cls in sys.modules:
773 suite.addTest(unittest.findTestCases(sys.modules[cls]))
775 raise ValueError("str arguments must be keys in sys.modules")
776 elif isinstance(cls, valid_types):
779 suite.addTest(unittest.makeSuite(cls))
782 def _run_doctest(self, result, module):
783 self.run_doctests(module, result)
785 def run_tests(self, result):
787 from test import test_support as support
788 except ImportError: # Py3k
789 from test import support
791 def run_test(result):
792 def run_unittest(*classes):
793 return self._run_unittest(result, *classes)
794 def run_doctest(module, verbosity=None):
795 return self._run_doctest(result, module)
797 support.run_unittest = run_unittest
798 support.run_doctest = run_doctest
801 module = __import__(self.module)
802 if hasattr(module, 'test_main'):
804 except (unittest.SkipTest, support.ResourceDenied):
805 result.addSkip(self, 'ok')
807 run_forked_test(result, run_test, self.shortDescription(), self.fork)
809 include_debugger = sys.version_info[:2] > (2, 5)
811 def collect_unittests(path, module_prefix, suite, selectors):
812 def file_matches(filename):
813 return filename.startswith("Test") and filename.endswith(".py")
815 def package_matches(dirname):
816 return dirname == "Tests"
818 loader = unittest.TestLoader()
823 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
825 for dirpath, dirnames, filenames in os.walk(path):
826 if dirpath != path and "__init__.py" not in filenames:
827 skipped_dirs.append(dirpath + os.path.sep)
830 for dir in skipped_dirs:
831 if dirpath.startswith(dir):
835 parentname = os.path.split(dirpath)[-1]
836 if package_matches(parentname):
839 filepath = os.path.join(dirpath, f)[:-len(".py")]
840 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
841 if not [ 1 for match in selectors if match(modulename) ]:
843 module = __import__(modulename)
844 for x in modulename.split('.')[1:]:
845 module = getattr(module, x)
846 suite.addTests([loader.loadTestsFromModule(module)])
850 def collect_doctests(path, module_prefix, suite, selectors):
851 def package_matches(dirname):
852 if dirname == 'Debugger' and not include_debugger:
854 return dirname not in ("Mac", "Distutils", "Plex")
855 def file_matches(filename):
856 filename, ext = os.path.splitext(filename)
857 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
859 return (ext == '.py' and not
860 '~' in filename and not
861 '#' in filename and not
862 filename.startswith('.') and not
863 filename in blacklist)
864 import doctest, types
865 for dirpath, dirnames, filenames in os.walk(path):
866 for dir in list(dirnames):
867 if not package_matches(dir):
871 if not f.endswith('.py'): continue
872 filepath = os.path.join(dirpath, f)
873 if os.path.getsize(filepath) == 0: continue
874 filepath = filepath[:-len(".py")]
875 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
876 if not [ 1 for match in selectors if match(modulename) ]:
878 if 'in_gdb' in modulename:
879 # These should only be imported from gdb.
881 module = __import__(modulename)
882 for x in modulename.split('.')[1:]:
883 module = getattr(module, x)
884 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
886 suite.addTest(doctest.DocTestSuite(module))
887 except ValueError: # no tests
891 class EndToEndTest(unittest.TestCase):
893 This is a test of build/*.srctree files, where srctree defines a full
894 directory structure and its header gives a list of commands to run.
896 cython_root = os.path.dirname(os.path.abspath(__file__))
898 def __init__(self, treefile, workdir, cleanup_workdir=True):
899 self.name = os.path.splitext(os.path.basename(treefile))[0]
900 self.treefile = treefile
901 self.workdir = os.path.join(workdir, self.name)
902 self.cleanup_workdir = cleanup_workdir
903 cython_syspath = self.cython_root
904 for path in sys.path[::-1]:
905 if path.startswith(self.cython_root):
906 # Py3 installation and refnanny build prepend their
907 # fixed paths to sys.path => prefer that over the
909 cython_syspath = path + os.pathsep + cython_syspath
910 self.cython_syspath = cython_syspath
911 unittest.TestCase.__init__(self)
913 def shortDescription(self):
914 return "End-to-end %s" % self.name
917 from Cython.TestUtils import unpack_source_tree
918 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
919 self.old_dir = os.getcwd()
920 os.chdir(self.workdir)
921 if self.workdir not in sys.path:
922 sys.path.insert(0, self.workdir)
925 if self.cleanup_workdir:
926 for trial in range(5):
928 shutil.rmtree(self.workdir)
933 os.chdir(self.old_dir)
936 commands = (self.commands
937 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
938 .replace("PYTHON", sys.executable))
940 old_path = os.environ.get('PYTHONPATH')
941 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
942 for command in commands.split('\n'):
943 if sys.version_info[:2] >= (2,4):
945 p = subprocess.Popen(commands,
946 stderr=subprocess.PIPE,
947 stdout=subprocess.PIPE,
949 out, err = p.communicate()
956 res = os.system(command)
957 self.assertEqual(0, res, "non-zero exit status")
960 os.environ['PYTHONPATH'] = old_path
962 del os.environ['PYTHONPATH']
965 # TODO: Support cython_freeze needed here as well.
966 # TODO: Windows support.
968 class EmbedTest(unittest.TestCase):
970 working_dir = "Demos/embed"
973 self.old_dir = os.getcwd()
974 os.chdir(self.working_dir)
976 "make PYTHON='%s' clean > /dev/null" % sys.executable)
981 "make PYTHON='%s' clean > /dev/null" % sys.executable)
984 os.chdir(self.old_dir)
986 def test_embed(self):
987 from distutils import sysconfig
988 libname = sysconfig.get_config_var('LIBRARY')
989 libdir = sysconfig.get_config_var('LIBDIR')
990 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
991 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
992 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
993 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
994 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
995 # report the error for the original directory
996 libdir = sysconfig.get_config_var('LIBDIR')
998 if sys.version_info[0] >=3 and CY3_DIR:
999 cython = os.path.join(CY3_DIR, cython)
1000 cython = os.path.abspath(os.path.join('..', '..', cython))
1001 self.assert_(os.system(
1002 "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
1004 os.remove('make.output')
1008 class MissingDependencyExcluder:
1009 def __init__(self, deps):
1010 # deps: { module name : matcher func }
1011 self.exclude_matchers = []
1012 for mod, matcher in deps.items():
1016 self.exclude_matchers.append(string_selector(matcher))
1017 self.tests_missing_deps = []
1018 def __call__(self, testname, tags=None):
1019 for matcher in self.exclude_matchers:
1020 if matcher(testname, tags):
1021 self.tests_missing_deps.append(testname)
1025 class VersionDependencyExcluder:
1026 def __init__(self, deps):
1027 # deps: { version : matcher func }
1028 from sys import version_info
1029 self.exclude_matchers = []
1030 for ver, (compare, matcher) in deps.items():
1031 if compare(version_info, ver):
1032 self.exclude_matchers.append(matcher)
1033 self.tests_missing_deps = []
1034 def __call__(self, testname, tags=None):
1035 for matcher in self.exclude_matchers:
1036 if matcher(testname):
1037 self.tests_missing_deps.append(testname)
1041 class FileListExcluder:
1043 def __init__(self, list_file):
1047 for line in f.readlines():
1049 if line and line[0] != '#':
1050 self.excludes[line.split()[0]] = True
1054 def __call__(self, testname, tags=None):
1055 return testname in self.excludes or testname.split('.')[-1] in self.excludes
1059 def __init__(self, tag, value):
1063 def __call__(self, testname, tags=None):
1067 return self.value in tags[self.tag]
1069 class RegExSelector:
1071 def __init__(self, pattern_string):
1072 self.pattern = re.compile(pattern_string, re.I|re.U)
1074 def __call__(self, testname, tags=None):
1075 return self.pattern.search(testname)
1077 def string_selector(s):
1080 return RegExSelector(s)
1082 return TagsSelector(s[:ix], s[ix+1:])
1085 def refactor_for_py3(distdir, cy3_dir):
1086 # need to convert Cython sources first
1087 import lib2to3.refactor
1088 from distutils.util import copydir_run_2to3
1089 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
1090 if fix.split('fix_')[-1] not in ('next',)
1092 if not os.path.exists(cy3_dir):
1093 os.makedirs(cy3_dir)
1094 import distutils.log as dlog
1095 dlog.set_threshold(dlog.INFO)
1096 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1100 recursive-exclude Cython *
1101 recursive-include Cython *.py *.pyx *.pxd
1102 recursive-include Cython/Debugger/Tests *
1106 sys.path.insert(0, cy3_dir)
1108 for keep_2x_file in KEEP_2X_FILES:
1109 destfile = os.path.join(cy3_dir, keep_2x_file)
1110 shutil.copy(keep_2x_file, destfile)
1112 class PendingThreadsError(RuntimeError):
1117 def check_thread_termination(ignore_seen=True):
1118 if threading is None: # no threading enabled in CPython
1120 current = threading.currentThread()
1121 blocking_threads = []
1122 for t in threading.enumerate():
1123 if not t.isAlive() or t == current:
1128 blocking_threads.append(t)
1130 for seen in threads_seen:
1134 threads_seen.append(t)
1135 blocking_threads.append(t)
1136 if not blocking_threads:
1138 sys.stderr.write("warning: left-over threads found after running test:\n")
1139 for t in blocking_threads:
1140 sys.stderr.write('...%s\n' % repr(t))
1141 raise PendingThreadsError("left-over threads found after running test")
1145 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1147 from optparse import OptionParser
1148 parser = OptionParser()
1149 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1150 action="store_false", default=True,
1151 help="do not delete the generated C files (allows passing --no-cython on next run)")
1152 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1153 action="store_false", default=True,
1154 help="do not delete the generated shared libary files (allows manual module experimentation)")
1155 parser.add_option("--no-cython", dest="with_cython",
1156 action="store_false", default=True,
1157 help="do not run the Cython compiler, only the C compiler")
1158 parser.add_option("--compiler", dest="compiler", default=None,
1159 help="C compiler type")
1160 parser.add_option("--no-c", dest="use_c",
1161 action="store_false", default=True,
1162 help="do not test C compilation")
1163 parser.add_option("--no-cpp", dest="use_cpp",
1164 action="store_false", default=True,
1165 help="do not test C++ compilation")
1166 parser.add_option("--no-unit", dest="unittests",
1167 action="store_false", default=True,
1168 help="do not run the unit tests")
1169 parser.add_option("--no-doctest", dest="doctests",
1170 action="store_false", default=True,
1171 help="do not run the doctests")
1172 parser.add_option("--no-file", dest="filetests",
1173 action="store_false", default=True,
1174 help="do not run the file based tests")
1175 parser.add_option("--no-pyregr", dest="pyregr",
1176 action="store_false", default=True,
1177 help="do not run the regression tests of CPython in tests/pyregr/")
1178 parser.add_option("--cython-only", dest="cython_only",
1179 action="store_true", default=False,
1180 help="only compile pyx to c, do not run C compiler or run the tests")
1181 parser.add_option("--no-refnanny", dest="with_refnanny",
1182 action="store_false", default=True,
1183 help="do not regression test reference counting")
1184 parser.add_option("--no-fork", dest="fork",
1185 action="store_false", default=True,
1186 help="do not fork to run tests")
1187 parser.add_option("--sys-pyregr", dest="system_pyregr",
1188 action="store_true", default=False,
1189 help="run the regression tests of the CPython installation")
1190 parser.add_option("-x", "--exclude", dest="exclude",
1191 action="append", metavar="PATTERN",
1192 help="exclude tests matching the PATTERN")
1193 parser.add_option("-C", "--coverage", dest="coverage",
1194 action="store_true", default=False,
1195 help="collect source coverage data for the Compiler")
1196 parser.add_option("--coverage-xml", dest="coverage_xml",
1197 action="store_true", default=False,
1198 help="collect source coverage data for the Compiler in XML format")
1199 parser.add_option("--coverage-html", dest="coverage_html",
1200 action="store_true", default=False,
1201 help="collect source coverage data for the Compiler in HTML format")
1202 parser.add_option("-A", "--annotate", dest="annotate_source",
1203 action="store_true", default=True,
1204 help="generate annotated HTML versions of the test source files")
1205 parser.add_option("--no-annotate", dest="annotate_source",
1206 action="store_false",
1207 help="do not generate annotated HTML versions of the test source files")
1208 parser.add_option("-v", "--verbose", dest="verbosity",
1209 action="count", default=0,
1210 help="display test progress, pass twice to print test names")
1211 parser.add_option("-T", "--ticket", dest="tickets",
1213 help="a bug ticket number to run the respective test in 'tests/*'")
1214 parser.add_option("-3", dest="language_level",
1215 action="store_const", const=3, default=2,
1216 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1217 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1218 help="write test results in XML to directory DIR")
1219 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1220 action="store_true",
1221 help="exit without error code even on test failures")
1222 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1223 help="working directory")
1224 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1225 help="working directory")
1227 options, cmd_args = parser.parse_args()
1229 ROOTDIR = os.path.abspath(options.root_dir)
1230 WORKDIR = os.path.abspath(options.work_dir)
1232 if sys.version_info[0] >= 3:
1233 options.doctests = False
1234 if options.with_cython:
1236 # try if Cython is installed in a Py3 version
1237 import Cython.Compiler.Main
1239 # back out anything the import process loaded, then
1240 # 2to3 the Cython sources to make them re-importable
1241 cy_modules = [ name for name in sys.modules
1242 if name == 'Cython' or name.startswith('Cython.') ]
1243 for name in cy_modules:
1244 del sys.modules[name]
1245 # hasn't been refactored yet - do it now
1247 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1248 if sys.version_info >= (3,1):
1249 refactor_for_py3(DISTDIR, cy3_dir)
1250 elif os.path.isdir(cy3_dir):
1251 sys.path.insert(0, cy3_dir)
1253 options.with_cython = False
1255 WITH_CYTHON = options.with_cython
1257 if options.coverage or options.coverage_xml or options.coverage_html:
1259 options.coverage = options.coverage_xml = options.coverage_html = False
1261 from coverage import coverage as _coverage
1262 coverage = _coverage(branch=True)
1267 global CompilationOptions, pyrex_default_options, cython_compile
1268 from Cython.Compiler.Main import \
1269 CompilationOptions, \
1270 default_options as pyrex_default_options, \
1271 compile as cython_compile
1272 from Cython.Compiler import Errors
1273 Errors.LEVEL = 0 # show all warnings
1274 from Cython.Compiler import Options
1275 Options.generate_cleanup_code = 3 # complete cleanup code
1276 from Cython.Compiler import DebugFlags
1277 DebugFlags.debug_temp_code_comments = 1
1280 UNITTEST_MODULE = "Cython"
1281 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1283 if os.path.exists(WORKDIR):
1284 for path in os.listdir(WORKDIR):
1285 if path in ("support", "Cy3"): continue
1286 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1287 if not os.path.exists(WORKDIR):
1288 os.makedirs(WORKDIR)
1290 sys.stderr.write("Python %s\n" % sys.version)
1291 sys.stderr.write("\n")
1293 from Cython.Compiler.Version import version
1294 sys.stderr.write("Running tests against Cython %s\n" % version)
1296 sys.stderr.write("Running tests without Cython.\n")
1298 if options.with_refnanny:
1299 from pyximport.pyxbuild import pyx_to_dll
1300 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1302 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1303 sys.path.insert(0, os.path.split(libpath)[0])
1304 CFLAGS.append("-DCYTHON_REFNANNY=1")
1306 if options.xml_output_dir and options.fork:
1307 # doesn't currently work together
1308 sys.stderr.write("Disabling forked testing to support XML test output\n")
1309 options.fork = False
1311 if WITH_CYTHON and options.language_level == 3:
1312 sys.stderr.write("Using Cython language level 3.\n")
1314 sys.stderr.write("\n")
1318 for ticket_number in options.tickets:
1320 cmd_args.append('ticket:%s' % ticket_number)
1322 for selector in cmd_args:
1323 if selector.startswith('bugs'):
1327 selectors = [ string_selector(r) for r in cmd_args ]
1329 selectors = [ lambda x, tags=None: True ]
1331 # Chech which external modules are not present and exclude tests
1332 # which depends on them (by prefix)
1334 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1335 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1336 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1339 exclude_selectors += [ string_selector(r) for r in options.exclude ]
1342 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1344 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1345 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1348 if options.compiler:
1349 COMPILER = options.compiler
1352 languages.append('c')
1354 languages.append('cpp')
1356 test_suite = unittest.TestSuite()
1358 if options.unittests:
1359 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1361 if options.doctests:
1362 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1364 if options.filetests and languages:
1365 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1366 options.annotate_source, options.cleanup_workdir,
1367 options.cleanup_sharedlibs, options.pyregr,
1368 options.cython_only, languages, test_bugs,
1369 options.fork, options.language_level)
1370 test_suite.addTest(filetests.build_suite())
1372 if options.system_pyregr and languages:
1373 sys_pyregr_dir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test')
1374 if os.path.isdir(sys_pyregr_dir):
1375 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1376 options.annotate_source, options.cleanup_workdir,
1377 options.cleanup_sharedlibs, True,
1378 options.cython_only, languages, test_bugs,
1379 options.fork, sys.version_info[0])
1380 sys.stderr.write("Including CPython regression tests in %s\n" % sys_pyregr_dir)
1381 test_suite.addTest(filetests.handle_directory(sys_pyregr_dir, 'pyregr'))
1383 if options.xml_output_dir:
1384 from Cython.Tests.xmlrunner import XMLTestRunner
1385 test_runner = XMLTestRunner(output=options.xml_output_dir,
1386 verbose=options.verbosity > 0)
1388 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1390 result = test_runner.run(test_suite)
1392 if options.coverage or options.coverage_xml or options.coverage_html:
1394 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1395 modules = [ module for name, module in sys.modules.items()
1396 if module is not None and
1397 name.startswith('Cython.Compiler.') and
1398 name[len('Cython.Compiler.'):] not in ignored_modules ]
1399 if options.coverage:
1400 coverage.report(modules, show_missing=0)
1401 if options.coverage_xml:
1402 coverage.xml_report(modules, outfile="coverage-report.xml")
1403 if options.coverage_html:
1404 coverage.html_report(modules, directory="coverage-report-html")
1406 if missing_dep_excluder.tests_missing_deps:
1407 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1408 for test in missing_dep_excluder.tests_missing_deps:
1409 sys.stderr.write(" %s\n" % test)
1411 if options.with_refnanny:
1413 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1420 return_code = not result.wasSuccessful()
1423 check_thread_termination(ignore_seen=False)
1424 sys.exit(return_code)
1425 except PendingThreadsError:
1426 # normal program exit won't kill the threads, do it the hard way here
1427 os._exit(return_code)
1429 if __name__ == '__main__':
1432 except SystemExit: # <= Py2.4 ...
1435 traceback.print_exc()
1437 check_thread_termination(ignore_seen=False)
1438 except PendingThreadsError:
1439 # normal program exit won't kill the threads, do it the hard way here