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 Options.warning_errors = self.warning_errors
358 if self.workdir not in sys.path:
359 sys.path.insert(0, self.workdir)
362 from Cython.Compiler import Options
363 Options.warning_errors = False
366 sys.path.remove(self.workdir)
370 del sys.modules[self.module]
373 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
374 cleanup_lib_files = self.cleanup_sharedlibs
375 if os.path.exists(self.workdir):
376 for rmfile in os.listdir(self.workdir):
377 if not cleanup_c_files:
378 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
380 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
382 if self.annotate and rmfile.endswith(".html"):
385 rmfile = os.path.join(self.workdir, rmfile)
386 if os.path.isdir(rmfile):
387 shutil.rmtree(rmfile, ignore_errors=True)
393 os.makedirs(self.workdir)
396 self.runCompileTest()
398 def runCompileTest(self):
399 self.compile(self.test_directory, self.module, self.workdir,
400 self.test_directory, self.expect_errors, self.annotate)
402 def find_module_source_file(self, source_file):
403 if not os.path.exists(source_file):
404 source_file = source_file[:-1]
407 def build_target_filename(self, module_name):
408 target = '%s.%s' % (module_name, self.language)
411 def copy_related_files(self, test_directory, target_directory, module_name):
412 is_related = re.compile('%s_.*[.].*' % module_name).match
413 for filename in os.listdir(test_directory):
414 if is_related(filename):
415 shutil.copy(os.path.join(test_directory, filename),
418 def find_source_files(self, workdir, module_name):
419 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
420 return [self.build_target_filename(module_name)] + [
421 filename for filename in os.listdir(workdir)
422 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
424 def split_source_and_output(self, test_directory, module, workdir):
425 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
426 source_and_output = io_open(source_file, 'rU', encoding='ISO-8859-1')
428 out = io_open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
429 'w', encoding='ISO-8859-1')
430 for line in source_and_output:
432 if line.startswith("_ERRORS"):
438 source_and_output.close()
440 geterrors = out.geterrors
441 except AttributeError:
447 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
448 extra_compile_options=None):
449 include_dirs = INCLUDE_DIRS[:]
451 include_dirs.append(incdir)
452 source = self.find_module_source_file(
453 os.path.join(test_directory, module + '.pyx'))
454 target = os.path.join(targetdir, self.build_target_filename(module))
456 if extra_compile_options is None:
457 extra_compile_options = {}
462 from Cython.Compiler.Main import CompilationOptions
463 from Cython.Compiler.Main import compile as cython_compile
464 from Cython.Compiler.Main import default_options
466 options = CompilationOptions(
468 include_path = include_dirs,
469 output_file = target,
471 use_listing_file = False,
472 cplus = self.language == 'cpp',
473 language_level = self.language_level,
474 generate_pxi = False,
475 evaluate_tree_assertions = True,
476 **extra_compile_options
478 cython_compile(source, options=options,
479 full_module_name=module)
481 def run_distutils(self, test_directory, module, workdir, incdir,
482 extra_extension_args=None):
486 build_extension = build_ext(distutils_distro)
487 build_extension.include_dirs = INCLUDE_DIRS[:]
489 build_extension.include_dirs.append(incdir)
490 build_extension.finalize_options()
492 build_extension.compiler = COMPILER
493 ext_include_dirs = []
494 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
496 ext_include_dirs += get_additional_include_dirs()
497 ext_compile_flags = CFLAGS[:]
498 if build_extension.compiler == 'mingw32':
499 ext_compile_flags.append('-Wno-format')
500 if extra_extension_args is None:
501 extra_extension_args = {}
503 self.copy_related_files(test_directory, workdir, module)
504 extension = Extension(
506 sources = self.find_source_files(workdir, module),
507 include_dirs = ext_include_dirs,
508 extra_compile_args = ext_compile_flags,
509 **extra_extension_args
511 if self.language == 'cpp':
512 extension.language = 'c++'
513 build_extension.extensions = [extension]
514 build_extension.build_temp = workdir
515 build_extension.build_lib = workdir
516 build_extension.run()
520 def compile(self, test_directory, module, workdir, incdir,
521 expect_errors, annotate):
522 expected_errors = errors = ()
524 expected_errors = self.split_source_and_output(
525 test_directory, module, workdir)
526 test_directory = workdir
529 old_stderr = sys.stderr
531 sys.stderr = ErrorWriter()
532 self.run_cython(test_directory, module, workdir, incdir, annotate)
533 errors = sys.stderr.geterrors()
535 sys.stderr = old_stderr
537 if errors or expected_errors:
539 for expected, error in zip(expected_errors, errors):
540 self.assertEquals(expected, error)
541 if len(errors) < len(expected_errors):
542 expected_error = expected_errors[len(errors)]
543 self.assertEquals(expected_error, None)
544 elif len(errors) > len(expected_errors):
545 unexpected_error = errors[len(expected_errors)]
546 self.assertEquals(None, unexpected_error)
547 except AssertionError:
548 print("\n=== Expected errors: ===")
549 print('\n'.join(expected_errors))
550 print("\n\n=== Got errors: ===")
551 print('\n'.join(errors))
555 if not self.cython_only:
556 self.run_distutils(test_directory, module, workdir, incdir)
558 class CythonRunTestCase(CythonCompileTestCase):
559 def shortDescription(self):
560 return "compiling (%s) and running %s" % (self.language, self.module)
562 def run(self, result=None):
564 result = self.defaultTestResult()
565 result.startTest(self)
569 self.runCompileTest()
570 self.run_tests(result)
572 check_thread_termination()
574 result.addError(self, sys.exc_info())
575 result.stopTest(self)
581 def run_tests(self, result):
582 if not self.cython_only:
583 self.run_doctests(self.module, result)
585 def run_doctests(self, module_name, result):
586 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
587 doctest.DocTestSuite(module_name).run(result)
591 # fork to make sure we do not keep the tested module loaded
592 result_handle, result_file = tempfile.mkstemp()
593 os.close(result_handle)
601 partial_result = PartialTestResult(result)
602 tests = doctest.DocTestSuite(module_name)
603 tests.run(partial_result)
607 # importing failed, try to fake a test class
609 failureException=sys.exc_info()[1],
610 _shortDescription=self.shortDescription(),
612 partial_result.addError(tests, sys.exc_info())
614 output = open(result_file, 'wb')
615 pickle.dump(partial_result.data(), output)
617 traceback.print_exc()
621 os._exit(result_code)
624 cid, result_code = os.waitpid(child_id, 0)
625 # os.waitpid returns the child's result code in the
626 # upper byte of result_code, and the signal it was
627 # killed by in the lower byte
628 if result_code & 255:
629 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
630 (module_name, result_code & 255))
631 result_code = result_code >> 8
632 if result_code in (0,1):
633 input = open(result_file, 'rb')
635 PartialTestResult.join_results(result, pickle.load(input))
639 raise Exception("Tests in module '%s' exited with status %d" %
640 (module_name, result_code))
642 try: os.unlink(result_file)
645 class PureDoctestTestCase(unittest.TestCase):
646 def __init__(self, module_name, module_path):
647 self.module_name = module_name
648 self.module_path = module_path
649 unittest.TestCase.__init__(self, 'run')
651 def shortDescription(self):
652 return "running pure doctests in %s" % self.module_name
654 def run(self, result=None):
656 result = self.defaultTestResult()
657 loaded_module_name = 'pure_doctest__' + self.module_name
658 result.startTest(self)
663 m = imp.load_source(loaded_module_name, self.module_path)
665 doctest.DocTestSuite(m).run(result)
668 if loaded_module_name in sys.modules:
669 del sys.modules[loaded_module_name]
670 check_thread_termination()
672 result.addError(self, sys.exc_info())
673 result.stopTest(self)
679 is_private_field = re.compile('^_[^_]').match
681 class _FakeClass(object):
682 def __init__(self, **kwargs):
683 self._shortDescription = kwargs.get('module_name')
684 self.__dict__.update(kwargs)
685 def shortDescription(self):
686 return self._shortDescription
688 try: # Py2.7+ and Py3.2+
689 from unittest.runner import _TextTestResult
691 from unittest import _TextTestResult
693 class PartialTestResult(_TextTestResult):
694 def __init__(self, base_result):
695 _TextTestResult.__init__(
696 self, self._StringIO(), True,
697 base_result.dots + base_result.showAll*2)
699 def strip_error_results(self, results):
700 for test_case, error in results:
701 for attr_name in filter(is_private_field, dir(test_case)):
702 if attr_name == '_dt_test':
703 test_case._dt_test = _FakeClass(
704 name=test_case._dt_test.name)
705 elif attr_name != '_shortDescription':
706 setattr(test_case, attr_name, None)
709 self.strip_error_results(self.failures)
710 self.strip_error_results(self.errors)
711 return (self.failures, self.errors, self.testsRun,
712 self.stream.getvalue())
714 def join_results(result, data):
715 """Static method for merging the result back into the main
718 failures, errors, tests_run, output = data
720 result.stream.write(output)
721 result.errors.extend(errors)
722 result.failures.extend(failures)
723 result.testsRun += tests_run
725 join_results = staticmethod(join_results)
727 class _StringIO(StringIO):
728 def writeln(self, line):
729 self.write("%s\n" % line)
732 class CythonUnitTestCase(CythonRunTestCase):
733 def shortDescription(self):
734 return "compiling (%s) tests in %s" % (self.language, self.module)
736 def run_tests(self, result):
737 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
740 class CythonPyregrTestCase(CythonRunTestCase):
741 def _run_unittest(self, result, *classes):
742 """Run tests from unittest.TestCase-derived classes."""
743 valid_types = (unittest.TestSuite, unittest.TestCase)
744 suite = unittest.TestSuite()
746 if isinstance(cls, str):
747 if cls in sys.modules:
748 suite.addTest(unittest.findTestCases(sys.modules[cls]))
750 raise ValueError("str arguments must be keys in sys.modules")
751 elif isinstance(cls, valid_types):
754 suite.addTest(unittest.makeSuite(cls))
757 def _run_doctest(self, result, module):
758 self.run_doctests(module, result)
760 def run_tests(self, result):
762 from test import test_support as support
763 except ImportError: # Py3k
764 from test import support
766 def run_unittest(*classes):
767 return self._run_unittest(result, *classes)
768 def run_doctest(module, verbosity=None):
769 return self._run_doctest(result, module)
771 support.run_unittest = run_unittest
772 support.run_doctest = run_doctest
775 module = __import__(self.module)
776 if hasattr(module, 'test_main'):
778 except (unittest.SkipTest, support.ResourceDenied):
779 result.addSkip(self, 'ok')
781 include_debugger = sys.version_info[:2] > (2, 5)
783 def collect_unittests(path, module_prefix, suite, selectors):
784 def file_matches(filename):
785 return filename.startswith("Test") and filename.endswith(".py")
787 def package_matches(dirname):
788 return dirname == "Tests"
790 loader = unittest.TestLoader()
795 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
797 for dirpath, dirnames, filenames in os.walk(path):
798 if dirpath != path and "__init__.py" not in filenames:
799 skipped_dirs.append(dirpath + os.path.sep)
802 for dir in skipped_dirs:
803 if dirpath.startswith(dir):
807 parentname = os.path.split(dirpath)[-1]
808 if package_matches(parentname):
811 filepath = os.path.join(dirpath, f)[:-len(".py")]
812 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
813 if not [ 1 for match in selectors if match(modulename) ]:
815 module = __import__(modulename)
816 for x in modulename.split('.')[1:]:
817 module = getattr(module, x)
818 suite.addTests([loader.loadTestsFromModule(module)])
822 def collect_doctests(path, module_prefix, suite, selectors):
823 def package_matches(dirname):
824 if dirname == 'Debugger' and not include_debugger:
826 return dirname not in ("Mac", "Distutils", "Plex")
827 def file_matches(filename):
828 filename, ext = os.path.splitext(filename)
829 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
831 return (ext == '.py' and not
832 '~' in filename and not
833 '#' in filename and not
834 filename.startswith('.') and not
835 filename in blacklist)
836 import doctest, types
837 for dirpath, dirnames, filenames in os.walk(path):
838 for dir in list(dirnames):
839 if not package_matches(dir):
843 if not f.endswith('.py'): continue
844 filepath = os.path.join(dirpath, f)
845 if os.path.getsize(filepath) == 0: continue
846 filepath = filepath[:-len(".py")]
847 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
848 if not [ 1 for match in selectors if match(modulename) ]:
850 if 'in_gdb' in modulename:
851 # These should only be imported from gdb.
853 module = __import__(modulename)
854 for x in modulename.split('.')[1:]:
855 module = getattr(module, x)
856 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
858 suite.addTest(doctest.DocTestSuite(module))
859 except ValueError: # no tests
863 class EndToEndTest(unittest.TestCase):
865 This is a test of build/*.srctree files, where srctree defines a full
866 directory structure and its header gives a list of commands to run.
868 cython_root = os.path.dirname(os.path.abspath(__file__))
870 def __init__(self, treefile, workdir, cleanup_workdir=True):
871 self.name = os.path.splitext(os.path.basename(treefile))[0]
872 self.treefile = treefile
873 self.workdir = os.path.join(workdir, self.name)
874 self.cleanup_workdir = cleanup_workdir
875 cython_syspath = self.cython_root
876 for path in sys.path[::-1]:
877 if path.startswith(self.cython_root):
878 # Py3 installation and refnanny build prepend their
879 # fixed paths to sys.path => prefer that over the
881 cython_syspath = path + os.pathsep + cython_syspath
882 self.cython_syspath = cython_syspath
883 unittest.TestCase.__init__(self)
885 def shortDescription(self):
886 return "End-to-end %s" % self.name
889 from Cython.TestUtils import unpack_source_tree
890 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
891 self.old_dir = os.getcwd()
892 os.chdir(self.workdir)
893 if self.workdir not in sys.path:
894 sys.path.insert(0, self.workdir)
897 if self.cleanup_workdir:
898 for trial in range(5):
900 shutil.rmtree(self.workdir)
905 os.chdir(self.old_dir)
908 commands = (self.commands
909 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
910 .replace("PYTHON", sys.executable))
912 old_path = os.environ.get('PYTHONPATH')
913 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
914 for command in commands.split('\n'):
915 if sys.version_info[:2] >= (2,4):
917 p = subprocess.Popen(commands,
918 stderr=subprocess.PIPE,
919 stdout=subprocess.PIPE,
921 out, err = p.communicate()
928 res = os.system(command)
929 self.assertEqual(0, res, "non-zero exit status")
932 os.environ['PYTHONPATH'] = old_path
934 del os.environ['PYTHONPATH']
937 # TODO: Support cython_freeze needed here as well.
938 # TODO: Windows support.
940 class EmbedTest(unittest.TestCase):
942 working_dir = "Demos/embed"
945 self.old_dir = os.getcwd()
946 os.chdir(self.working_dir)
948 "make PYTHON='%s' clean > /dev/null" % sys.executable)
953 "make PYTHON='%s' clean > /dev/null" % sys.executable)
956 os.chdir(self.old_dir)
958 def test_embed(self):
959 from distutils import sysconfig
960 libname = sysconfig.get_config_var('LIBRARY')
961 libdir = sysconfig.get_config_var('LIBDIR')
962 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
963 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
964 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
965 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
966 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
967 # report the error for the original directory
968 libdir = sysconfig.get_config_var('LIBDIR')
970 if sys.version_info[0] >=3 and CY3_DIR:
971 cython = os.path.join(CY3_DIR, cython)
972 cython = os.path.abspath(os.path.join('..', '..', cython))
973 self.assert_(os.system(
974 "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
976 os.remove('make.output')
980 class MissingDependencyExcluder:
981 def __init__(self, deps):
982 # deps: { module name : matcher func }
983 self.exclude_matchers = []
984 for mod, matcher in deps.items():
988 self.exclude_matchers.append(string_selector(matcher))
989 self.tests_missing_deps = []
990 def __call__(self, testname, tags=None):
991 for matcher in self.exclude_matchers:
992 if matcher(testname, tags):
993 self.tests_missing_deps.append(testname)
997 class VersionDependencyExcluder:
998 def __init__(self, deps):
999 # deps: { version : matcher func }
1000 from sys import version_info
1001 self.exclude_matchers = []
1002 for ver, (compare, matcher) in deps.items():
1003 if compare(version_info, ver):
1004 self.exclude_matchers.append(matcher)
1005 self.tests_missing_deps = []
1006 def __call__(self, testname, tags=None):
1007 for matcher in self.exclude_matchers:
1008 if matcher(testname):
1009 self.tests_missing_deps.append(testname)
1013 class FileListExcluder:
1015 def __init__(self, list_file):
1019 for line in f.readlines():
1021 if line and line[0] != '#':
1022 self.excludes[line.split()[0]] = True
1026 def __call__(self, testname, tags=None):
1027 return testname in self.excludes or testname.split('.')[-1] in self.excludes
1031 def __init__(self, tag, value):
1035 def __call__(self, testname, tags=None):
1039 return self.value in tags[self.tag]
1041 class RegExSelector:
1043 def __init__(self, pattern_string):
1044 self.pattern = re.compile(pattern_string, re.I|re.U)
1046 def __call__(self, testname, tags=None):
1047 return self.pattern.search(testname)
1049 def string_selector(s):
1052 return RegExSelector(s)
1054 return TagsSelector(s[:ix], s[ix+1:])
1057 def refactor_for_py3(distdir, cy3_dir):
1058 # need to convert Cython sources first
1059 import lib2to3.refactor
1060 from distutils.util import copydir_run_2to3
1061 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
1062 if fix.split('fix_')[-1] not in ('next',)
1064 if not os.path.exists(cy3_dir):
1065 os.makedirs(cy3_dir)
1066 import distutils.log as dlog
1067 dlog.set_threshold(dlog.INFO)
1068 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1072 recursive-exclude Cython *
1073 recursive-include Cython *.py *.pyx *.pxd
1074 recursive-include Cython/Debugger/Tests *
1078 sys.path.insert(0, cy3_dir)
1080 for keep_2x_file in KEEP_2X_FILES:
1081 destfile = os.path.join(cy3_dir, keep_2x_file)
1082 shutil.copy(keep_2x_file, destfile)
1084 class PendingThreadsError(RuntimeError):
1089 def check_thread_termination(ignore_seen=True):
1090 if threading is None: # no threading enabled in CPython
1092 current = threading.currentThread()
1093 blocking_threads = []
1094 for t in threading.enumerate():
1095 if not t.isAlive() or t == current:
1100 blocking_threads.append(t)
1102 for seen in threads_seen:
1106 threads_seen.append(t)
1107 blocking_threads.append(t)
1108 if not blocking_threads:
1110 sys.stderr.write("warning: left-over threads found after running test:\n")
1111 for t in blocking_threads:
1112 sys.stderr.write('...%s\n' % repr(t))
1113 raise PendingThreadsError("left-over threads found after running test")
1117 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1119 from optparse import OptionParser
1120 parser = OptionParser()
1121 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1122 action="store_false", default=True,
1123 help="do not delete the generated C files (allows passing --no-cython on next run)")
1124 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1125 action="store_false", default=True,
1126 help="do not delete the generated shared libary files (allows manual module experimentation)")
1127 parser.add_option("--no-cython", dest="with_cython",
1128 action="store_false", default=True,
1129 help="do not run the Cython compiler, only the C compiler")
1130 parser.add_option("--compiler", dest="compiler", default=None,
1131 help="C compiler type")
1132 parser.add_option("--no-c", dest="use_c",
1133 action="store_false", default=True,
1134 help="do not test C compilation")
1135 parser.add_option("--no-cpp", dest="use_cpp",
1136 action="store_false", default=True,
1137 help="do not test C++ compilation")
1138 parser.add_option("--no-unit", dest="unittests",
1139 action="store_false", default=True,
1140 help="do not run the unit tests")
1141 parser.add_option("--no-doctest", dest="doctests",
1142 action="store_false", default=True,
1143 help="do not run the doctests")
1144 parser.add_option("--no-file", dest="filetests",
1145 action="store_false", default=True,
1146 help="do not run the file based tests")
1147 parser.add_option("--no-pyregr", dest="pyregr",
1148 action="store_false", default=True,
1149 help="do not run the regression tests of CPython in tests/pyregr/")
1150 parser.add_option("--cython-only", dest="cython_only",
1151 action="store_true", default=False,
1152 help="only compile pyx to c, do not run C compiler or run the tests")
1153 parser.add_option("--no-refnanny", dest="with_refnanny",
1154 action="store_false", default=True,
1155 help="do not regression test reference counting")
1156 parser.add_option("--no-fork", dest="fork",
1157 action="store_false", default=True,
1158 help="do not fork to run tests")
1159 parser.add_option("--sys-pyregr", dest="system_pyregr",
1160 action="store_true", default=False,
1161 help="run the regression tests of the CPython installation")
1162 parser.add_option("-x", "--exclude", dest="exclude",
1163 action="append", metavar="PATTERN",
1164 help="exclude tests matching the PATTERN")
1165 parser.add_option("-C", "--coverage", dest="coverage",
1166 action="store_true", default=False,
1167 help="collect source coverage data for the Compiler")
1168 parser.add_option("--coverage-xml", dest="coverage_xml",
1169 action="store_true", default=False,
1170 help="collect source coverage data for the Compiler in XML format")
1171 parser.add_option("-A", "--annotate", dest="annotate_source",
1172 action="store_true", default=True,
1173 help="generate annotated HTML versions of the test source files")
1174 parser.add_option("--no-annotate", dest="annotate_source",
1175 action="store_false",
1176 help="do not generate annotated HTML versions of the test source files")
1177 parser.add_option("-v", "--verbose", dest="verbosity",
1178 action="count", default=0,
1179 help="display test progress, pass twice to print test names")
1180 parser.add_option("-T", "--ticket", dest="tickets",
1182 help="a bug ticket number to run the respective test in 'tests/*'")
1183 parser.add_option("-3", dest="language_level",
1184 action="store_const", const=3, default=2,
1185 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1186 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1187 help="write test results in XML to directory DIR")
1188 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1189 action="store_true",
1190 help="exit without error code even on test failures")
1191 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1192 help="working directory")
1193 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1194 help="working directory")
1196 options, cmd_args = parser.parse_args()
1198 ROOTDIR = os.path.abspath(options.root_dir)
1199 WORKDIR = os.path.abspath(options.work_dir)
1201 if sys.version_info[0] >= 3:
1202 options.doctests = False
1203 if options.with_cython:
1205 # try if Cython is installed in a Py3 version
1206 import Cython.Compiler.Main
1208 # back out anything the import process loaded, then
1209 # 2to3 the Cython sources to make them re-importable
1210 cy_modules = [ name for name in sys.modules
1211 if name == 'Cython' or name.startswith('Cython.') ]
1212 for name in cy_modules:
1213 del sys.modules[name]
1214 # hasn't been refactored yet - do it now
1216 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1217 if sys.version_info >= (3,1):
1218 refactor_for_py3(DISTDIR, cy3_dir)
1219 elif os.path.isdir(cy3_dir):
1220 sys.path.insert(0, cy3_dir)
1222 options.with_cython = False
1224 WITH_CYTHON = options.with_cython
1226 if options.coverage or options.coverage_xml:
1228 options.coverage = options.coverage_xml = False
1230 from coverage import coverage as _coverage
1231 coverage = _coverage(branch=True)
1236 global CompilationOptions, pyrex_default_options, cython_compile
1237 from Cython.Compiler.Main import \
1238 CompilationOptions, \
1239 default_options as pyrex_default_options, \
1240 compile as cython_compile
1241 from Cython.Compiler import Errors
1242 Errors.LEVEL = 0 # show all warnings
1243 from Cython.Compiler import Options
1244 Options.generate_cleanup_code = 3 # complete cleanup code
1245 from Cython.Compiler import DebugFlags
1246 DebugFlags.debug_temp_code_comments = 1
1249 UNITTEST_MODULE = "Cython"
1250 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1252 if os.path.exists(WORKDIR):
1253 for path in os.listdir(WORKDIR):
1254 if path in ("support", "Cy3"): continue
1255 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1256 if not os.path.exists(WORKDIR):
1257 os.makedirs(WORKDIR)
1259 sys.stderr.write("Python %s\n" % sys.version)
1260 sys.stderr.write("\n")
1262 from Cython.Compiler.Version import version
1263 sys.stderr.write("Running tests against Cython %s\n" % version)
1265 sys.stderr.write("Running tests without Cython.\n")
1267 if options.with_refnanny:
1268 from pyximport.pyxbuild import pyx_to_dll
1269 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1271 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1272 sys.path.insert(0, os.path.split(libpath)[0])
1273 CFLAGS.append("-DCYTHON_REFNANNY=1")
1275 if options.xml_output_dir and options.fork:
1276 # doesn't currently work together
1277 sys.stderr.write("Disabling forked testing to support XML test output\n")
1278 options.fork = False
1280 if WITH_CYTHON and options.language_level == 3:
1281 sys.stderr.write("Using Cython language level 3.\n")
1283 sys.stderr.write("\n")
1287 for ticket_number in options.tickets:
1289 cmd_args.append('ticket:%s' % ticket_number)
1291 for selector in cmd_args:
1292 if selector.startswith('bugs'):
1296 selectors = [ string_selector(r) for r in cmd_args ]
1298 selectors = [ lambda x, tags=None: True ]
1300 # Chech which external modules are not present and exclude tests
1301 # which depends on them (by prefix)
1303 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1304 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1305 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1308 exclude_selectors += [ string_selector(r) for r in options.exclude ]
1311 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1313 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1314 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1317 if options.compiler:
1318 COMPILER = options.compiler
1321 languages.append('c')
1323 languages.append('cpp')
1325 test_suite = unittest.TestSuite()
1327 if options.unittests:
1328 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1330 if options.doctests:
1331 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1333 if options.filetests and languages:
1334 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1335 options.annotate_source, options.cleanup_workdir,
1336 options.cleanup_sharedlibs, options.pyregr,
1337 options.cython_only, languages, test_bugs,
1338 options.fork, options.language_level)
1339 test_suite.addTest(filetests.build_suite())
1341 if options.system_pyregr and languages:
1342 sys_pyregr_dir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test')
1343 if os.path.isdir(sys_pyregr_dir):
1344 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1345 options.annotate_source, options.cleanup_workdir,
1346 options.cleanup_sharedlibs, True,
1347 options.cython_only, languages, test_bugs,
1348 options.fork, options.language_level)
1349 sys.stderr.write("Including CPython regression tests in %s\n" % sys_pyregr_dir)
1350 test_suite.addTest(filetests.handle_directory(sys_pyregr_dir, 'pyregr'))
1352 if options.xml_output_dir:
1353 from Cython.Tests.xmlrunner import XMLTestRunner
1354 test_runner = XMLTestRunner(output=options.xml_output_dir,
1355 verbose=options.verbosity > 0)
1357 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1359 result = test_runner.run(test_suite)
1361 if options.coverage or options.coverage_xml:
1363 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1364 modules = [ module for name, module in sys.modules.items()
1365 if module is not None and
1366 name.startswith('Cython.Compiler.') and
1367 name[len('Cython.Compiler.'):] not in ignored_modules ]
1368 if options.coverage:
1369 coverage.report(modules, show_missing=0)
1370 if options.coverage_xml:
1371 coverage.xml_report(modules, outfile="coverage-report.xml")
1373 if missing_dep_excluder.tests_missing_deps:
1374 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1375 for test in missing_dep_excluder.tests_missing_deps:
1376 sys.stderr.write(" %s\n" % test)
1378 if options.with_refnanny:
1380 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1387 return_code = not result.wasSuccessful()
1390 check_thread_termination(ignore_seen=False)
1391 sys.exit(return_code)
1392 except PendingThreadsError:
1393 # normal program exit won't kill the threads, do it the hard way here
1394 os._exit(return_code)
1396 if __name__ == '__main__':
1399 except SystemExit: # <= Py2.4 ...
1402 traceback.print_exc()
1404 check_thread_termination(ignore_seen=False)
1405 except PendingThreadsError:
1406 # normal program exit won't kill the threads, do it the hard way here