16 from StringIO import StringIO
18 from io import StringIO
21 import cPickle as pickle
27 except ImportError: # No threads, no problems
32 from distutils.dist import Distribution
33 from distutils.core import Extension
34 from distutils.command.build_ext import build_ext as _build_ext
35 distutils_distro = Distribution()
37 if sys.platform == 'win32':
38 # TODO: Figure out why this hackery (see http://thread.gmane.org/gmane.comp.python.cython.devel/8280/).
39 config_files = distutils_distro.find_config_files()
40 try: config_files.remove('setup.cfg')
41 except ValueError: pass
42 distutils_distro.parse_config_files(config_files)
44 cfgfiles = distutils_distro.find_config_files()
45 try: cfgfiles.remove('setup.cfg')
46 except ValueError: pass
47 distutils_distro.parse_config_files(cfgfiles)
49 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr', 'build']
50 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
52 # Lists external modules, and a matcher matching tests
53 # which should be excluded if the module is not present.
55 'numpy' : re.compile('.*\.numpy_.*').match,
56 'pstats' : re.compile('.*\.pstats_.*').match,
57 'posix' : re.compile('.*\.posix_.*').match,
60 def get_numpy_include_dirs():
62 return [numpy.get_include()]
65 # test name matcher , callable returning list
66 (re.compile('numpy_.*').match, get_numpy_include_dirs),
70 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
71 # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
72 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
75 (2,5) : (operator.lt, lambda x: x in ['run.any',
78 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
80 'run.pure_py', # decorators, with statement
82 # The next line should start (3,); but this is a dictionary, so
83 # we can only have one (3,) key. Since 2.7 is supposed to be the
84 # last 2.x release, things would have to change drastically for this
86 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
87 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
88 'compile.extsetslice',
89 'compile.extdelslice',
90 'run.special_methods_T561_py2']),
93 # files that should not be converted to Python 3 code with 2to3
95 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
96 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
97 os.path.join('Cython', 'Debugger', 'libcython.py'),
98 os.path.join('Cython', 'Debugger', 'libpython.py'),
102 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
103 CFLAGS = os.getenv('CFLAGS', '').split()
105 class build_ext(_build_ext):
106 def build_extension(self, ext):
107 if ext.language == 'c++':
109 try: # Py2.7+ & Py3.2+
110 compiler_obj = self.compiler_obj
111 except AttributeError:
112 compiler_obj = self.compiler
113 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
116 _build_ext.build_extension(self, ext)
118 class ErrorWriter(object):
119 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
122 self.write = self.output.append
124 def _collect(self, collect_errors, collect_warnings):
125 s = ''.join(self.output)
127 for line in s.split('\n'):
128 match = self.match_error(line)
130 is_warning, line, column, message = match.groups()
131 if (is_warning and collect_warnings) or \
132 (not is_warning and collect_errors):
133 result.append( (int(line), int(column), message.strip()) )
135 return [ "%d:%d: %s" % values for values in result ]
138 return self._collect(True, False)
140 def getwarnings(self):
141 return self._collect(False, True)
144 return self._collect(True, True)
146 class TestBuilder(object):
147 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
148 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
149 languages, test_bugs, fork, language_level):
150 self.rootdir = rootdir
151 self.workdir = workdir
152 self.selectors = selectors
153 self.exclude_selectors = exclude_selectors
154 self.annotate = annotate
155 self.cleanup_workdir = cleanup_workdir
156 self.cleanup_sharedlibs = cleanup_sharedlibs
157 self.with_pyregr = with_pyregr
158 self.cython_only = cython_only
159 self.languages = languages
160 self.test_bugs = test_bugs
162 self.language_level = language_level
164 def build_suite(self):
165 suite = unittest.TestSuite()
166 test_dirs = TEST_DIRS
167 filenames = os.listdir(self.rootdir)
169 for filename in filenames:
170 if not WITH_CYTHON and filename == "errors":
171 # we won't get any errors without running Cython
173 path = os.path.join(self.rootdir, filename)
174 if os.path.isdir(path) and filename in test_dirs:
175 if filename == 'pyregr' and not self.with_pyregr:
178 self.handle_directory(path, filename))
179 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
180 # Non-Windows makefile, can't run Cython under Py3.
181 if [1 for selector in self.selectors if selector("embedded")] \
182 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
183 suite.addTest(unittest.makeSuite(EmbedTest))
186 def handle_directory(self, path, context):
187 workdir = os.path.join(self.workdir, context)
188 if not os.path.exists(workdir):
191 expect_errors = (context == 'errors')
192 suite = unittest.TestSuite()
193 filenames = os.listdir(path)
195 for filename in filenames:
196 if context == "build" and filename.endswith(".srctree"):
197 if not [ 1 for match in self.selectors if match(filename) ]:
199 if self.exclude_selectors:
200 if [1 for match in self.exclude_selectors if match(filename)]:
202 suite.addTest(EndToEndTest(os.path.join(path, filename), workdir, self.cleanup_workdir))
204 if not (filename.endswith(".pyx") or filename.endswith(".py")):
206 if filename.startswith('.'): continue # certain emacs backup files
207 if context == 'pyregr' and not filename.startswith('test_'):
209 module = os.path.splitext(filename)[0]
210 fqmodule = "%s.%s" % (context, module)
211 if not [ 1 for match in self.selectors
212 if match(fqmodule) ]:
214 if self.exclude_selectors:
215 if [1 for match in self.exclude_selectors if match(fqmodule)]:
217 if context == 'pyregr':
218 test_class = CythonPyregrTestCase
219 elif context in TEST_RUN_DIRS:
220 if module.startswith("test_"):
221 test_class = CythonUnitTestCase
223 test_class = CythonRunTestCase
225 test_class = CythonCompileTestCase
226 for test in self.build_tests(test_class, path, workdir,
227 module, expect_errors):
229 if context == 'run' and filename.endswith('.py'):
230 # additionally test file in real Python
231 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
234 def build_tests(self, test_class, path, workdir, module, expect_errors):
236 if 'cpp' in module and 'cpp' in self.languages:
239 languages = self.languages[:1]
241 languages = self.languages
242 if 'cpp' in module and 'c' in languages:
243 languages = list(languages)
244 languages.remove('c')
245 tests = [ self.build_test(test_class, path, workdir, module,
246 language, expect_errors)
247 for language in languages ]
250 def build_test(self, test_class, path, workdir, module,
251 language, expect_errors):
252 workdir = os.path.join(workdir, language)
253 if not os.path.exists(workdir):
255 return test_class(path, workdir, module,
257 expect_errors=expect_errors,
258 annotate=self.annotate,
259 cleanup_workdir=self.cleanup_workdir,
260 cleanup_sharedlibs=self.cleanup_sharedlibs,
261 cython_only=self.cython_only,
263 language_level=self.language_level)
265 class CythonCompileTestCase(unittest.TestCase):
266 def __init__(self, test_directory, workdir, module, language='c',
267 expect_errors=False, annotate=False, cleanup_workdir=True,
268 cleanup_sharedlibs=True, cython_only=False, fork=True,
270 self.test_directory = test_directory
271 self.workdir = workdir
273 self.language = language
274 self.expect_errors = expect_errors
275 self.annotate = annotate
276 self.cleanup_workdir = cleanup_workdir
277 self.cleanup_sharedlibs = cleanup_sharedlibs
278 self.cython_only = cython_only
280 self.language_level = language_level
281 unittest.TestCase.__init__(self)
283 def shortDescription(self):
284 return "compiling (%s) %s" % (self.language, self.module)
287 if self.workdir not in sys.path:
288 sys.path.insert(0, self.workdir)
292 sys.path.remove(self.workdir)
296 del sys.modules[self.module]
299 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
300 cleanup_lib_files = self.cleanup_sharedlibs
301 if os.path.exists(self.workdir):
302 for rmfile in os.listdir(self.workdir):
303 if not cleanup_c_files:
304 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
306 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
308 if self.annotate and rmfile.endswith(".html"):
311 rmfile = os.path.join(self.workdir, rmfile)
312 if os.path.isdir(rmfile):
313 shutil.rmtree(rmfile, ignore_errors=True)
319 os.makedirs(self.workdir)
322 self.runCompileTest()
324 def runCompileTest(self):
325 self.compile(self.test_directory, self.module, self.workdir,
326 self.test_directory, self.expect_errors, self.annotate)
328 def find_module_source_file(self, source_file):
329 if not os.path.exists(source_file):
330 source_file = source_file[:-1]
333 def build_target_filename(self, module_name):
334 target = '%s.%s' % (module_name, self.language)
337 def copy_related_files(self, test_directory, target_directory, module_name):
338 is_related = re.compile('%s_.*[.].*' % module_name).match
339 for filename in os.listdir(test_directory):
340 if is_related(filename):
341 shutil.copy(os.path.join(test_directory, filename),
344 def find_source_files(self, workdir, module_name):
345 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
346 return [self.build_target_filename(module_name)] + [
347 filename for filename in os.listdir(workdir)
348 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
350 def split_source_and_output(self, test_directory, module, workdir):
351 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
352 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
354 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
356 for line in source_and_output:
358 if line.startswith("_ERRORS"):
364 source_and_output.close()
366 geterrors = out.geterrors
367 except AttributeError:
373 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
374 extra_compile_options=None):
375 include_dirs = INCLUDE_DIRS[:]
377 include_dirs.append(incdir)
378 source = self.find_module_source_file(
379 os.path.join(test_directory, module + '.pyx'))
380 target = os.path.join(targetdir, self.build_target_filename(module))
382 if extra_compile_options is None:
383 extra_compile_options = {}
388 from Cython.Compiler.Main import CompilationOptions
389 from Cython.Compiler.Main import compile as cython_compile
390 from Cython.Compiler.Main import default_options
392 options = CompilationOptions(
394 include_path = include_dirs,
395 output_file = target,
397 use_listing_file = False,
398 cplus = self.language == 'cpp',
399 language_level = self.language_level,
400 generate_pxi = False,
401 evaluate_tree_assertions = True,
402 **extra_compile_options
404 cython_compile(source, options=options,
405 full_module_name=module)
407 def run_distutils(self, test_directory, module, workdir, incdir,
408 extra_extension_args=None):
412 build_extension = build_ext(distutils_distro)
413 build_extension.include_dirs = INCLUDE_DIRS[:]
415 build_extension.include_dirs.append(incdir)
416 build_extension.finalize_options()
418 build_extension.compiler = COMPILER
419 ext_include_dirs = []
420 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
422 ext_include_dirs += get_additional_include_dirs()
423 self.copy_related_files(test_directory, workdir, module)
425 if extra_extension_args is None:
426 extra_extension_args = {}
428 extension = Extension(
430 sources = self.find_source_files(workdir, module),
431 include_dirs = ext_include_dirs,
432 extra_compile_args = CFLAGS,
433 **extra_extension_args
435 if self.language == 'cpp':
436 extension.language = 'c++'
437 build_extension.extensions = [extension]
438 build_extension.build_temp = workdir
439 build_extension.build_lib = workdir
440 build_extension.run()
444 def compile(self, test_directory, module, workdir, incdir,
445 expect_errors, annotate):
446 expected_errors = errors = ()
448 expected_errors = self.split_source_and_output(
449 test_directory, module, workdir)
450 test_directory = workdir
453 old_stderr = sys.stderr
455 sys.stderr = ErrorWriter()
456 self.run_cython(test_directory, module, workdir, incdir, annotate)
457 errors = sys.stderr.geterrors()
459 sys.stderr = old_stderr
461 if errors or expected_errors:
463 for expected, error in zip(expected_errors, errors):
464 self.assertEquals(expected, error)
465 if len(errors) < len(expected_errors):
466 expected_error = expected_errors[len(errors)]
467 self.assertEquals(expected_error, None)
468 elif len(errors) > len(expected_errors):
469 unexpected_error = errors[len(expected_errors)]
470 self.assertEquals(None, unexpected_error)
471 except AssertionError:
472 print("\n=== Expected errors: ===")
473 print('\n'.join(expected_errors))
474 print("\n\n=== Got errors: ===")
475 print('\n'.join(errors))
479 if not self.cython_only:
480 self.run_distutils(test_directory, module, workdir, incdir)
482 class CythonRunTestCase(CythonCompileTestCase):
483 def shortDescription(self):
484 return "compiling (%s) and running %s" % (self.language, self.module)
486 def run(self, result=None):
488 result = self.defaultTestResult()
489 result.startTest(self)
493 self.runCompileTest()
494 self.run_tests(result)
496 check_thread_termination()
498 result.addError(self, sys.exc_info())
499 result.stopTest(self)
505 def run_tests(self, result):
506 if not self.cython_only:
507 self.run_doctests(self.module, result)
509 def run_doctests(self, module_name, result):
510 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
511 doctest.DocTestSuite(module_name).run(result)
515 # fork to make sure we do not keep the tested module loaded
516 result_handle, result_file = tempfile.mkstemp()
517 os.close(result_handle)
525 partial_result = PartialTestResult(result)
526 tests = doctest.DocTestSuite(module_name)
527 tests.run(partial_result)
531 # importing failed, try to fake a test class
533 failureException=sys.exc_info()[1],
534 _shortDescription=self.shortDescription(),
536 partial_result.addError(tests, sys.exc_info())
538 output = open(result_file, 'wb')
539 pickle.dump(partial_result.data(), output)
541 traceback.print_exc()
545 os._exit(result_code)
548 cid, result_code = os.waitpid(child_id, 0)
549 # os.waitpid returns the child's result code in the
550 # upper byte of result_code, and the signal it was
551 # killed by in the lower byte
552 if result_code & 255:
553 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
554 (module_name, result_code & 255))
555 result_code = result_code >> 8
556 if result_code in (0,1):
557 input = open(result_file, 'rb')
559 PartialTestResult.join_results(result, pickle.load(input))
563 raise Exception("Tests in module '%s' exited with status %d" %
564 (module_name, result_code))
566 try: os.unlink(result_file)
569 class PureDoctestTestCase(unittest.TestCase):
570 def __init__(self, module_name, module_path):
571 self.module_name = module_name
572 self.module_path = module_path
573 unittest.TestCase.__init__(self, 'run')
575 def shortDescription(self):
576 return "running pure doctests in %s" % self.module_name
578 def run(self, result=None):
580 result = self.defaultTestResult()
581 loaded_module_name = 'pure_doctest__' + self.module_name
582 result.startTest(self)
587 m = imp.load_source(loaded_module_name, self.module_path)
589 doctest.DocTestSuite(m).run(result)
592 if loaded_module_name in sys.modules:
593 del sys.modules[loaded_module_name]
594 check_thread_termination()
596 result.addError(self, sys.exc_info())
597 result.stopTest(self)
603 is_private_field = re.compile('^_[^_]').match
605 class _FakeClass(object):
606 def __init__(self, **kwargs):
607 self._shortDescription = kwargs.get('module_name')
608 self.__dict__.update(kwargs)
609 def shortDescription(self):
610 return self._shortDescription
612 try: # Py2.7+ and Py3.2+
613 from unittest.runner import _TextTestResult
615 from unittest import _TextTestResult
617 class PartialTestResult(_TextTestResult):
618 def __init__(self, base_result):
619 _TextTestResult.__init__(
620 self, self._StringIO(), True,
621 base_result.dots + base_result.showAll*2)
623 def strip_error_results(self, results):
624 for test_case, error in results:
625 for attr_name in filter(is_private_field, dir(test_case)):
626 if attr_name == '_dt_test':
627 test_case._dt_test = _FakeClass(
628 name=test_case._dt_test.name)
629 elif attr_name != '_shortDescription':
630 setattr(test_case, attr_name, None)
633 self.strip_error_results(self.failures)
634 self.strip_error_results(self.errors)
635 return (self.failures, self.errors, self.testsRun,
636 self.stream.getvalue())
638 def join_results(result, data):
639 """Static method for merging the result back into the main
642 failures, errors, tests_run, output = data
644 result.stream.write(output)
645 result.errors.extend(errors)
646 result.failures.extend(failures)
647 result.testsRun += tests_run
649 join_results = staticmethod(join_results)
651 class _StringIO(StringIO):
652 def writeln(self, line):
653 self.write("%s\n" % line)
656 class CythonUnitTestCase(CythonRunTestCase):
657 def shortDescription(self):
658 return "compiling (%s) tests in %s" % (self.language, self.module)
660 def run_tests(self, result):
661 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
664 class CythonPyregrTestCase(CythonRunTestCase):
665 def _run_unittest(self, result, *classes):
666 """Run tests from unittest.TestCase-derived classes."""
667 valid_types = (unittest.TestSuite, unittest.TestCase)
668 suite = unittest.TestSuite()
670 if isinstance(cls, str):
671 if cls in sys.modules:
672 suite.addTest(unittest.findTestCases(sys.modules[cls]))
674 raise ValueError("str arguments must be keys in sys.modules")
675 elif isinstance(cls, valid_types):
678 suite.addTest(unittest.makeSuite(cls))
681 def _run_doctest(self, result, module):
682 self.run_doctests(module, result)
684 def run_tests(self, result):
686 from test import test_support as support
687 except ImportError: # Py3k
688 from test import support
690 def run_unittest(*classes):
691 return self._run_unittest(result, *classes)
692 def run_doctest(module, verbosity=None):
693 return self._run_doctest(result, module)
695 support.run_unittest = run_unittest
696 support.run_doctest = run_doctest
699 module = __import__(self.module)
700 if hasattr(module, 'test_main'):
702 except (unittest.SkipTest, support.ResourceDenied):
703 result.addSkip(self, 'ok')
705 include_debugger = sys.version_info[:2] > (2, 5)
707 def collect_unittests(path, module_prefix, suite, selectors):
708 def file_matches(filename):
709 return filename.startswith("Test") and filename.endswith(".py")
711 def package_matches(dirname):
712 return dirname == "Tests"
714 loader = unittest.TestLoader()
719 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
721 for dirpath, dirnames, filenames in os.walk(path):
722 if dirpath != path and "__init__.py" not in filenames:
723 skipped_dirs.append(dirpath + os.path.sep)
726 for dir in skipped_dirs:
727 if dirpath.startswith(dir):
731 parentname = os.path.split(dirpath)[-1]
732 if package_matches(parentname):
735 filepath = os.path.join(dirpath, f)[:-len(".py")]
736 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
737 if not [ 1 for match in selectors if match(modulename) ]:
739 module = __import__(modulename)
740 for x in modulename.split('.')[1:]:
741 module = getattr(module, x)
742 suite.addTests([loader.loadTestsFromModule(module)])
746 def collect_doctests(path, module_prefix, suite, selectors):
747 def package_matches(dirname):
748 if dirname == 'Debugger' and not include_debugger:
750 return dirname not in ("Mac", "Distutils", "Plex")
751 def file_matches(filename):
752 filename, ext = os.path.splitext(filename)
753 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
755 return (ext == '.py' and not
756 '~' in filename and not
757 '#' in filename and not
758 filename.startswith('.') and not
759 filename in blacklist)
760 import doctest, types
761 for dirpath, dirnames, filenames in os.walk(path):
762 for dir in list(dirnames):
763 if not package_matches(dir):
767 if not f.endswith('.py'): continue
768 filepath = os.path.join(dirpath, f)
769 if os.path.getsize(filepath) == 0: continue
770 filepath = filepath[:-len(".py")]
771 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
772 if not [ 1 for match in selectors if match(modulename) ]:
774 if 'in_gdb' in modulename:
775 # These should only be imported from gdb.
777 module = __import__(modulename)
778 for x in modulename.split('.')[1:]:
779 module = getattr(module, x)
780 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
782 suite.addTest(doctest.DocTestSuite(module))
783 except ValueError: # no tests
787 class EndToEndTest(unittest.TestCase):
789 This is a test of build/*.srctree files, where srctree defines a full
790 directory structure and its header gives a list of commands to run.
792 cython_root = os.path.dirname(os.path.abspath(__file__))
794 def __init__(self, treefile, workdir, cleanup_workdir=True):
795 self.name = os.path.splitext(os.path.basename(treefile))[0]
796 self.treefile = treefile
797 self.workdir = os.path.join(workdir, self.name)
798 self.cleanup_workdir = cleanup_workdir
799 cython_syspath = self.cython_root
800 for path in sys.path[::-1]:
801 if path.startswith(self.cython_root):
802 # Py3 installation and refnanny build prepend their
803 # fixed paths to sys.path => prefer that over the
805 cython_syspath = path + os.pathsep + cython_syspath
806 self.cython_syspath = cython_syspath
807 unittest.TestCase.__init__(self)
809 def shortDescription(self):
810 return "End-to-end %s" % self.name
813 from Cython.TestUtils import unpack_source_tree
814 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
815 self.old_dir = os.getcwd()
816 os.chdir(self.workdir)
817 if self.workdir not in sys.path:
818 sys.path.insert(0, self.workdir)
821 if self.cleanup_workdir:
822 for trial in range(5):
824 shutil.rmtree(self.workdir)
829 os.chdir(self.old_dir)
832 commands = (self.commands
833 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
834 .replace("PYTHON", sys.executable))
836 old_path = os.environ.get('PYTHONPATH')
837 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
838 for command in commands.split('\n'):
839 if sys.version_info[:2] >= (2,4):
841 p = subprocess.Popen(commands,
842 stderr=subprocess.PIPE,
843 stdout=subprocess.PIPE,
845 out, err = p.communicate()
852 res = os.system(command)
853 self.assertEqual(0, res, "non-zero exit status")
856 os.environ['PYTHONPATH'] = old_path
858 del os.environ['PYTHONPATH']
861 # TODO: Support cython_freeze needed here as well.
862 # TODO: Windows support.
864 class EmbedTest(unittest.TestCase):
866 working_dir = "Demos/embed"
869 self.old_dir = os.getcwd()
870 os.chdir(self.working_dir)
872 "make PYTHON='%s' clean > /dev/null" % sys.executable)
877 "make PYTHON='%s' clean > /dev/null" % sys.executable)
880 os.chdir(self.old_dir)
882 def test_embed(self):
883 from distutils import sysconfig
884 libname = sysconfig.get_config_var('LIBRARY')
885 libdir = sysconfig.get_config_var('LIBDIR')
886 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
887 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
888 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
889 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
890 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
891 # report the error for the original directory
892 libdir = sysconfig.get_config_var('LIBDIR')
893 self.assert_(os.system(
894 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
896 os.remove('make.output')
900 class MissingDependencyExcluder:
901 def __init__(self, deps):
902 # deps: { module name : matcher func }
903 self.exclude_matchers = []
904 for mod, matcher in deps.items():
908 self.exclude_matchers.append(matcher)
909 self.tests_missing_deps = []
910 def __call__(self, testname):
911 for matcher in self.exclude_matchers:
912 if matcher(testname):
913 self.tests_missing_deps.append(testname)
917 class VersionDependencyExcluder:
918 def __init__(self, deps):
919 # deps: { version : matcher func }
920 from sys import version_info
921 self.exclude_matchers = []
922 for ver, (compare, matcher) in deps.items():
923 if compare(version_info, ver):
924 self.exclude_matchers.append(matcher)
925 self.tests_missing_deps = []
926 def __call__(self, testname):
927 for matcher in self.exclude_matchers:
928 if matcher(testname):
929 self.tests_missing_deps.append(testname)
933 class FileListExcluder:
935 def __init__(self, list_file):
939 for line in f.readlines():
941 if line and line[0] != '#':
942 self.excludes[line.split()[0]] = True
946 def __call__(self, testname):
947 return testname in self.excludes or testname.split('.')[-1] in self.excludes
949 def refactor_for_py3(distdir, cy3_dir):
950 # need to convert Cython sources first
951 import lib2to3.refactor
952 from distutils.util import copydir_run_2to3
953 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
954 if fix.split('fix_')[-1] not in ('next',)
956 if not os.path.exists(cy3_dir):
958 import distutils.log as dlog
959 dlog.set_threshold(dlog.INFO)
960 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
964 recursive-exclude Cython *
965 recursive-include Cython *.py *.pyx *.pxd
966 recursive-include Cython/Debugger/Tests *
969 sys.path.insert(0, cy3_dir)
971 for keep_2x_file in KEEP_2X_FILES:
972 destfile = os.path.join(cy3_dir, keep_2x_file)
973 shutil.copy(keep_2x_file, destfile)
975 class PendingThreadsError(RuntimeError):
980 def check_thread_termination(ignore_seen=True):
981 if threading is None: # no threading enabled in CPython
983 current = threading.currentThread()
984 blocking_threads = []
985 for t in threading.enumerate():
986 if not t.isAlive() or t == current:
991 blocking_threads.append(t)
993 for seen in threads_seen:
997 threads_seen.append(t)
998 blocking_threads.append(t)
999 if not blocking_threads:
1001 sys.stderr.write("warning: left-over threads found after running test:\n")
1002 for t in blocking_threads:
1003 sys.stderr.write('...%s\n' % repr(t))
1004 raise PendingThreadsError("left-over threads found after running test")
1008 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1010 from optparse import OptionParser
1011 parser = OptionParser()
1012 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1013 action="store_false", default=True,
1014 help="do not delete the generated C files (allows passing --no-cython on next run)")
1015 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1016 action="store_false", default=True,
1017 help="do not delete the generated shared libary files (allows manual module experimentation)")
1018 parser.add_option("--no-cython", dest="with_cython",
1019 action="store_false", default=True,
1020 help="do not run the Cython compiler, only the C compiler")
1021 parser.add_option("--compiler", dest="compiler", default=None,
1022 help="C compiler type")
1023 parser.add_option("--no-c", dest="use_c",
1024 action="store_false", default=True,
1025 help="do not test C compilation")
1026 parser.add_option("--no-cpp", dest="use_cpp",
1027 action="store_false", default=True,
1028 help="do not test C++ compilation")
1029 parser.add_option("--no-unit", dest="unittests",
1030 action="store_false", default=True,
1031 help="do not run the unit tests")
1032 parser.add_option("--no-doctest", dest="doctests",
1033 action="store_false", default=True,
1034 help="do not run the doctests")
1035 parser.add_option("--no-file", dest="filetests",
1036 action="store_false", default=True,
1037 help="do not run the file based tests")
1038 parser.add_option("--no-pyregr", dest="pyregr",
1039 action="store_false", default=True,
1040 help="do not run the regression tests of CPython in tests/pyregr/")
1041 parser.add_option("--cython-only", dest="cython_only",
1042 action="store_true", default=False,
1043 help="only compile pyx to c, do not run C compiler or run the tests")
1044 parser.add_option("--no-refnanny", dest="with_refnanny",
1045 action="store_false", default=True,
1046 help="do not regression test reference counting")
1047 parser.add_option("--no-fork", dest="fork",
1048 action="store_false", default=True,
1049 help="do not fork to run tests")
1050 parser.add_option("--sys-pyregr", dest="system_pyregr",
1051 action="store_true", default=False,
1052 help="run the regression tests of the CPython installation")
1053 parser.add_option("-x", "--exclude", dest="exclude",
1054 action="append", metavar="PATTERN",
1055 help="exclude tests matching the PATTERN")
1056 parser.add_option("-C", "--coverage", dest="coverage",
1057 action="store_true", default=False,
1058 help="collect source coverage data for the Compiler")
1059 parser.add_option("--coverage-xml", dest="coverage_xml",
1060 action="store_true", default=False,
1061 help="collect source coverage data for the Compiler in XML format")
1062 parser.add_option("-A", "--annotate", dest="annotate_source",
1063 action="store_true", default=True,
1064 help="generate annotated HTML versions of the test source files")
1065 parser.add_option("--no-annotate", dest="annotate_source",
1066 action="store_false",
1067 help="do not generate annotated HTML versions of the test source files")
1068 parser.add_option("-v", "--verbose", dest="verbosity",
1069 action="count", default=0,
1070 help="display test progress, pass twice to print test names")
1071 parser.add_option("-T", "--ticket", dest="tickets",
1073 help="a bug ticket number to run the respective test in 'tests/*'")
1074 parser.add_option("-3", dest="language_level",
1075 action="store_const", const=3, default=2,
1076 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1077 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1078 help="write test results in XML to directory DIR")
1079 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1080 action="store_true",
1081 help="exit without error code even on test failures")
1082 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1083 help="working directory")
1084 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1085 help="working directory")
1087 options, cmd_args = parser.parse_args()
1089 ROOTDIR = os.path.abspath(options.root_dir)
1090 WORKDIR = os.path.abspath(options.work_dir)
1092 if sys.version_info[0] >= 3:
1093 options.doctests = False
1094 if options.with_cython:
1096 # try if Cython is installed in a Py3 version
1097 import Cython.Compiler.Main
1099 # back out anything the import process loaded, then
1100 # 2to3 the Cython sources to make them re-importable
1101 cy_modules = [ name for name in sys.modules
1102 if name == 'Cython' or name.startswith('Cython.') ]
1103 for name in cy_modules:
1104 del sys.modules[name]
1105 # hasn't been refactored yet - do it now
1106 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1107 if sys.version_info >= (3,1):
1108 refactor_for_py3(DISTDIR, cy3_dir)
1109 elif os.path.isdir(cy3_dir):
1110 sys.path.insert(0, cy3_dir)
1112 options.with_cython = False
1114 WITH_CYTHON = options.with_cython
1116 if options.coverage or options.coverage_xml:
1118 options.coverage = options.coverage_xml = False
1120 from coverage import coverage as _coverage
1121 coverage = _coverage(branch=True)
1126 global CompilationOptions, pyrex_default_options, cython_compile
1127 from Cython.Compiler.Main import \
1128 CompilationOptions, \
1129 default_options as pyrex_default_options, \
1130 compile as cython_compile
1131 from Cython.Compiler import Errors
1132 Errors.LEVEL = 0 # show all warnings
1133 from Cython.Compiler import Options
1134 Options.generate_cleanup_code = 3 # complete cleanup code
1135 from Cython.Compiler import DebugFlags
1136 DebugFlags.debug_temp_code_comments = 1
1139 UNITTEST_MODULE = "Cython"
1140 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1142 if os.path.exists(WORKDIR):
1143 for path in os.listdir(WORKDIR):
1144 if path in ("support", "Cy3"): continue
1145 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1146 if not os.path.exists(WORKDIR):
1147 os.makedirs(WORKDIR)
1149 sys.stderr.write("Python %s\n" % sys.version)
1150 sys.stderr.write("\n")
1152 from Cython.Compiler.Version import version
1153 sys.stderr.write("Running tests against Cython %s\n" % version)
1155 sys.stderr.write("Running tests without Cython.\n")
1157 if options.with_refnanny:
1158 from pyximport.pyxbuild import pyx_to_dll
1159 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1161 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1162 sys.path.insert(0, os.path.split(libpath)[0])
1163 CFLAGS.append("-DCYTHON_REFNANNY=1")
1165 if options.xml_output_dir and options.fork:
1166 # doesn't currently work together
1167 sys.stderr.write("Disabling forked testing to support XML test output\n")
1168 options.fork = False
1170 if WITH_CYTHON and options.language_level == 3:
1171 sys.stderr.write("Using Cython language level 3.\n")
1173 sys.stderr.write("\n")
1177 for ticket_number in options.tickets:
1179 cmd_args.append('.*T%s$' % ticket_number)
1181 for selector in cmd_args:
1182 if selector.startswith('bugs'):
1186 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1188 selectors = [ lambda x:True ]
1190 # Chech which external modules are not present and exclude tests
1191 # which depends on them (by prefix)
1193 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1194 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1195 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1198 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1201 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1203 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1204 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1207 if options.compiler:
1208 COMPILER = options.compiler
1211 languages.append('c')
1213 languages.append('cpp')
1215 test_suite = unittest.TestSuite()
1217 if options.unittests:
1218 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1220 if options.doctests:
1221 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1223 if options.filetests and languages:
1224 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1225 options.annotate_source, options.cleanup_workdir,
1226 options.cleanup_sharedlibs, options.pyregr,
1227 options.cython_only, languages, test_bugs,
1228 options.fork, options.language_level)
1229 test_suite.addTest(filetests.build_suite())
1231 if options.system_pyregr and languages:
1232 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1233 options.annotate_source, options.cleanup_workdir,
1234 options.cleanup_sharedlibs, True,
1235 options.cython_only, languages, test_bugs,
1236 options.fork, options.language_level)
1238 filetests.handle_directory(
1239 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1242 if options.xml_output_dir:
1243 from Cython.Tests.xmlrunner import XMLTestRunner
1244 test_runner = XMLTestRunner(output=options.xml_output_dir,
1245 verbose=options.verbosity > 0)
1247 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1249 result = test_runner.run(test_suite)
1251 if options.coverage or options.coverage_xml:
1253 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1254 modules = [ module for name, module in sys.modules.items()
1255 if module is not None and
1256 name.startswith('Cython.Compiler.') and
1257 name[len('Cython.Compiler.'):] not in ignored_modules ]
1258 if options.coverage:
1259 coverage.report(modules, show_missing=0)
1260 if options.coverage_xml:
1261 coverage.xml_report(modules, outfile="coverage-report.xml")
1263 if missing_dep_excluder.tests_missing_deps:
1264 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1265 for test in missing_dep_excluder.tests_missing_deps:
1266 sys.stderr.write(" %s\n" % test)
1268 if options.with_refnanny:
1270 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1277 return_code = not result.wasSuccessful()
1280 check_thread_termination(ignore_seen=False)
1281 sys.exit(return_code)
1282 except PendingThreadsError:
1283 # normal program exit won't kill the threads, do it the hard way here
1284 os._exit(return_code)
1286 if __name__ == '__main__':
1289 except SystemExit: # <= Py2.4 ...
1292 traceback.print_exc()
1294 check_thread_termination(ignore_seen=False)
1295 except PendingThreadsError:
1296 # normal program exit won't kill the threads, do it the hard way here