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 # The next line should start (3,); but this is a dictionary, so
105 # we can only have one (3,) key. Since 2.7 is supposed to be the
106 # last 2.x release, things would have to change drastically for this
108 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
109 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
110 'compile.extsetslice',
111 'compile.extdelslice',
112 'run.special_methods_T561_py2']),
115 # files that should not be converted to Python 3 code with 2to3
117 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
118 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
119 os.path.join('Cython', 'Debugger', 'libcython.py'),
120 os.path.join('Cython', 'Debugger', 'libpython.py'),
124 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
125 CFLAGS = os.getenv('CFLAGS', '').split()
128 uncomputed = object()
131 res = f._cache.get(args, uncomputed)
132 if res is uncomputed:
133 res = f._cache[args] = f(*args)
137 def parse_tags(filepath):
138 tags = defaultdict(list)
139 f = io_open(filepath, encoding='ISO-8859-1', errors='replace')
149 tag = line[1:ix].strip()
150 values = line[ix+1:].split(',')
151 tags[tag].extend([value.strip() for value in values])
156 parse_tags = memoize(parse_tags)
159 class build_ext(_build_ext):
160 def build_extension(self, ext):
161 if ext.language == 'c++':
163 try: # Py2.7+ & Py3.2+
164 compiler_obj = self.compiler_obj
165 except AttributeError:
166 compiler_obj = self.compiler
167 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
170 _build_ext.build_extension(self, ext)
172 class ErrorWriter(object):
173 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
176 self.write = self.output.append
178 def _collect(self, collect_errors, collect_warnings):
179 s = ''.join(self.output)
181 for line in s.split('\n'):
182 match = self.match_error(line)
184 is_warning, line, column, message = match.groups()
185 if (is_warning and collect_warnings) or \
186 (not is_warning and collect_errors):
187 result.append( (int(line), int(column), message.strip()) )
189 return [ "%d:%d: %s" % values for values in result ]
192 return self._collect(True, False)
194 def getwarnings(self):
195 return self._collect(False, True)
198 return self._collect(True, True)
200 class TestBuilder(object):
201 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
202 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
203 languages, test_bugs, fork, language_level):
204 self.rootdir = rootdir
205 self.workdir = workdir
206 self.selectors = selectors
207 self.exclude_selectors = exclude_selectors
208 self.annotate = annotate
209 self.cleanup_workdir = cleanup_workdir
210 self.cleanup_sharedlibs = cleanup_sharedlibs
211 self.with_pyregr = with_pyregr
212 self.cython_only = cython_only
213 self.languages = languages
214 self.test_bugs = test_bugs
216 self.language_level = language_level
218 def build_suite(self):
219 suite = unittest.TestSuite()
220 filenames = os.listdir(self.rootdir)
222 for filename in filenames:
223 path = os.path.join(self.rootdir, filename)
224 if os.path.isdir(path):
225 if filename == 'pyregr' and not self.with_pyregr:
227 if filename == 'broken' and not self.test_bugs:
230 self.handle_directory(path, filename))
231 if sys.platform not in ['win32']:
232 # Non-Windows makefile.
233 if [1 for selector in self.selectors if selector("embedded")] \
234 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
235 suite.addTest(unittest.makeSuite(EmbedTest))
238 def handle_directory(self, path, context):
239 workdir = os.path.join(self.workdir, context)
240 if not os.path.exists(workdir):
243 suite = unittest.TestSuite()
244 filenames = os.listdir(path)
246 for filename in filenames:
247 filepath = os.path.join(path, filename)
248 module, ext = os.path.splitext(filename)
249 if ext not in ('.py', '.pyx', '.srctree'):
251 if filename.startswith('.'):
252 continue # certain emacs backup files
253 tags = parse_tags(filepath)
254 fqmodule = "%s.%s" % (context, module)
255 if not [ 1 for match in self.selectors
256 if match(fqmodule, tags) ]:
258 if self.exclude_selectors:
259 if [1 for match in self.exclude_selectors
260 if match(fqmodule, tags)]:
263 mode = 'run' # default
265 mode = tags['mode'][0]
266 elif context == 'pyregr':
269 if ext == '.srctree':
270 suite.addTest(EndToEndTest(filepath, workdir, self.cleanup_workdir))
273 # Choose the test suite.
275 if not filename.startswith('test_'):
277 test_class = CythonPyregrTestCase
279 if module.startswith("test_"):
280 test_class = CythonUnitTestCase
282 test_class = CythonRunTestCase
284 test_class = CythonCompileTestCase
286 for test in self.build_tests(test_class, path, workdir,
287 module, mode == 'error', tags):
289 if mode == 'run' and ext == '.py':
290 # additionally test file in real Python
291 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
295 def build_tests(self, test_class, path, workdir, module, expect_errors, tags):
296 if 'werror' in tags['tags']:
297 warning_errors = True
299 warning_errors = False
302 if 'cpp' in tags['tag'] and 'cpp' in self.languages:
305 languages = self.languages[:1]
307 languages = self.languages
308 if 'cpp' in tags['tag'] and 'c' in languages:
309 languages = list(languages)
310 languages.remove('c')
311 tests = [ self.build_test(test_class, path, workdir, module,
312 language, expect_errors, warning_errors)
313 for language in languages ]
316 def build_test(self, test_class, path, workdir, module,
317 language, expect_errors, warning_errors):
318 workdir = os.path.join(workdir, language)
319 if not os.path.exists(workdir):
321 return test_class(path, workdir, module,
323 expect_errors=expect_errors,
324 annotate=self.annotate,
325 cleanup_workdir=self.cleanup_workdir,
326 cleanup_sharedlibs=self.cleanup_sharedlibs,
327 cython_only=self.cython_only,
329 language_level=self.language_level,
330 warning_errors=warning_errors)
332 class CythonCompileTestCase(unittest.TestCase):
333 def __init__(self, test_directory, workdir, module, language='c',
334 expect_errors=False, annotate=False, cleanup_workdir=True,
335 cleanup_sharedlibs=True, cython_only=False, fork=True,
336 language_level=2, warning_errors=False):
337 self.test_directory = test_directory
338 self.workdir = workdir
340 self.language = language
341 self.expect_errors = expect_errors
342 self.annotate = annotate
343 self.cleanup_workdir = cleanup_workdir
344 self.cleanup_sharedlibs = cleanup_sharedlibs
345 self.cython_only = cython_only
347 self.language_level = language_level
348 self.warning_errors = warning_errors
349 unittest.TestCase.__init__(self)
351 def shortDescription(self):
352 return "compiling (%s) %s" % (self.language, self.module)
355 from Cython.Compiler import Options
356 self._saved_options = [ (name, getattr(Options, name))
357 for name in ('warning_errors', 'error_on_unknown_names') ]
358 Options.warning_errors = self.warning_errors
360 if self.workdir not in sys.path:
361 sys.path.insert(0, self.workdir)
364 from Cython.Compiler import Options
365 for name, value in self._saved_options:
366 setattr(Options, name, value)
369 sys.path.remove(self.workdir)
373 del sys.modules[self.module]
376 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
377 cleanup_lib_files = self.cleanup_sharedlibs
378 if os.path.exists(self.workdir):
379 for rmfile in os.listdir(self.workdir):
380 if not cleanup_c_files:
381 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
383 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
385 if self.annotate and rmfile.endswith(".html"):
388 rmfile = os.path.join(self.workdir, rmfile)
389 if os.path.isdir(rmfile):
390 shutil.rmtree(rmfile, ignore_errors=True)
396 os.makedirs(self.workdir)
399 self.runCompileTest()
401 def runCompileTest(self):
402 self.compile(self.test_directory, self.module, self.workdir,
403 self.test_directory, self.expect_errors, self.annotate)
405 def find_module_source_file(self, source_file):
406 if not os.path.exists(source_file):
407 source_file = source_file[:-1]
410 def build_target_filename(self, module_name):
411 target = '%s.%s' % (module_name, self.language)
414 def copy_related_files(self, test_directory, target_directory, module_name):
415 is_related = re.compile('%s_.*[.].*' % module_name).match
416 for filename in os.listdir(test_directory):
417 if is_related(filename):
418 shutil.copy(os.path.join(test_directory, filename),
421 def find_source_files(self, workdir, module_name):
422 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
423 return [self.build_target_filename(module_name)] + [
424 filename for filename in os.listdir(workdir)
425 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
427 def split_source_and_output(self, test_directory, module, workdir):
428 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
429 source_and_output = io_open(source_file, 'rU', encoding='ISO-8859-1')
431 out = io_open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
432 'w', encoding='ISO-8859-1')
433 for line in source_and_output:
435 if line.startswith("_ERRORS"):
441 source_and_output.close()
443 geterrors = out.geterrors
444 except AttributeError:
450 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
451 extra_compile_options=None):
452 include_dirs = INCLUDE_DIRS[:]
454 include_dirs.append(incdir)
455 source = self.find_module_source_file(
456 os.path.join(test_directory, module + '.pyx'))
457 target = os.path.join(targetdir, self.build_target_filename(module))
459 if extra_compile_options is None:
460 extra_compile_options = {}
465 from Cython.Compiler.Main import CompilationOptions
466 from Cython.Compiler.Main import compile as cython_compile
467 from Cython.Compiler.Main import default_options
469 options = CompilationOptions(
471 include_path = include_dirs,
472 output_file = target,
474 use_listing_file = False,
475 cplus = self.language == 'cpp',
476 language_level = self.language_level,
477 generate_pxi = False,
478 evaluate_tree_assertions = True,
479 **extra_compile_options
481 cython_compile(source, options=options,
482 full_module_name=module)
484 def run_distutils(self, test_directory, module, workdir, incdir,
485 extra_extension_args=None):
489 build_extension = build_ext(distutils_distro)
490 build_extension.include_dirs = INCLUDE_DIRS[:]
492 build_extension.include_dirs.append(incdir)
493 build_extension.finalize_options()
495 build_extension.compiler = COMPILER
496 ext_include_dirs = []
497 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
499 ext_include_dirs += get_additional_include_dirs()
500 ext_compile_flags = CFLAGS[:]
501 if build_extension.compiler == 'mingw32':
502 ext_compile_flags.append('-Wno-format')
503 if extra_extension_args is None:
504 extra_extension_args = {}
506 self.copy_related_files(test_directory, workdir, module)
507 extension = Extension(
509 sources = self.find_source_files(workdir, module),
510 include_dirs = ext_include_dirs,
511 extra_compile_args = ext_compile_flags,
512 **extra_extension_args
514 if self.language == 'cpp':
515 extension.language = 'c++'
516 build_extension.extensions = [extension]
517 build_extension.build_temp = workdir
518 build_extension.build_lib = workdir
519 build_extension.run()
523 def compile(self, test_directory, module, workdir, incdir,
524 expect_errors, annotate):
525 expected_errors = errors = ()
527 expected_errors = self.split_source_and_output(
528 test_directory, module, workdir)
529 test_directory = workdir
532 old_stderr = sys.stderr
534 sys.stderr = ErrorWriter()
535 self.run_cython(test_directory, module, workdir, incdir, annotate)
536 errors = sys.stderr.geterrors()
538 sys.stderr = old_stderr
540 if errors or expected_errors:
542 for expected, error in zip(expected_errors, errors):
543 self.assertEquals(expected, error)
544 if len(errors) < len(expected_errors):
545 expected_error = expected_errors[len(errors)]
546 self.assertEquals(expected_error, None)
547 elif len(errors) > len(expected_errors):
548 unexpected_error = errors[len(expected_errors)]
549 self.assertEquals(None, unexpected_error)
550 except AssertionError:
551 print("\n=== Expected errors: ===")
552 print('\n'.join(expected_errors))
553 print("\n\n=== Got errors: ===")
554 print('\n'.join(errors))
558 if not self.cython_only:
559 self.run_distutils(test_directory, module, workdir, incdir)
561 class CythonRunTestCase(CythonCompileTestCase):
562 def shortDescription(self):
563 return "compiling (%s) and running %s" % (self.language, self.module)
565 def run(self, result=None):
567 result = self.defaultTestResult()
568 result.startTest(self)
572 self.runCompileTest()
573 self.run_tests(result)
575 check_thread_termination()
577 result.addError(self, sys.exc_info())
578 result.stopTest(self)
584 def run_tests(self, result):
585 if not self.cython_only:
586 self.run_doctests(self.module, result)
588 def run_doctests(self, module_name, result):
589 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
590 doctest.DocTestSuite(module_name).run(result)
594 # fork to make sure we do not keep the tested module loaded
595 result_handle, result_file = tempfile.mkstemp()
596 os.close(result_handle)
604 partial_result = PartialTestResult(result)
605 tests = doctest.DocTestSuite(module_name)
606 tests.run(partial_result)
610 # importing failed, try to fake a test class
612 failureException=sys.exc_info()[1],
613 _shortDescription=self.shortDescription(),
615 partial_result.addError(tests, sys.exc_info())
617 output = open(result_file, 'wb')
618 pickle.dump(partial_result.data(), output)
620 traceback.print_exc()
624 os._exit(result_code)
627 cid, result_code = os.waitpid(child_id, 0)
628 # os.waitpid returns the child's result code in the
629 # upper byte of result_code, and the signal it was
630 # killed by in the lower byte
631 if result_code & 255:
632 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
633 (module_name, result_code & 255))
634 result_code = result_code >> 8
635 if result_code in (0,1):
636 input = open(result_file, 'rb')
638 PartialTestResult.join_results(result, pickle.load(input))
642 raise Exception("Tests in module '%s' exited with status %d" %
643 (module_name, result_code))
645 try: os.unlink(result_file)
648 class PureDoctestTestCase(unittest.TestCase):
649 def __init__(self, module_name, module_path):
650 self.module_name = module_name
651 self.module_path = module_path
652 unittest.TestCase.__init__(self, 'run')
654 def shortDescription(self):
655 return "running pure doctests in %s" % self.module_name
657 def run(self, result=None):
659 result = self.defaultTestResult()
660 loaded_module_name = 'pure_doctest__' + self.module_name
661 result.startTest(self)
666 m = imp.load_source(loaded_module_name, self.module_path)
668 doctest.DocTestSuite(m).run(result)
671 if loaded_module_name in sys.modules:
672 del sys.modules[loaded_module_name]
673 check_thread_termination()
675 result.addError(self, sys.exc_info())
676 result.stopTest(self)
682 is_private_field = re.compile('^_[^_]').match
684 class _FakeClass(object):
685 def __init__(self, **kwargs):
686 self._shortDescription = kwargs.get('module_name')
687 self.__dict__.update(kwargs)
688 def shortDescription(self):
689 return self._shortDescription
691 try: # Py2.7+ and Py3.2+
692 from unittest.runner import _TextTestResult
694 from unittest import _TextTestResult
696 class PartialTestResult(_TextTestResult):
697 def __init__(self, base_result):
698 _TextTestResult.__init__(
699 self, self._StringIO(), True,
700 base_result.dots + base_result.showAll*2)
702 def strip_error_results(self, results):
703 for test_case, error in results:
704 for attr_name in filter(is_private_field, dir(test_case)):
705 if attr_name == '_dt_test':
706 test_case._dt_test = _FakeClass(
707 name=test_case._dt_test.name)
708 elif attr_name != '_shortDescription':
709 setattr(test_case, attr_name, None)
712 self.strip_error_results(self.failures)
713 self.strip_error_results(self.errors)
714 return (self.failures, self.errors, self.testsRun,
715 self.stream.getvalue())
717 def join_results(result, data):
718 """Static method for merging the result back into the main
721 failures, errors, tests_run, output = data
723 result.stream.write(output)
724 result.errors.extend(errors)
725 result.failures.extend(failures)
726 result.testsRun += tests_run
728 join_results = staticmethod(join_results)
730 class _StringIO(StringIO):
731 def writeln(self, line):
732 self.write("%s\n" % line)
735 class CythonUnitTestCase(CythonRunTestCase):
736 def shortDescription(self):
737 return "compiling (%s) tests in %s" % (self.language, self.module)
739 def run_tests(self, result):
740 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
743 class CythonPyregrTestCase(CythonRunTestCase):
745 CythonRunTestCase.setUp(self)
746 from Cython.Compiler import Options
747 Options.error_on_unknown_names = False
749 def _run_unittest(self, result, *classes):
750 """Run tests from unittest.TestCase-derived classes."""
751 valid_types = (unittest.TestSuite, unittest.TestCase)
752 suite = unittest.TestSuite()
754 if isinstance(cls, str):
755 if cls in sys.modules:
756 suite.addTest(unittest.findTestCases(sys.modules[cls]))
758 raise ValueError("str arguments must be keys in sys.modules")
759 elif isinstance(cls, valid_types):
762 suite.addTest(unittest.makeSuite(cls))
765 def _run_doctest(self, result, module):
766 self.run_doctests(module, result)
768 def run_tests(self, result):
770 from test import test_support as support
771 except ImportError: # Py3k
772 from test import support
774 def run_unittest(*classes):
775 return self._run_unittest(result, *classes)
776 def run_doctest(module, verbosity=None):
777 return self._run_doctest(result, module)
779 support.run_unittest = run_unittest
780 support.run_doctest = run_doctest
783 module = __import__(self.module)
784 if hasattr(module, 'test_main'):
786 except (unittest.SkipTest, support.ResourceDenied):
787 result.addSkip(self, 'ok')
789 include_debugger = sys.version_info[:2] > (2, 5)
791 def collect_unittests(path, module_prefix, suite, selectors):
792 def file_matches(filename):
793 return filename.startswith("Test") and filename.endswith(".py")
795 def package_matches(dirname):
796 return dirname == "Tests"
798 loader = unittest.TestLoader()
803 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
805 for dirpath, dirnames, filenames in os.walk(path):
806 if dirpath != path and "__init__.py" not in filenames:
807 skipped_dirs.append(dirpath + os.path.sep)
810 for dir in skipped_dirs:
811 if dirpath.startswith(dir):
815 parentname = os.path.split(dirpath)[-1]
816 if package_matches(parentname):
819 filepath = os.path.join(dirpath, f)[:-len(".py")]
820 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
821 if not [ 1 for match in selectors if match(modulename) ]:
823 module = __import__(modulename)
824 for x in modulename.split('.')[1:]:
825 module = getattr(module, x)
826 suite.addTests([loader.loadTestsFromModule(module)])
830 def collect_doctests(path, module_prefix, suite, selectors):
831 def package_matches(dirname):
832 if dirname == 'Debugger' and not include_debugger:
834 return dirname not in ("Mac", "Distutils", "Plex")
835 def file_matches(filename):
836 filename, ext = os.path.splitext(filename)
837 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
839 return (ext == '.py' and not
840 '~' in filename and not
841 '#' in filename and not
842 filename.startswith('.') and not
843 filename in blacklist)
844 import doctest, types
845 for dirpath, dirnames, filenames in os.walk(path):
846 for dir in list(dirnames):
847 if not package_matches(dir):
851 if not f.endswith('.py'): continue
852 filepath = os.path.join(dirpath, f)
853 if os.path.getsize(filepath) == 0: continue
854 filepath = filepath[:-len(".py")]
855 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
856 if not [ 1 for match in selectors if match(modulename) ]:
858 if 'in_gdb' in modulename:
859 # These should only be imported from gdb.
861 module = __import__(modulename)
862 for x in modulename.split('.')[1:]:
863 module = getattr(module, x)
864 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
866 suite.addTest(doctest.DocTestSuite(module))
867 except ValueError: # no tests
871 class EndToEndTest(unittest.TestCase):
873 This is a test of build/*.srctree files, where srctree defines a full
874 directory structure and its header gives a list of commands to run.
876 cython_root = os.path.dirname(os.path.abspath(__file__))
878 def __init__(self, treefile, workdir, cleanup_workdir=True):
879 self.name = os.path.splitext(os.path.basename(treefile))[0]
880 self.treefile = treefile
881 self.workdir = os.path.join(workdir, self.name)
882 self.cleanup_workdir = cleanup_workdir
883 cython_syspath = self.cython_root
884 for path in sys.path[::-1]:
885 if path.startswith(self.cython_root):
886 # Py3 installation and refnanny build prepend their
887 # fixed paths to sys.path => prefer that over the
889 cython_syspath = path + os.pathsep + cython_syspath
890 self.cython_syspath = cython_syspath
891 unittest.TestCase.__init__(self)
893 def shortDescription(self):
894 return "End-to-end %s" % self.name
897 from Cython.TestUtils import unpack_source_tree
898 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
899 self.old_dir = os.getcwd()
900 os.chdir(self.workdir)
901 if self.workdir not in sys.path:
902 sys.path.insert(0, self.workdir)
905 if self.cleanup_workdir:
906 for trial in range(5):
908 shutil.rmtree(self.workdir)
913 os.chdir(self.old_dir)
916 commands = (self.commands
917 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
918 .replace("PYTHON", sys.executable))
920 old_path = os.environ.get('PYTHONPATH')
921 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
922 for command in commands.split('\n'):
923 if sys.version_info[:2] >= (2,4):
925 p = subprocess.Popen(commands,
926 stderr=subprocess.PIPE,
927 stdout=subprocess.PIPE,
929 out, err = p.communicate()
936 res = os.system(command)
937 self.assertEqual(0, res, "non-zero exit status")
940 os.environ['PYTHONPATH'] = old_path
942 del os.environ['PYTHONPATH']
945 # TODO: Support cython_freeze needed here as well.
946 # TODO: Windows support.
948 class EmbedTest(unittest.TestCase):
950 working_dir = "Demos/embed"
953 self.old_dir = os.getcwd()
954 os.chdir(self.working_dir)
956 "make PYTHON='%s' clean > /dev/null" % sys.executable)
961 "make PYTHON='%s' clean > /dev/null" % sys.executable)
964 os.chdir(self.old_dir)
966 def test_embed(self):
967 from distutils import sysconfig
968 libname = sysconfig.get_config_var('LIBRARY')
969 libdir = sysconfig.get_config_var('LIBDIR')
970 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
971 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
972 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
973 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
974 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
975 # report the error for the original directory
976 libdir = sysconfig.get_config_var('LIBDIR')
978 if sys.version_info[0] >=3 and CY3_DIR:
979 cython = os.path.join(CY3_DIR, cython)
980 cython = os.path.abspath(os.path.join('..', '..', cython))
981 self.assert_(os.system(
982 "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
984 os.remove('make.output')
988 class MissingDependencyExcluder:
989 def __init__(self, deps):
990 # deps: { module name : matcher func }
991 self.exclude_matchers = []
992 for mod, matcher in deps.items():
996 self.exclude_matchers.append(string_selector(matcher))
997 self.tests_missing_deps = []
998 def __call__(self, testname, tags=None):
999 for matcher in self.exclude_matchers:
1000 if matcher(testname, tags):
1001 self.tests_missing_deps.append(testname)
1005 class VersionDependencyExcluder:
1006 def __init__(self, deps):
1007 # deps: { version : matcher func }
1008 from sys import version_info
1009 self.exclude_matchers = []
1010 for ver, (compare, matcher) in deps.items():
1011 if compare(version_info, ver):
1012 self.exclude_matchers.append(matcher)
1013 self.tests_missing_deps = []
1014 def __call__(self, testname, tags=None):
1015 for matcher in self.exclude_matchers:
1016 if matcher(testname):
1017 self.tests_missing_deps.append(testname)
1021 class FileListExcluder:
1023 def __init__(self, list_file):
1027 for line in f.readlines():
1029 if line and line[0] != '#':
1030 self.excludes[line.split()[0]] = True
1034 def __call__(self, testname, tags=None):
1035 return testname in self.excludes or testname.split('.')[-1] in self.excludes
1039 def __init__(self, tag, value):
1043 def __call__(self, testname, tags=None):
1047 return self.value in tags[self.tag]
1049 class RegExSelector:
1051 def __init__(self, pattern_string):
1052 self.pattern = re.compile(pattern_string, re.I|re.U)
1054 def __call__(self, testname, tags=None):
1055 return self.pattern.search(testname)
1057 def string_selector(s):
1060 return RegExSelector(s)
1062 return TagsSelector(s[:ix], s[ix+1:])
1065 def refactor_for_py3(distdir, cy3_dir):
1066 # need to convert Cython sources first
1067 import lib2to3.refactor
1068 from distutils.util import copydir_run_2to3
1069 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
1070 if fix.split('fix_')[-1] not in ('next',)
1072 if not os.path.exists(cy3_dir):
1073 os.makedirs(cy3_dir)
1074 import distutils.log as dlog
1075 dlog.set_threshold(dlog.INFO)
1076 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1080 recursive-exclude Cython *
1081 recursive-include Cython *.py *.pyx *.pxd
1082 recursive-include Cython/Debugger/Tests *
1086 sys.path.insert(0, cy3_dir)
1088 for keep_2x_file in KEEP_2X_FILES:
1089 destfile = os.path.join(cy3_dir, keep_2x_file)
1090 shutil.copy(keep_2x_file, destfile)
1092 class PendingThreadsError(RuntimeError):
1097 def check_thread_termination(ignore_seen=True):
1098 if threading is None: # no threading enabled in CPython
1100 current = threading.currentThread()
1101 blocking_threads = []
1102 for t in threading.enumerate():
1103 if not t.isAlive() or t == current:
1108 blocking_threads.append(t)
1110 for seen in threads_seen:
1114 threads_seen.append(t)
1115 blocking_threads.append(t)
1116 if not blocking_threads:
1118 sys.stderr.write("warning: left-over threads found after running test:\n")
1119 for t in blocking_threads:
1120 sys.stderr.write('...%s\n' % repr(t))
1121 raise PendingThreadsError("left-over threads found after running test")
1125 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1127 from optparse import OptionParser
1128 parser = OptionParser()
1129 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1130 action="store_false", default=True,
1131 help="do not delete the generated C files (allows passing --no-cython on next run)")
1132 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1133 action="store_false", default=True,
1134 help="do not delete the generated shared libary files (allows manual module experimentation)")
1135 parser.add_option("--no-cython", dest="with_cython",
1136 action="store_false", default=True,
1137 help="do not run the Cython compiler, only the C compiler")
1138 parser.add_option("--compiler", dest="compiler", default=None,
1139 help="C compiler type")
1140 parser.add_option("--no-c", dest="use_c",
1141 action="store_false", default=True,
1142 help="do not test C compilation")
1143 parser.add_option("--no-cpp", dest="use_cpp",
1144 action="store_false", default=True,
1145 help="do not test C++ compilation")
1146 parser.add_option("--no-unit", dest="unittests",
1147 action="store_false", default=True,
1148 help="do not run the unit tests")
1149 parser.add_option("--no-doctest", dest="doctests",
1150 action="store_false", default=True,
1151 help="do not run the doctests")
1152 parser.add_option("--no-file", dest="filetests",
1153 action="store_false", default=True,
1154 help="do not run the file based tests")
1155 parser.add_option("--no-pyregr", dest="pyregr",
1156 action="store_false", default=True,
1157 help="do not run the regression tests of CPython in tests/pyregr/")
1158 parser.add_option("--cython-only", dest="cython_only",
1159 action="store_true", default=False,
1160 help="only compile pyx to c, do not run C compiler or run the tests")
1161 parser.add_option("--no-refnanny", dest="with_refnanny",
1162 action="store_false", default=True,
1163 help="do not regression test reference counting")
1164 parser.add_option("--no-fork", dest="fork",
1165 action="store_false", default=True,
1166 help="do not fork to run tests")
1167 parser.add_option("--sys-pyregr", dest="system_pyregr",
1168 action="store_true", default=False,
1169 help="run the regression tests of the CPython installation")
1170 parser.add_option("-x", "--exclude", dest="exclude",
1171 action="append", metavar="PATTERN",
1172 help="exclude tests matching the PATTERN")
1173 parser.add_option("-C", "--coverage", dest="coverage",
1174 action="store_true", default=False,
1175 help="collect source coverage data for the Compiler")
1176 parser.add_option("--coverage-xml", dest="coverage_xml",
1177 action="store_true", default=False,
1178 help="collect source coverage data for the Compiler in XML format")
1179 parser.add_option("-A", "--annotate", dest="annotate_source",
1180 action="store_true", default=True,
1181 help="generate annotated HTML versions of the test source files")
1182 parser.add_option("--no-annotate", dest="annotate_source",
1183 action="store_false",
1184 help="do not generate annotated HTML versions of the test source files")
1185 parser.add_option("-v", "--verbose", dest="verbosity",
1186 action="count", default=0,
1187 help="display test progress, pass twice to print test names")
1188 parser.add_option("-T", "--ticket", dest="tickets",
1190 help="a bug ticket number to run the respective test in 'tests/*'")
1191 parser.add_option("-3", dest="language_level",
1192 action="store_const", const=3, default=2,
1193 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1194 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1195 help="write test results in XML to directory DIR")
1196 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1197 action="store_true",
1198 help="exit without error code even on test failures")
1199 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1200 help="working directory")
1201 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1202 help="working directory")
1204 options, cmd_args = parser.parse_args()
1206 ROOTDIR = os.path.abspath(options.root_dir)
1207 WORKDIR = os.path.abspath(options.work_dir)
1209 if sys.version_info[0] >= 3:
1210 options.doctests = False
1211 if options.with_cython:
1213 # try if Cython is installed in a Py3 version
1214 import Cython.Compiler.Main
1216 # back out anything the import process loaded, then
1217 # 2to3 the Cython sources to make them re-importable
1218 cy_modules = [ name for name in sys.modules
1219 if name == 'Cython' or name.startswith('Cython.') ]
1220 for name in cy_modules:
1221 del sys.modules[name]
1222 # hasn't been refactored yet - do it now
1224 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1225 if sys.version_info >= (3,1):
1226 refactor_for_py3(DISTDIR, cy3_dir)
1227 elif os.path.isdir(cy3_dir):
1228 sys.path.insert(0, cy3_dir)
1230 options.with_cython = False
1232 WITH_CYTHON = options.with_cython
1234 if options.coverage or options.coverage_xml:
1236 options.coverage = options.coverage_xml = False
1238 from coverage import coverage as _coverage
1239 coverage = _coverage(branch=True)
1244 global CompilationOptions, pyrex_default_options, cython_compile
1245 from Cython.Compiler.Main import \
1246 CompilationOptions, \
1247 default_options as pyrex_default_options, \
1248 compile as cython_compile
1249 from Cython.Compiler import Errors
1250 Errors.LEVEL = 0 # show all warnings
1251 from Cython.Compiler import Options
1252 Options.generate_cleanup_code = 3 # complete cleanup code
1253 from Cython.Compiler import DebugFlags
1254 DebugFlags.debug_temp_code_comments = 1
1257 UNITTEST_MODULE = "Cython"
1258 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1260 if os.path.exists(WORKDIR):
1261 for path in os.listdir(WORKDIR):
1262 if path in ("support", "Cy3"): continue
1263 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1264 if not os.path.exists(WORKDIR):
1265 os.makedirs(WORKDIR)
1267 sys.stderr.write("Python %s\n" % sys.version)
1268 sys.stderr.write("\n")
1270 from Cython.Compiler.Version import version
1271 sys.stderr.write("Running tests against Cython %s\n" % version)
1273 sys.stderr.write("Running tests without Cython.\n")
1275 if options.with_refnanny:
1276 from pyximport.pyxbuild import pyx_to_dll
1277 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1279 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1280 sys.path.insert(0, os.path.split(libpath)[0])
1281 CFLAGS.append("-DCYTHON_REFNANNY=1")
1283 if options.xml_output_dir and options.fork:
1284 # doesn't currently work together
1285 sys.stderr.write("Disabling forked testing to support XML test output\n")
1286 options.fork = False
1288 if WITH_CYTHON and options.language_level == 3:
1289 sys.stderr.write("Using Cython language level 3.\n")
1291 sys.stderr.write("\n")
1295 for ticket_number in options.tickets:
1297 cmd_args.append('ticket:%s' % ticket_number)
1299 for selector in cmd_args:
1300 if selector.startswith('bugs'):
1304 selectors = [ string_selector(r) for r in cmd_args ]
1306 selectors = [ lambda x, tags=None: True ]
1308 # Chech which external modules are not present and exclude tests
1309 # which depends on them (by prefix)
1311 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1312 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1313 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1316 exclude_selectors += [ string_selector(r) for r in options.exclude ]
1319 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1321 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1322 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1325 if options.compiler:
1326 COMPILER = options.compiler
1329 languages.append('c')
1331 languages.append('cpp')
1333 test_suite = unittest.TestSuite()
1335 if options.unittests:
1336 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1338 if options.doctests:
1339 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1341 if options.filetests and languages:
1342 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1343 options.annotate_source, options.cleanup_workdir,
1344 options.cleanup_sharedlibs, options.pyregr,
1345 options.cython_only, languages, test_bugs,
1346 options.fork, options.language_level)
1347 test_suite.addTest(filetests.build_suite())
1349 if options.system_pyregr and languages:
1350 sys_pyregr_dir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test')
1351 if os.path.isdir(sys_pyregr_dir):
1352 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1353 options.annotate_source, options.cleanup_workdir,
1354 options.cleanup_sharedlibs, True,
1355 options.cython_only, languages, test_bugs,
1356 options.fork, sys.version_info[0])
1357 sys.stderr.write("Including CPython regression tests in %s\n" % sys_pyregr_dir)
1358 test_suite.addTest(filetests.handle_directory(sys_pyregr_dir, 'pyregr'))
1360 if options.xml_output_dir:
1361 from Cython.Tests.xmlrunner import XMLTestRunner
1362 test_runner = XMLTestRunner(output=options.xml_output_dir,
1363 verbose=options.verbosity > 0)
1365 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1367 result = test_runner.run(test_suite)
1369 if options.coverage or options.coverage_xml:
1371 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1372 modules = [ module for name, module in sys.modules.items()
1373 if module is not None and
1374 name.startswith('Cython.Compiler.') and
1375 name[len('Cython.Compiler.'):] not in ignored_modules ]
1376 if options.coverage:
1377 coverage.report(modules, show_missing=0)
1378 if options.coverage_xml:
1379 coverage.xml_report(modules, outfile="coverage-report.xml")
1381 if missing_dep_excluder.tests_missing_deps:
1382 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1383 for test in missing_dep_excluder.tests_missing_deps:
1384 sys.stderr.write(" %s\n" % test)
1386 if options.with_refnanny:
1388 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1395 return_code = not result.wasSuccessful()
1398 check_thread_termination(ignore_seen=False)
1399 sys.exit(return_code)
1400 except PendingThreadsError:
1401 # normal program exit won't kill the threads, do it the hard way here
1402 os._exit(return_code)
1404 if __name__ == '__main__':
1407 except SystemExit: # <= Py2.4 ...
1410 traceback.print_exc()
1412 check_thread_termination(ignore_seen=False)
1413 except PendingThreadsError:
1414 # normal program exit won't kill the threads, do it the hard way here