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 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
112 'compile.extsetslice',
113 'compile.extdelslice',
114 'run.special_methods_T561_py2']),
117 # files that should not be converted to Python 3 code with 2to3
119 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
120 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
121 os.path.join('Cython', 'Debugger', 'libcython.py'),
122 os.path.join('Cython', 'Debugger', 'libpython.py'),
126 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
127 CFLAGS = os.getenv('CFLAGS', '').split()
130 uncomputed = object()
133 res = f._cache.get(args, uncomputed)
134 if res is uncomputed:
135 res = f._cache[args] = f(*args)
139 def parse_tags(filepath):
140 tags = defaultdict(list)
141 f = io_open(filepath, encoding='ISO-8859-1', errors='replace')
151 tag = line[1:ix].strip()
152 values = line[ix+1:].split(',')
153 tags[tag].extend([value.strip() for value in values])
158 parse_tags = memoize(parse_tags)
161 class build_ext(_build_ext):
162 def build_extension(self, ext):
163 if ext.language == 'c++':
165 try: # Py2.7+ & Py3.2+
166 compiler_obj = self.compiler_obj
167 except AttributeError:
168 compiler_obj = self.compiler
169 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
172 _build_ext.build_extension(self, ext)
174 class ErrorWriter(object):
175 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
178 self.write = self.output.append
180 def _collect(self, collect_errors, collect_warnings):
181 s = ''.join(self.output)
183 for line in s.split('\n'):
184 match = self.match_error(line)
186 is_warning, line, column, message = match.groups()
187 if (is_warning and collect_warnings) or \
188 (not is_warning and collect_errors):
189 result.append( (int(line), int(column), message.strip()) )
191 return [ "%d:%d: %s" % values for values in result ]
194 return self._collect(True, False)
196 def getwarnings(self):
197 return self._collect(False, True)
200 return self._collect(True, True)
202 class TestBuilder(object):
203 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
204 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
205 languages, test_bugs, fork, language_level):
206 self.rootdir = rootdir
207 self.workdir = workdir
208 self.selectors = selectors
209 self.exclude_selectors = exclude_selectors
210 self.annotate = annotate
211 self.cleanup_workdir = cleanup_workdir
212 self.cleanup_sharedlibs = cleanup_sharedlibs
213 self.with_pyregr = with_pyregr
214 self.cython_only = cython_only
215 self.languages = languages
216 self.test_bugs = test_bugs
218 self.language_level = language_level
220 def build_suite(self):
221 suite = unittest.TestSuite()
222 filenames = os.listdir(self.rootdir)
224 for filename in filenames:
225 path = os.path.join(self.rootdir, filename)
226 if os.path.isdir(path):
227 if filename == 'pyregr' and not self.with_pyregr:
229 if filename == 'broken' and not self.test_bugs:
232 self.handle_directory(path, filename))
233 if sys.platform not in ['win32']:
234 # Non-Windows makefile.
235 if [1 for selector in self.selectors if selector("embedded")] \
236 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
237 suite.addTest(unittest.makeSuite(EmbedTest))
240 def handle_directory(self, path, context):
241 workdir = os.path.join(self.workdir, context)
242 if not os.path.exists(workdir):
245 suite = unittest.TestSuite()
246 filenames = os.listdir(path)
248 for filename in filenames:
249 filepath = os.path.join(path, filename)
250 module, ext = os.path.splitext(filename)
251 if ext not in ('.py', '.pyx', '.srctree'):
253 if filename.startswith('.'):
254 continue # certain emacs backup files
255 tags = parse_tags(filepath)
256 fqmodule = "%s.%s" % (context, module)
257 if not [ 1 for match in self.selectors
258 if match(fqmodule, tags) ]:
260 if self.exclude_selectors:
261 if [1 for match in self.exclude_selectors
262 if match(fqmodule, tags)]:
265 mode = 'run' # default
267 mode = tags['mode'][0]
268 elif context == 'pyregr':
271 if ext == '.srctree':
272 suite.addTest(EndToEndTest(filepath, workdir, self.cleanup_workdir))
275 # Choose the test suite.
277 if not filename.startswith('test_'):
279 test_class = CythonPyregrTestCase
281 if module.startswith("test_"):
282 test_class = CythonUnitTestCase
284 test_class = CythonRunTestCase
286 test_class = CythonCompileTestCase
288 for test in self.build_tests(test_class, path, workdir,
289 module, mode == 'error', tags):
291 if mode == 'run' and ext == '.py':
292 # additionally test file in real Python
293 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
297 def build_tests(self, test_class, path, workdir, module, expect_errors, tags):
298 if 'werror' in tags['tags']:
299 warning_errors = True
301 warning_errors = False
304 if 'cpp' in tags['tag'] and 'cpp' in self.languages:
307 languages = self.languages[:1]
309 languages = self.languages
310 if 'cpp' in tags['tag'] and 'c' in languages:
311 languages = list(languages)
312 languages.remove('c')
313 tests = [ self.build_test(test_class, path, workdir, module,
314 language, expect_errors, warning_errors)
315 for language in languages ]
318 def build_test(self, test_class, path, workdir, module,
319 language, expect_errors, warning_errors):
320 workdir = os.path.join(workdir, language)
321 if not os.path.exists(workdir):
323 return test_class(path, workdir, module,
325 expect_errors=expect_errors,
326 annotate=self.annotate,
327 cleanup_workdir=self.cleanup_workdir,
328 cleanup_sharedlibs=self.cleanup_sharedlibs,
329 cython_only=self.cython_only,
331 language_level=self.language_level,
332 warning_errors=warning_errors)
334 class CythonCompileTestCase(unittest.TestCase):
335 def __init__(self, test_directory, workdir, module, language='c',
336 expect_errors=False, annotate=False, cleanup_workdir=True,
337 cleanup_sharedlibs=True, cython_only=False, fork=True,
338 language_level=2, warning_errors=False):
339 self.test_directory = test_directory
340 self.workdir = workdir
342 self.language = language
343 self.expect_errors = expect_errors
344 self.annotate = annotate
345 self.cleanup_workdir = cleanup_workdir
346 self.cleanup_sharedlibs = cleanup_sharedlibs
347 self.cython_only = cython_only
349 self.language_level = language_level
350 self.warning_errors = warning_errors
351 unittest.TestCase.__init__(self)
353 def shortDescription(self):
354 return "compiling (%s) %s" % (self.language, self.module)
357 from Cython.Compiler import Options
358 self._saved_options = [ (name, getattr(Options, name))
359 for name in ('warning_errors', 'error_on_unknown_names') ]
360 Options.warning_errors = self.warning_errors
362 if self.workdir not in sys.path:
363 sys.path.insert(0, self.workdir)
366 from Cython.Compiler import Options
367 for name, value in self._saved_options:
368 setattr(Options, name, value)
371 sys.path.remove(self.workdir)
375 del sys.modules[self.module]
378 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
379 cleanup_lib_files = self.cleanup_sharedlibs
380 if os.path.exists(self.workdir):
381 for rmfile in os.listdir(self.workdir):
382 if not cleanup_c_files:
383 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
385 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
387 if self.annotate and rmfile.endswith(".html"):
390 rmfile = os.path.join(self.workdir, rmfile)
391 if os.path.isdir(rmfile):
392 shutil.rmtree(rmfile, ignore_errors=True)
398 os.makedirs(self.workdir)
401 self.runCompileTest()
403 def runCompileTest(self):
404 self.compile(self.test_directory, self.module, self.workdir,
405 self.test_directory, self.expect_errors, self.annotate)
407 def find_module_source_file(self, source_file):
408 if not os.path.exists(source_file):
409 source_file = source_file[:-1]
412 def build_target_filename(self, module_name):
413 target = '%s.%s' % (module_name, self.language)
416 def copy_related_files(self, test_directory, target_directory, module_name):
417 is_related = re.compile('%s_.*[.].*' % module_name).match
418 for filename in os.listdir(test_directory):
419 if is_related(filename):
420 shutil.copy(os.path.join(test_directory, filename),
423 def find_source_files(self, workdir, module_name):
424 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
425 return [self.build_target_filename(module_name)] + [
426 filename for filename in os.listdir(workdir)
427 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
429 def split_source_and_output(self, test_directory, module, workdir):
430 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
431 source_and_output = io_open(source_file, 'rU', encoding='ISO-8859-1')
433 out = io_open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
434 'w', encoding='ISO-8859-1')
435 for line in source_and_output:
437 if line.startswith("_ERRORS"):
443 source_and_output.close()
445 geterrors = out.geterrors
446 except AttributeError:
452 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
453 extra_compile_options=None):
454 include_dirs = INCLUDE_DIRS[:]
456 include_dirs.append(incdir)
457 source = self.find_module_source_file(
458 os.path.join(test_directory, module + '.pyx'))
459 target = os.path.join(targetdir, self.build_target_filename(module))
461 if extra_compile_options is None:
462 extra_compile_options = {}
467 from Cython.Compiler.Main import CompilationOptions
468 from Cython.Compiler.Main import compile as cython_compile
469 from Cython.Compiler.Main import default_options
471 options = CompilationOptions(
473 include_path = include_dirs,
474 output_file = target,
476 use_listing_file = False,
477 cplus = self.language == 'cpp',
478 language_level = self.language_level,
479 generate_pxi = False,
480 evaluate_tree_assertions = True,
481 **extra_compile_options
483 cython_compile(source, options=options,
484 full_module_name=module)
486 def run_distutils(self, test_directory, module, workdir, incdir,
487 extra_extension_args=None):
491 build_extension = build_ext(distutils_distro)
492 build_extension.include_dirs = INCLUDE_DIRS[:]
494 build_extension.include_dirs.append(incdir)
495 build_extension.finalize_options()
497 build_extension.compiler = COMPILER
498 ext_include_dirs = []
499 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
501 ext_include_dirs += get_additional_include_dirs()
502 ext_compile_flags = CFLAGS[:]
503 if build_extension.compiler == 'mingw32':
504 ext_compile_flags.append('-Wno-format')
505 if extra_extension_args is None:
506 extra_extension_args = {}
508 self.copy_related_files(test_directory, workdir, module)
509 extension = Extension(
511 sources = self.find_source_files(workdir, module),
512 include_dirs = ext_include_dirs,
513 extra_compile_args = ext_compile_flags,
514 **extra_extension_args
516 if self.language == 'cpp':
517 extension.language = 'c++'
518 build_extension.extensions = [extension]
519 build_extension.build_temp = workdir
520 build_extension.build_lib = workdir
521 build_extension.run()
525 def compile(self, test_directory, module, workdir, incdir,
526 expect_errors, annotate):
527 expected_errors = errors = ()
529 expected_errors = self.split_source_and_output(
530 test_directory, module, workdir)
531 test_directory = workdir
534 old_stderr = sys.stderr
536 sys.stderr = ErrorWriter()
537 self.run_cython(test_directory, module, workdir, incdir, annotate)
538 errors = sys.stderr.geterrors()
540 sys.stderr = old_stderr
542 if errors or expected_errors:
544 for expected, error in zip(expected_errors, errors):
545 self.assertEquals(expected, error)
546 if len(errors) < len(expected_errors):
547 expected_error = expected_errors[len(errors)]
548 self.assertEquals(expected_error, None)
549 elif len(errors) > len(expected_errors):
550 unexpected_error = errors[len(expected_errors)]
551 self.assertEquals(None, unexpected_error)
552 except AssertionError:
553 print("\n=== Expected errors: ===")
554 print('\n'.join(expected_errors))
555 print("\n\n=== Got errors: ===")
556 print('\n'.join(errors))
560 if not self.cython_only:
561 self.run_distutils(test_directory, module, workdir, incdir)
563 class CythonRunTestCase(CythonCompileTestCase):
564 def shortDescription(self):
565 return "compiling (%s) and running %s" % (self.language, self.module)
567 def run(self, result=None):
569 result = self.defaultTestResult()
570 result.startTest(self)
574 self.runCompileTest()
575 self.run_tests(result)
577 check_thread_termination()
579 result.addError(self, sys.exc_info())
580 result.stopTest(self)
586 def run_tests(self, result):
587 if not self.cython_only:
588 self.run_doctests(self.module, result)
590 def run_doctests(self, module_name, result):
591 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
592 doctest.DocTestSuite(module_name).run(result)
596 # fork to make sure we do not keep the tested module loaded
597 result_handle, result_file = tempfile.mkstemp()
598 os.close(result_handle)
606 partial_result = PartialTestResult(result)
607 tests = doctest.DocTestSuite(module_name)
608 tests.run(partial_result)
612 # importing failed, try to fake a test class
614 failureException=sys.exc_info()[1],
615 _shortDescription=self.shortDescription(),
617 partial_result.addError(tests, sys.exc_info())
619 output = open(result_file, 'wb')
620 pickle.dump(partial_result.data(), output)
622 traceback.print_exc()
626 os._exit(result_code)
629 cid, result_code = os.waitpid(child_id, 0)
630 # os.waitpid returns the child's result code in the
631 # upper byte of result_code, and the signal it was
632 # killed by in the lower byte
633 if result_code & 255:
634 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
635 (module_name, result_code & 255))
636 result_code = result_code >> 8
637 if result_code in (0,1):
638 input = open(result_file, 'rb')
640 PartialTestResult.join_results(result, pickle.load(input))
644 raise Exception("Tests in module '%s' exited with status %d" %
645 (module_name, result_code))
647 try: os.unlink(result_file)
650 class PureDoctestTestCase(unittest.TestCase):
651 def __init__(self, module_name, module_path):
652 self.module_name = module_name
653 self.module_path = module_path
654 unittest.TestCase.__init__(self, 'run')
656 def shortDescription(self):
657 return "running pure doctests in %s" % self.module_name
659 def run(self, result=None):
661 result = self.defaultTestResult()
662 loaded_module_name = 'pure_doctest__' + self.module_name
663 result.startTest(self)
668 m = imp.load_source(loaded_module_name, self.module_path)
670 doctest.DocTestSuite(m).run(result)
673 if loaded_module_name in sys.modules:
674 del sys.modules[loaded_module_name]
675 check_thread_termination()
677 result.addError(self, sys.exc_info())
678 result.stopTest(self)
684 is_private_field = re.compile('^_[^_]').match
686 class _FakeClass(object):
687 def __init__(self, **kwargs):
688 self._shortDescription = kwargs.get('module_name')
689 self.__dict__.update(kwargs)
690 def shortDescription(self):
691 return self._shortDescription
693 try: # Py2.7+ and Py3.2+
694 from unittest.runner import _TextTestResult
696 from unittest import _TextTestResult
698 class PartialTestResult(_TextTestResult):
699 def __init__(self, base_result):
700 _TextTestResult.__init__(
701 self, self._StringIO(), True,
702 base_result.dots + base_result.showAll*2)
704 def strip_error_results(self, results):
705 for test_case, error in results:
706 for attr_name in filter(is_private_field, dir(test_case)):
707 if attr_name == '_dt_test':
708 test_case._dt_test = _FakeClass(
709 name=test_case._dt_test.name)
710 elif attr_name != '_shortDescription':
711 setattr(test_case, attr_name, None)
714 self.strip_error_results(self.failures)
715 self.strip_error_results(self.errors)
716 return (self.failures, self.errors, self.testsRun,
717 self.stream.getvalue())
719 def join_results(result, data):
720 """Static method for merging the result back into the main
723 failures, errors, tests_run, output = data
725 result.stream.write(output)
726 result.errors.extend(errors)
727 result.failures.extend(failures)
728 result.testsRun += tests_run
730 join_results = staticmethod(join_results)
732 class _StringIO(StringIO):
733 def writeln(self, line):
734 self.write("%s\n" % line)
737 class CythonUnitTestCase(CythonRunTestCase):
738 def shortDescription(self):
739 return "compiling (%s) tests in %s" % (self.language, self.module)
741 def run_tests(self, result):
742 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
745 class CythonPyregrTestCase(CythonRunTestCase):
747 CythonRunTestCase.setUp(self)
748 from Cython.Compiler import Options
749 Options.error_on_unknown_names = False
751 def _run_unittest(self, result, *classes):
752 """Run tests from unittest.TestCase-derived classes."""
753 valid_types = (unittest.TestSuite, unittest.TestCase)
754 suite = unittest.TestSuite()
756 if isinstance(cls, str):
757 if cls in sys.modules:
758 suite.addTest(unittest.findTestCases(sys.modules[cls]))
760 raise ValueError("str arguments must be keys in sys.modules")
761 elif isinstance(cls, valid_types):
764 suite.addTest(unittest.makeSuite(cls))
767 def _run_doctest(self, result, module):
768 self.run_doctests(module, result)
770 def run_tests(self, result):
772 from test import test_support as support
773 except ImportError: # Py3k
774 from test import support
776 def run_unittest(*classes):
777 return self._run_unittest(result, *classes)
778 def run_doctest(module, verbosity=None):
779 return self._run_doctest(result, module)
781 support.run_unittest = run_unittest
782 support.run_doctest = run_doctest
785 module = __import__(self.module)
786 if hasattr(module, 'test_main'):
788 except (unittest.SkipTest, support.ResourceDenied):
789 result.addSkip(self, 'ok')
791 include_debugger = sys.version_info[:2] > (2, 5)
793 def collect_unittests(path, module_prefix, suite, selectors):
794 def file_matches(filename):
795 return filename.startswith("Test") and filename.endswith(".py")
797 def package_matches(dirname):
798 return dirname == "Tests"
800 loader = unittest.TestLoader()
805 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
807 for dirpath, dirnames, filenames in os.walk(path):
808 if dirpath != path and "__init__.py" not in filenames:
809 skipped_dirs.append(dirpath + os.path.sep)
812 for dir in skipped_dirs:
813 if dirpath.startswith(dir):
817 parentname = os.path.split(dirpath)[-1]
818 if package_matches(parentname):
821 filepath = os.path.join(dirpath, f)[:-len(".py")]
822 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
823 if not [ 1 for match in selectors if match(modulename) ]:
825 module = __import__(modulename)
826 for x in modulename.split('.')[1:]:
827 module = getattr(module, x)
828 suite.addTests([loader.loadTestsFromModule(module)])
832 def collect_doctests(path, module_prefix, suite, selectors):
833 def package_matches(dirname):
834 if dirname == 'Debugger' and not include_debugger:
836 return dirname not in ("Mac", "Distutils", "Plex")
837 def file_matches(filename):
838 filename, ext = os.path.splitext(filename)
839 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
841 return (ext == '.py' and not
842 '~' in filename and not
843 '#' in filename and not
844 filename.startswith('.') and not
845 filename in blacklist)
846 import doctest, types
847 for dirpath, dirnames, filenames in os.walk(path):
848 for dir in list(dirnames):
849 if not package_matches(dir):
853 if not f.endswith('.py'): continue
854 filepath = os.path.join(dirpath, f)
855 if os.path.getsize(filepath) == 0: continue
856 filepath = filepath[:-len(".py")]
857 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
858 if not [ 1 for match in selectors if match(modulename) ]:
860 if 'in_gdb' in modulename:
861 # These should only be imported from gdb.
863 module = __import__(modulename)
864 for x in modulename.split('.')[1:]:
865 module = getattr(module, x)
866 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
868 suite.addTest(doctest.DocTestSuite(module))
869 except ValueError: # no tests
873 class EndToEndTest(unittest.TestCase):
875 This is a test of build/*.srctree files, where srctree defines a full
876 directory structure and its header gives a list of commands to run.
878 cython_root = os.path.dirname(os.path.abspath(__file__))
880 def __init__(self, treefile, workdir, cleanup_workdir=True):
881 self.name = os.path.splitext(os.path.basename(treefile))[0]
882 self.treefile = treefile
883 self.workdir = os.path.join(workdir, self.name)
884 self.cleanup_workdir = cleanup_workdir
885 cython_syspath = self.cython_root
886 for path in sys.path[::-1]:
887 if path.startswith(self.cython_root):
888 # Py3 installation and refnanny build prepend their
889 # fixed paths to sys.path => prefer that over the
891 cython_syspath = path + os.pathsep + cython_syspath
892 self.cython_syspath = cython_syspath
893 unittest.TestCase.__init__(self)
895 def shortDescription(self):
896 return "End-to-end %s" % self.name
899 from Cython.TestUtils import unpack_source_tree
900 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
901 self.old_dir = os.getcwd()
902 os.chdir(self.workdir)
903 if self.workdir not in sys.path:
904 sys.path.insert(0, self.workdir)
907 if self.cleanup_workdir:
908 for trial in range(5):
910 shutil.rmtree(self.workdir)
915 os.chdir(self.old_dir)
918 commands = (self.commands
919 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
920 .replace("PYTHON", sys.executable))
922 old_path = os.environ.get('PYTHONPATH')
923 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
924 for command in commands.split('\n'):
925 if sys.version_info[:2] >= (2,4):
927 p = subprocess.Popen(commands,
928 stderr=subprocess.PIPE,
929 stdout=subprocess.PIPE,
931 out, err = p.communicate()
938 res = os.system(command)
939 self.assertEqual(0, res, "non-zero exit status")
942 os.environ['PYTHONPATH'] = old_path
944 del os.environ['PYTHONPATH']
947 # TODO: Support cython_freeze needed here as well.
948 # TODO: Windows support.
950 class EmbedTest(unittest.TestCase):
952 working_dir = "Demos/embed"
955 self.old_dir = os.getcwd()
956 os.chdir(self.working_dir)
958 "make PYTHON='%s' clean > /dev/null" % sys.executable)
963 "make PYTHON='%s' clean > /dev/null" % sys.executable)
966 os.chdir(self.old_dir)
968 def test_embed(self):
969 from distutils import sysconfig
970 libname = sysconfig.get_config_var('LIBRARY')
971 libdir = sysconfig.get_config_var('LIBDIR')
972 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
973 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
974 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
975 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
976 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
977 # report the error for the original directory
978 libdir = sysconfig.get_config_var('LIBDIR')
980 if sys.version_info[0] >=3 and CY3_DIR:
981 cython = os.path.join(CY3_DIR, cython)
982 cython = os.path.abspath(os.path.join('..', '..', cython))
983 self.assert_(os.system(
984 "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
986 os.remove('make.output')
990 class MissingDependencyExcluder:
991 def __init__(self, deps):
992 # deps: { module name : matcher func }
993 self.exclude_matchers = []
994 for mod, matcher in deps.items():
998 self.exclude_matchers.append(string_selector(matcher))
999 self.tests_missing_deps = []
1000 def __call__(self, testname, tags=None):
1001 for matcher in self.exclude_matchers:
1002 if matcher(testname, tags):
1003 self.tests_missing_deps.append(testname)
1007 class VersionDependencyExcluder:
1008 def __init__(self, deps):
1009 # deps: { version : matcher func }
1010 from sys import version_info
1011 self.exclude_matchers = []
1012 for ver, (compare, matcher) in deps.items():
1013 if compare(version_info, ver):
1014 self.exclude_matchers.append(matcher)
1015 self.tests_missing_deps = []
1016 def __call__(self, testname, tags=None):
1017 for matcher in self.exclude_matchers:
1018 if matcher(testname):
1019 self.tests_missing_deps.append(testname)
1023 class FileListExcluder:
1025 def __init__(self, list_file):
1029 for line in f.readlines():
1031 if line and line[0] != '#':
1032 self.excludes[line.split()[0]] = True
1036 def __call__(self, testname, tags=None):
1037 return testname in self.excludes or testname.split('.')[-1] in self.excludes
1041 def __init__(self, tag, value):
1045 def __call__(self, testname, tags=None):
1049 return self.value in tags[self.tag]
1051 class RegExSelector:
1053 def __init__(self, pattern_string):
1054 self.pattern = re.compile(pattern_string, re.I|re.U)
1056 def __call__(self, testname, tags=None):
1057 return self.pattern.search(testname)
1059 def string_selector(s):
1062 return RegExSelector(s)
1064 return TagsSelector(s[:ix], s[ix+1:])
1067 def refactor_for_py3(distdir, cy3_dir):
1068 # need to convert Cython sources first
1069 import lib2to3.refactor
1070 from distutils.util import copydir_run_2to3
1071 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
1072 if fix.split('fix_')[-1] not in ('next',)
1074 if not os.path.exists(cy3_dir):
1075 os.makedirs(cy3_dir)
1076 import distutils.log as dlog
1077 dlog.set_threshold(dlog.INFO)
1078 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1082 recursive-exclude Cython *
1083 recursive-include Cython *.py *.pyx *.pxd
1084 recursive-include Cython/Debugger/Tests *
1088 sys.path.insert(0, cy3_dir)
1090 for keep_2x_file in KEEP_2X_FILES:
1091 destfile = os.path.join(cy3_dir, keep_2x_file)
1092 shutil.copy(keep_2x_file, destfile)
1094 class PendingThreadsError(RuntimeError):
1099 def check_thread_termination(ignore_seen=True):
1100 if threading is None: # no threading enabled in CPython
1102 current = threading.currentThread()
1103 blocking_threads = []
1104 for t in threading.enumerate():
1105 if not t.isAlive() or t == current:
1110 blocking_threads.append(t)
1112 for seen in threads_seen:
1116 threads_seen.append(t)
1117 blocking_threads.append(t)
1118 if not blocking_threads:
1120 sys.stderr.write("warning: left-over threads found after running test:\n")
1121 for t in blocking_threads:
1122 sys.stderr.write('...%s\n' % repr(t))
1123 raise PendingThreadsError("left-over threads found after running test")
1127 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1129 from optparse import OptionParser
1130 parser = OptionParser()
1131 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1132 action="store_false", default=True,
1133 help="do not delete the generated C files (allows passing --no-cython on next run)")
1134 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1135 action="store_false", default=True,
1136 help="do not delete the generated shared libary files (allows manual module experimentation)")
1137 parser.add_option("--no-cython", dest="with_cython",
1138 action="store_false", default=True,
1139 help="do not run the Cython compiler, only the C compiler")
1140 parser.add_option("--compiler", dest="compiler", default=None,
1141 help="C compiler type")
1142 parser.add_option("--no-c", dest="use_c",
1143 action="store_false", default=True,
1144 help="do not test C compilation")
1145 parser.add_option("--no-cpp", dest="use_cpp",
1146 action="store_false", default=True,
1147 help="do not test C++ compilation")
1148 parser.add_option("--no-unit", dest="unittests",
1149 action="store_false", default=True,
1150 help="do not run the unit tests")
1151 parser.add_option("--no-doctest", dest="doctests",
1152 action="store_false", default=True,
1153 help="do not run the doctests")
1154 parser.add_option("--no-file", dest="filetests",
1155 action="store_false", default=True,
1156 help="do not run the file based tests")
1157 parser.add_option("--no-pyregr", dest="pyregr",
1158 action="store_false", default=True,
1159 help="do not run the regression tests of CPython in tests/pyregr/")
1160 parser.add_option("--cython-only", dest="cython_only",
1161 action="store_true", default=False,
1162 help="only compile pyx to c, do not run C compiler or run the tests")
1163 parser.add_option("--no-refnanny", dest="with_refnanny",
1164 action="store_false", default=True,
1165 help="do not regression test reference counting")
1166 parser.add_option("--no-fork", dest="fork",
1167 action="store_false", default=True,
1168 help="do not fork to run tests")
1169 parser.add_option("--sys-pyregr", dest="system_pyregr",
1170 action="store_true", default=False,
1171 help="run the regression tests of the CPython installation")
1172 parser.add_option("-x", "--exclude", dest="exclude",
1173 action="append", metavar="PATTERN",
1174 help="exclude tests matching the PATTERN")
1175 parser.add_option("-C", "--coverage", dest="coverage",
1176 action="store_true", default=False,
1177 help="collect source coverage data for the Compiler")
1178 parser.add_option("--coverage-xml", dest="coverage_xml",
1179 action="store_true", default=False,
1180 help="collect source coverage data for the Compiler in XML format")
1181 parser.add_option("-A", "--annotate", dest="annotate_source",
1182 action="store_true", default=True,
1183 help="generate annotated HTML versions of the test source files")
1184 parser.add_option("--no-annotate", dest="annotate_source",
1185 action="store_false",
1186 help="do not generate annotated HTML versions of the test source files")
1187 parser.add_option("-v", "--verbose", dest="verbosity",
1188 action="count", default=0,
1189 help="display test progress, pass twice to print test names")
1190 parser.add_option("-T", "--ticket", dest="tickets",
1192 help="a bug ticket number to run the respective test in 'tests/*'")
1193 parser.add_option("-3", dest="language_level",
1194 action="store_const", const=3, default=2,
1195 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1196 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1197 help="write test results in XML to directory DIR")
1198 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1199 action="store_true",
1200 help="exit without error code even on test failures")
1201 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1202 help="working directory")
1203 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1204 help="working directory")
1206 options, cmd_args = parser.parse_args()
1208 ROOTDIR = os.path.abspath(options.root_dir)
1209 WORKDIR = os.path.abspath(options.work_dir)
1211 if sys.version_info[0] >= 3:
1212 options.doctests = False
1213 if options.with_cython:
1215 # try if Cython is installed in a Py3 version
1216 import Cython.Compiler.Main
1218 # back out anything the import process loaded, then
1219 # 2to3 the Cython sources to make them re-importable
1220 cy_modules = [ name for name in sys.modules
1221 if name == 'Cython' or name.startswith('Cython.') ]
1222 for name in cy_modules:
1223 del sys.modules[name]
1224 # hasn't been refactored yet - do it now
1226 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1227 if sys.version_info >= (3,1):
1228 refactor_for_py3(DISTDIR, cy3_dir)
1229 elif os.path.isdir(cy3_dir):
1230 sys.path.insert(0, cy3_dir)
1232 options.with_cython = False
1234 WITH_CYTHON = options.with_cython
1236 if options.coverage or options.coverage_xml:
1238 options.coverage = options.coverage_xml = False
1240 from coverage import coverage as _coverage
1241 coverage = _coverage(branch=True)
1246 global CompilationOptions, pyrex_default_options, cython_compile
1247 from Cython.Compiler.Main import \
1248 CompilationOptions, \
1249 default_options as pyrex_default_options, \
1250 compile as cython_compile
1251 from Cython.Compiler import Errors
1252 Errors.LEVEL = 0 # show all warnings
1253 from Cython.Compiler import Options
1254 Options.generate_cleanup_code = 3 # complete cleanup code
1255 from Cython.Compiler import DebugFlags
1256 DebugFlags.debug_temp_code_comments = 1
1259 UNITTEST_MODULE = "Cython"
1260 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1262 if os.path.exists(WORKDIR):
1263 for path in os.listdir(WORKDIR):
1264 if path in ("support", "Cy3"): continue
1265 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1266 if not os.path.exists(WORKDIR):
1267 os.makedirs(WORKDIR)
1269 sys.stderr.write("Python %s\n" % sys.version)
1270 sys.stderr.write("\n")
1272 from Cython.Compiler.Version import version
1273 sys.stderr.write("Running tests against Cython %s\n" % version)
1275 sys.stderr.write("Running tests without Cython.\n")
1277 if options.with_refnanny:
1278 from pyximport.pyxbuild import pyx_to_dll
1279 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1281 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1282 sys.path.insert(0, os.path.split(libpath)[0])
1283 CFLAGS.append("-DCYTHON_REFNANNY=1")
1285 if options.xml_output_dir and options.fork:
1286 # doesn't currently work together
1287 sys.stderr.write("Disabling forked testing to support XML test output\n")
1288 options.fork = False
1290 if WITH_CYTHON and options.language_level == 3:
1291 sys.stderr.write("Using Cython language level 3.\n")
1293 sys.stderr.write("\n")
1297 for ticket_number in options.tickets:
1299 cmd_args.append('ticket:%s' % ticket_number)
1301 for selector in cmd_args:
1302 if selector.startswith('bugs'):
1306 selectors = [ string_selector(r) for r in cmd_args ]
1308 selectors = [ lambda x, tags=None: True ]
1310 # Chech which external modules are not present and exclude tests
1311 # which depends on them (by prefix)
1313 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1314 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1315 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1318 exclude_selectors += [ string_selector(r) for r in options.exclude ]
1321 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1323 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1324 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1327 if options.compiler:
1328 COMPILER = options.compiler
1331 languages.append('c')
1333 languages.append('cpp')
1335 test_suite = unittest.TestSuite()
1337 if options.unittests:
1338 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1340 if options.doctests:
1341 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1343 if options.filetests and languages:
1344 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1345 options.annotate_source, options.cleanup_workdir,
1346 options.cleanup_sharedlibs, options.pyregr,
1347 options.cython_only, languages, test_bugs,
1348 options.fork, options.language_level)
1349 test_suite.addTest(filetests.build_suite())
1351 if options.system_pyregr and languages:
1352 sys_pyregr_dir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test')
1353 if os.path.isdir(sys_pyregr_dir):
1354 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1355 options.annotate_source, options.cleanup_workdir,
1356 options.cleanup_sharedlibs, True,
1357 options.cython_only, languages, test_bugs,
1358 options.fork, sys.version_info[0])
1359 sys.stderr.write("Including CPython regression tests in %s\n" % sys_pyregr_dir)
1360 test_suite.addTest(filetests.handle_directory(sys_pyregr_dir, 'pyregr'))
1362 if options.xml_output_dir:
1363 from Cython.Tests.xmlrunner import XMLTestRunner
1364 test_runner = XMLTestRunner(output=options.xml_output_dir,
1365 verbose=options.verbosity > 0)
1367 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1369 result = test_runner.run(test_suite)
1371 if options.coverage or options.coverage_xml:
1373 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1374 modules = [ module for name, module in sys.modules.items()
1375 if module is not None and
1376 name.startswith('Cython.Compiler.') and
1377 name[len('Cython.Compiler.'):] not in ignored_modules ]
1378 if options.coverage:
1379 coverage.report(modules, show_missing=0)
1380 if options.coverage_xml:
1381 coverage.xml_report(modules, outfile="coverage-report.xml")
1383 if missing_dep_excluder.tests_missing_deps:
1384 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1385 for test in missing_dep_excluder.tests_missing_deps:
1386 sys.stderr.write(" %s\n" % test)
1388 if options.with_refnanny:
1390 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1397 return_code = not result.wasSuccessful()
1400 check_thread_termination(ignore_seen=False)
1401 sys.exit(return_code)
1402 except PendingThreadsError:
1403 # normal program exit won't kill the threads, do it the hard way here
1404 os._exit(return_code)
1406 if __name__ == '__main__':
1409 except SystemExit: # <= Py2.4 ...
1412 traceback.print_exc()
1414 check_thread_termination(ignore_seen=False)
1415 except PendingThreadsError:
1416 # normal program exit won't kill the threads, do it the hard way here