15 from StringIO import StringIO
17 from io import StringIO
20 import cPickle as pickle
26 except ImportError: # No threads, no problems
31 from distutils.dist import Distribution
32 from distutils.core import Extension
33 from distutils.command.build_ext import build_ext as _build_ext
34 distutils_distro = Distribution()
36 if sys.platform == 'win32':
37 # TODO: Figure out why this hackery (see http://thread.gmane.org/gmane.comp.python.cython.devel/8280/).
38 config_files = distutils_distro.find_config_files()
39 try: config_files.remove('setup.cfg')
40 except ValueError: pass
41 distutils_distro.parse_config_files(config_files)
43 cfgfiles = distutils_distro.find_config_files()
44 try: cfgfiles.remove('setup.cfg')
45 except ValueError: pass
46 distutils_distro.parse_config_files(cfgfiles)
48 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr', 'build']
49 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
51 # Lists external modules, and a matcher matching tests
52 # which should be excluded if the module is not present.
54 'numpy' : re.compile('.*\.numpy_.*').match,
55 'pstats' : re.compile('.*\.pstats_.*').match,
56 'posix' : re.compile('.*\.posix_.*').match,
59 def get_numpy_include_dirs():
61 return [numpy.get_include()]
64 # test name matcher , callable returning list
65 (re.compile('numpy_.*').match, get_numpy_include_dirs),
69 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
70 # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
71 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
74 (2,5) : (operator.lt, lambda x: x in ['run.any',
77 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
79 'run.pure_py', # decorators, with statement
81 # The next line should start (3,); but this is a dictionary, so
82 # we can only have one (3,) key. Since 2.7 is supposed to be the
83 # last 2.x release, things would have to change drastically for this
85 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
86 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
87 'compile.extsetslice',
88 'compile.extdelslice',
89 'run.special_methods_T561_py2']),
92 # files that should not be converted to Python 3 code with 2to3
94 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
95 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
96 os.path.join('Cython', 'Debugger', 'libcython.py'),
97 os.path.join('Cython', 'Debugger', 'libpython.py'),
101 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
102 CFLAGS = os.getenv('CFLAGS', '').split()
104 class build_ext(_build_ext):
105 def build_extension(self, ext):
106 if ext.language == 'c++':
108 try: # Py2.7+ & Py3.2+
109 compiler_obj = self.compiler_obj
110 except AttributeError:
111 compiler_obj = self.compiler
112 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
115 _build_ext.build_extension(self, ext)
117 class ErrorWriter(object):
118 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
121 self.write = self.output.append
123 def _collect(self, collect_errors, collect_warnings):
124 s = ''.join(self.output)
126 for line in s.split('\n'):
127 match = self.match_error(line)
129 is_warning, line, column, message = match.groups()
130 if (is_warning and collect_warnings) or \
131 (not is_warning and collect_errors):
132 result.append( (int(line), int(column), message.strip()) )
134 return [ "%d:%d: %s" % values for values in result ]
137 return self._collect(True, False)
139 def getwarnings(self):
140 return self._collect(False, True)
143 return self._collect(True, True)
145 class TestBuilder(object):
146 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
147 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
148 languages, test_bugs, fork, language_level):
149 self.rootdir = rootdir
150 self.workdir = workdir
151 self.selectors = selectors
152 self.exclude_selectors = exclude_selectors
153 self.annotate = annotate
154 self.cleanup_workdir = cleanup_workdir
155 self.cleanup_sharedlibs = cleanup_sharedlibs
156 self.with_pyregr = with_pyregr
157 self.cython_only = cython_only
158 self.languages = languages
159 self.test_bugs = test_bugs
161 self.language_level = language_level
163 def build_suite(self):
164 suite = unittest.TestSuite()
165 test_dirs = TEST_DIRS
166 filenames = os.listdir(self.rootdir)
168 for filename in filenames:
169 if not WITH_CYTHON and filename == "errors":
170 # we won't get any errors without running Cython
172 path = os.path.join(self.rootdir, filename)
173 if os.path.isdir(path) and filename in test_dirs:
174 if filename == 'pyregr' and not self.with_pyregr:
177 self.handle_directory(path, filename))
178 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
179 # Non-Windows makefile, can't run Cython under Py3.
180 if [1 for selector in self.selectors if selector("embedded")] \
181 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
182 suite.addTest(unittest.makeSuite(EmbedTest))
185 def handle_directory(self, path, context):
186 workdir = os.path.join(self.workdir, context)
187 if not os.path.exists(workdir):
190 expect_errors = (context == 'errors')
191 suite = unittest.TestSuite()
192 filenames = os.listdir(path)
194 for filename in filenames:
195 if context == "build" and filename.endswith(".srctree"):
196 if not [ 1 for match in self.selectors if match(filename) ]:
198 if self.exclude_selectors:
199 if [1 for match in self.exclude_selectors if match(filename)]:
201 suite.addTest(EndToEndTest(os.path.join(path, filename), workdir, self.cleanup_workdir))
203 if not (filename.endswith(".pyx") or filename.endswith(".py")):
205 if filename.startswith('.'): continue # certain emacs backup files
206 if context == 'pyregr' and not filename.startswith('test_'):
208 module = os.path.splitext(filename)[0]
209 fqmodule = "%s.%s" % (context, module)
210 if not [ 1 for match in self.selectors
211 if match(fqmodule) ]:
213 if self.exclude_selectors:
214 if [1 for match in self.exclude_selectors if match(fqmodule)]:
216 if context == 'pyregr':
217 test_class = CythonPyregrTestCase
218 elif context in TEST_RUN_DIRS:
219 if module.startswith("test_"):
220 test_class = CythonUnitTestCase
222 test_class = CythonRunTestCase
224 test_class = CythonCompileTestCase
225 for test in self.build_tests(test_class, path, workdir,
226 module, expect_errors):
228 if context == 'run' and filename.endswith('.py'):
229 # additionally test file in real Python
230 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
233 def build_tests(self, test_class, path, workdir, module, expect_errors):
235 if 'cpp' in module and 'cpp' in self.languages:
238 languages = self.languages[:1]
240 languages = self.languages
241 if 'cpp' in module and 'c' in languages:
242 languages = list(languages)
243 languages.remove('c')
244 tests = [ self.build_test(test_class, path, workdir, module,
245 language, expect_errors)
246 for language in languages ]
249 def build_test(self, test_class, path, workdir, module,
250 language, expect_errors):
251 workdir = os.path.join(workdir, language)
252 if not os.path.exists(workdir):
254 return test_class(path, workdir, module,
256 expect_errors=expect_errors,
257 annotate=self.annotate,
258 cleanup_workdir=self.cleanup_workdir,
259 cleanup_sharedlibs=self.cleanup_sharedlibs,
260 cython_only=self.cython_only,
262 language_level=self.language_level)
264 class CythonCompileTestCase(unittest.TestCase):
265 def __init__(self, test_directory, workdir, module, language='c',
266 expect_errors=False, annotate=False, cleanup_workdir=True,
267 cleanup_sharedlibs=True, cython_only=False, fork=True,
269 self.test_directory = test_directory
270 self.workdir = workdir
272 self.language = language
273 self.expect_errors = expect_errors
274 self.annotate = annotate
275 self.cleanup_workdir = cleanup_workdir
276 self.cleanup_sharedlibs = cleanup_sharedlibs
277 self.cython_only = cython_only
279 self.language_level = language_level
280 unittest.TestCase.__init__(self)
282 def shortDescription(self):
283 return "compiling (%s) %s" % (self.language, self.module)
286 if self.workdir not in sys.path:
287 sys.path.insert(0, self.workdir)
291 sys.path.remove(self.workdir)
295 del sys.modules[self.module]
298 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
299 cleanup_lib_files = self.cleanup_sharedlibs
300 if os.path.exists(self.workdir):
301 for rmfile in os.listdir(self.workdir):
302 if not cleanup_c_files:
303 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
305 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
307 if self.annotate and rmfile.endswith(".html"):
310 rmfile = os.path.join(self.workdir, rmfile)
311 if os.path.isdir(rmfile):
312 shutil.rmtree(rmfile, ignore_errors=True)
318 os.makedirs(self.workdir)
321 self.runCompileTest()
323 def runCompileTest(self):
324 self.compile(self.test_directory, self.module, self.workdir,
325 self.test_directory, self.expect_errors, self.annotate)
327 def find_module_source_file(self, source_file):
328 if not os.path.exists(source_file):
329 source_file = source_file[:-1]
332 def build_target_filename(self, module_name):
333 target = '%s.%s' % (module_name, self.language)
336 def copy_related_files(self, test_directory, target_directory, module_name):
337 is_related = re.compile('%s_.*[.].*' % module_name).match
338 for filename in os.listdir(test_directory):
339 if is_related(filename):
340 shutil.copy(os.path.join(test_directory, filename),
343 def find_source_files(self, workdir, module_name):
344 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
345 return [self.build_target_filename(module_name)] + [
346 filename for filename in os.listdir(workdir)
347 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
349 def split_source_and_output(self, test_directory, module, workdir):
350 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
351 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
353 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
355 for line in source_and_output:
357 if line.startswith("_ERRORS"):
363 source_and_output.close()
365 geterrors = out.geterrors
366 except AttributeError:
372 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
373 extra_compile_options=None):
374 include_dirs = INCLUDE_DIRS[:]
376 include_dirs.append(incdir)
377 source = self.find_module_source_file(
378 os.path.join(test_directory, module + '.pyx'))
379 target = os.path.join(targetdir, self.build_target_filename(module))
381 if extra_compile_options is None:
382 extra_compile_options = {}
387 from Cython.Compiler.Main import CompilationOptions
388 from Cython.Compiler.Main import compile as cython_compile
389 from Cython.Compiler.Main import default_options
391 options = CompilationOptions(
393 include_path = include_dirs,
394 output_file = target,
396 use_listing_file = False,
397 cplus = self.language == 'cpp',
398 language_level = self.language_level,
399 generate_pxi = False,
400 evaluate_tree_assertions = True,
401 **extra_compile_options
403 cython_compile(source, options=options,
404 full_module_name=module)
406 def run_distutils(self, test_directory, module, workdir, incdir,
407 extra_extension_args=None):
411 build_extension = build_ext(distutils_distro)
412 build_extension.include_dirs = INCLUDE_DIRS[:]
414 build_extension.include_dirs.append(incdir)
415 build_extension.finalize_options()
416 ext_include_dirs = []
417 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
419 ext_include_dirs += get_additional_include_dirs()
420 self.copy_related_files(test_directory, workdir, module)
422 if extra_extension_args is None:
423 extra_extension_args = {}
425 extension = Extension(
427 sources = self.find_source_files(workdir, module),
428 include_dirs = ext_include_dirs,
429 extra_compile_args = CFLAGS,
430 **extra_extension_args
432 if self.language == 'cpp':
433 extension.language = 'c++'
434 build_extension.extensions = [extension]
435 build_extension.build_temp = workdir
436 build_extension.build_lib = workdir
437 build_extension.run()
441 def compile(self, test_directory, module, workdir, incdir,
442 expect_errors, annotate):
443 expected_errors = errors = ()
445 expected_errors = self.split_source_and_output(
446 test_directory, module, workdir)
447 test_directory = workdir
450 old_stderr = sys.stderr
452 sys.stderr = ErrorWriter()
453 self.run_cython(test_directory, module, workdir, incdir, annotate)
454 errors = sys.stderr.geterrors()
456 sys.stderr = old_stderr
458 if errors or expected_errors:
460 for expected, error in zip(expected_errors, errors):
461 self.assertEquals(expected, error)
462 if len(errors) < len(expected_errors):
463 expected_error = expected_errors[len(errors)]
464 self.assertEquals(expected_error, None)
465 elif len(errors) > len(expected_errors):
466 unexpected_error = errors[len(expected_errors)]
467 self.assertEquals(None, unexpected_error)
468 except AssertionError:
469 print("\n=== Expected errors: ===")
470 print('\n'.join(expected_errors))
471 print("\n\n=== Got errors: ===")
472 print('\n'.join(errors))
476 if not self.cython_only:
477 self.run_distutils(test_directory, module, workdir, incdir)
479 class CythonRunTestCase(CythonCompileTestCase):
480 def shortDescription(self):
481 return "compiling (%s) and running %s" % (self.language, self.module)
483 def run(self, result=None):
485 result = self.defaultTestResult()
486 result.startTest(self)
490 self.runCompileTest()
491 self.run_tests(result)
493 check_thread_termination()
495 result.addError(self, sys.exc_info())
496 result.stopTest(self)
502 def run_tests(self, result):
503 if not self.cython_only:
504 self.run_doctests(self.module, result)
506 def run_doctests(self, module_name, result):
507 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
508 doctest.DocTestSuite(module_name).run(result)
512 # fork to make sure we do not keep the tested module loaded
513 result_handle, result_file = tempfile.mkstemp()
514 os.close(result_handle)
522 partial_result = PartialTestResult(result)
523 tests = doctest.DocTestSuite(module_name)
524 tests.run(partial_result)
528 # importing failed, try to fake a test class
530 failureException=sys.exc_info()[1],
531 _shortDescription=self.shortDescription(),
533 partial_result.addError(tests, sys.exc_info())
535 output = open(result_file, 'wb')
536 pickle.dump(partial_result.data(), output)
538 traceback.print_exc()
542 os._exit(result_code)
545 cid, result_code = os.waitpid(child_id, 0)
546 # os.waitpid returns the child's result code in the
547 # upper byte of result_code, and the signal it was
548 # killed by in the lower byte
549 if result_code & 255:
550 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
551 (module_name, result_code & 255))
552 result_code = result_code >> 8
553 if result_code in (0,1):
554 input = open(result_file, 'rb')
556 PartialTestResult.join_results(result, pickle.load(input))
560 raise Exception("Tests in module '%s' exited with status %d" %
561 (module_name, result_code))
563 try: os.unlink(result_file)
566 class PureDoctestTestCase(unittest.TestCase):
567 def __init__(self, module_name, module_path):
568 self.module_name = module_name
569 self.module_path = module_path
570 unittest.TestCase.__init__(self, 'run')
572 def shortDescription(self):
573 return "running pure doctests in %s" % self.module_name
575 def run(self, result=None):
577 result = self.defaultTestResult()
578 loaded_module_name = 'pure_doctest__' + self.module_name
579 result.startTest(self)
584 m = imp.load_source(loaded_module_name, self.module_path)
586 doctest.DocTestSuite(m).run(result)
589 if loaded_module_name in sys.modules:
590 del sys.modules[loaded_module_name]
591 check_thread_termination()
593 result.addError(self, sys.exc_info())
594 result.stopTest(self)
600 is_private_field = re.compile('^_[^_]').match
602 class _FakeClass(object):
603 def __init__(self, **kwargs):
604 self._shortDescription = kwargs.get('module_name')
605 self.__dict__.update(kwargs)
606 def shortDescription(self):
607 return self._shortDescription
609 try: # Py2.7+ and Py3.2+
610 from unittest.runner import _TextTestResult
612 from unittest import _TextTestResult
614 class PartialTestResult(_TextTestResult):
615 def __init__(self, base_result):
616 _TextTestResult.__init__(
617 self, self._StringIO(), True,
618 base_result.dots + base_result.showAll*2)
620 def strip_error_results(self, results):
621 for test_case, error in results:
622 for attr_name in filter(is_private_field, dir(test_case)):
623 if attr_name == '_dt_test':
624 test_case._dt_test = _FakeClass(
625 name=test_case._dt_test.name)
626 elif attr_name != '_shortDescription':
627 setattr(test_case, attr_name, None)
630 self.strip_error_results(self.failures)
631 self.strip_error_results(self.errors)
632 return (self.failures, self.errors, self.testsRun,
633 self.stream.getvalue())
635 def join_results(result, data):
636 """Static method for merging the result back into the main
639 failures, errors, tests_run, output = data
641 result.stream.write(output)
642 result.errors.extend(errors)
643 result.failures.extend(failures)
644 result.testsRun += tests_run
646 join_results = staticmethod(join_results)
648 class _StringIO(StringIO):
649 def writeln(self, line):
650 self.write("%s\n" % line)
653 class CythonUnitTestCase(CythonRunTestCase):
654 def shortDescription(self):
655 return "compiling (%s) tests in %s" % (self.language, self.module)
657 def run_tests(self, result):
658 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
661 class CythonPyregrTestCase(CythonRunTestCase):
662 def _run_unittest(self, result, *classes):
663 """Run tests from unittest.TestCase-derived classes."""
664 valid_types = (unittest.TestSuite, unittest.TestCase)
665 suite = unittest.TestSuite()
667 if isinstance(cls, str):
668 if cls in sys.modules:
669 suite.addTest(unittest.findTestCases(sys.modules[cls]))
671 raise ValueError("str arguments must be keys in sys.modules")
672 elif isinstance(cls, valid_types):
675 suite.addTest(unittest.makeSuite(cls))
678 def _run_doctest(self, result, module):
679 self.run_doctests(module, result)
681 def run_tests(self, result):
683 from test import test_support as support
684 except ImportError: # Py3k
685 from test import support
687 def run_unittest(*classes):
688 return self._run_unittest(result, *classes)
689 def run_doctest(module, verbosity=None):
690 return self._run_doctest(result, module)
692 support.run_unittest = run_unittest
693 support.run_doctest = run_doctest
696 module = __import__(self.module)
697 if hasattr(module, 'test_main'):
699 except (unittest.SkipTest, support.ResourceDenied):
700 result.addSkip(self, 'ok')
702 include_debugger = sys.version_info[:2] > (2, 5)
704 def collect_unittests(path, module_prefix, suite, selectors):
705 def file_matches(filename):
706 return filename.startswith("Test") and filename.endswith(".py")
708 def package_matches(dirname):
709 return dirname == "Tests"
711 loader = unittest.TestLoader()
716 cython_dir = os.path.dirname(os.path.abspath(__file__))
717 skipped_dirs = [os.path.join(cython_dir, 'Cython', 'Debugger')]
719 for dirpath, dirnames, filenames in os.walk(path):
720 if dirpath != path and "__init__.py" not in filenames:
721 skipped_dirs.append(dirpath + os.path.sep)
724 for dir in skipped_dirs:
725 if dirpath.startswith(dir):
729 parentname = os.path.split(dirpath)[-1]
730 if package_matches(parentname):
733 filepath = os.path.join(dirpath, f)[:-len(".py")]
734 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
735 if not [ 1 for match in selectors if match(modulename) ]:
737 module = __import__(modulename)
738 for x in modulename.split('.')[1:]:
739 module = getattr(module, x)
740 suite.addTests([loader.loadTestsFromModule(module)])
744 def collect_doctests(path, module_prefix, suite, selectors):
745 def package_matches(dirname):
746 if dirname == 'Debugger' and not include_debugger:
748 return dirname not in ("Mac", "Distutils", "Plex")
749 def file_matches(filename):
750 filename, ext = os.path.splitext(filename)
751 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
753 return (ext == '.py' and not
754 '~' in filename and not
755 '#' in filename and not
756 filename.startswith('.') and not
757 filename in blacklist)
758 import doctest, types
759 for dirpath, dirnames, filenames in os.walk(path):
760 for dir in list(dirnames):
761 if not package_matches(dir):
765 if not f.endswith('.py'): continue
766 filepath = os.path.join(dirpath, f)
767 if os.path.getsize(filepath) == 0: continue
768 filepath = filepath[:-len(".py")]
769 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
770 if not [ 1 for match in selectors if match(modulename) ]:
772 if 'in_gdb' in modulename:
773 # These should only be imported from gdb.
775 module = __import__(modulename)
776 for x in modulename.split('.')[1:]:
777 module = getattr(module, x)
778 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
780 suite.addTest(doctest.DocTestSuite(module))
781 except ValueError: # no tests
785 class EndToEndTest(unittest.TestCase):
787 This is a test of build/*.srctree files, where srctree defines a full
788 directory structure and its header gives a list of commands to run.
790 cython_root = os.path.dirname(os.path.abspath(__file__))
792 def __init__(self, treefile, workdir, cleanup_workdir=True):
793 self.name = os.path.splitext(os.path.basename(treefile))[0]
794 self.treefile = treefile
795 self.workdir = os.path.join(workdir, self.name)
796 self.cleanup_workdir = cleanup_workdir
797 cython_syspath = self.cython_root
798 for path in sys.path[::-1]:
799 if path.startswith(self.cython_root):
800 # Py3 installation and refnanny build prepend their
801 # fixed paths to sys.path => prefer that over the
803 cython_syspath = path + os.pathsep + cython_syspath
804 self.cython_syspath = cython_syspath
805 unittest.TestCase.__init__(self)
807 def shortDescription(self):
808 return "End-to-end %s" % self.name
811 from Cython.TestUtils import unpack_source_tree
812 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
813 self.old_dir = os.getcwd()
814 os.chdir(self.workdir)
815 if self.workdir not in sys.path:
816 sys.path.insert(0, self.workdir)
819 if self.cleanup_workdir:
820 shutil.rmtree(self.workdir)
821 os.chdir(self.old_dir)
824 commands = (self.commands
825 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
826 .replace("PYTHON", sys.executable))
828 old_path = os.environ.get('PYTHONPATH')
829 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
830 for command in commands.split('\n'):
831 if sys.version_info[:2] >= (2,4):
833 p = subprocess.Popen(commands,
834 stderr=subprocess.PIPE,
835 stdout=subprocess.PIPE,
837 out, err = p.communicate()
844 res = os.system(command)
845 self.assertEqual(0, res, "non-zero exit status")
848 os.environ['PYTHONPATH'] = old_path
850 del os.environ['PYTHONPATH']
853 # TODO: Support cython_freeze needed here as well.
854 # TODO: Windows support.
856 class EmbedTest(unittest.TestCase):
858 working_dir = "Demos/embed"
861 self.old_dir = os.getcwd()
862 os.chdir(self.working_dir)
864 "make PYTHON='%s' clean > /dev/null" % sys.executable)
869 "make PYTHON='%s' clean > /dev/null" % sys.executable)
872 os.chdir(self.old_dir)
874 def test_embed(self):
875 from distutils import sysconfig
876 libname = sysconfig.get_config_var('LIBRARY')
877 libdir = sysconfig.get_config_var('LIBDIR')
878 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
879 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
880 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
881 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
882 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
883 # report the error for the original directory
884 libdir = sysconfig.get_config_var('LIBDIR')
885 self.assert_(os.system(
886 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
888 os.remove('make.output')
892 class MissingDependencyExcluder:
893 def __init__(self, deps):
894 # deps: { module name : matcher func }
895 self.exclude_matchers = []
896 for mod, matcher in deps.items():
900 self.exclude_matchers.append(matcher)
901 self.tests_missing_deps = []
902 def __call__(self, testname):
903 for matcher in self.exclude_matchers:
904 if matcher(testname):
905 self.tests_missing_deps.append(testname)
909 class VersionDependencyExcluder:
910 def __init__(self, deps):
911 # deps: { version : matcher func }
912 from sys import version_info
913 self.exclude_matchers = []
914 for ver, (compare, matcher) in deps.items():
915 if compare(version_info, ver):
916 self.exclude_matchers.append(matcher)
917 self.tests_missing_deps = []
918 def __call__(self, testname):
919 for matcher in self.exclude_matchers:
920 if matcher(testname):
921 self.tests_missing_deps.append(testname)
925 class FileListExcluder:
927 def __init__(self, list_file):
931 for line in f.readlines():
933 if line and line[0] != '#':
934 self.excludes[line.split()[0]] = True
938 def __call__(self, testname):
939 return testname in self.excludes or testname.split('.')[-1] in self.excludes
941 def refactor_for_py3(distdir, cy3_dir):
942 # need to convert Cython sources first
943 import lib2to3.refactor
944 from distutils.util import copydir_run_2to3
945 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
946 if fix.split('fix_')[-1] not in ('next',)
948 if not os.path.exists(cy3_dir):
950 import distutils.log as dlog
951 dlog.set_threshold(dlog.INFO)
952 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
956 recursive-exclude Cython *
957 recursive-include Cython *.py *.pyx *.pxd
958 recursive-include Cython/Debugger/Tests *
961 sys.path.insert(0, cy3_dir)
963 for keep_2x_file in KEEP_2X_FILES:
964 destfile = os.path.join(cy3_dir, keep_2x_file)
965 shutil.copy(keep_2x_file, destfile)
967 class PendingThreadsError(RuntimeError):
972 def check_thread_termination(ignore_seen=True):
973 if threading is None: # no threading enabled in CPython
975 current = threading.currentThread()
976 blocking_threads = []
977 for t in threading.enumerate():
978 if not t.isAlive() or t == current:
983 blocking_threads.append(t)
985 for seen in threads_seen:
989 threads_seen.append(t)
990 blocking_threads.append(t)
991 if not blocking_threads:
993 sys.stderr.write("warning: left-over threads found after running test:\n")
994 for t in blocking_threads:
995 sys.stderr.write('...%s\n' % repr(t))
996 raise PendingThreadsError("left-over threads found after running test")
1000 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1002 from optparse import OptionParser
1003 parser = OptionParser()
1004 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1005 action="store_false", default=True,
1006 help="do not delete the generated C files (allows passing --no-cython on next run)")
1007 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1008 action="store_false", default=True,
1009 help="do not delete the generated shared libary files (allows manual module experimentation)")
1010 parser.add_option("--no-cython", dest="with_cython",
1011 action="store_false", default=True,
1012 help="do not run the Cython compiler, only the C compiler")
1013 parser.add_option("--no-c", dest="use_c",
1014 action="store_false", default=True,
1015 help="do not test C compilation")
1016 parser.add_option("--no-cpp", dest="use_cpp",
1017 action="store_false", default=True,
1018 help="do not test C++ compilation")
1019 parser.add_option("--no-unit", dest="unittests",
1020 action="store_false", default=True,
1021 help="do not run the unit tests")
1022 parser.add_option("--no-doctest", dest="doctests",
1023 action="store_false", default=True,
1024 help="do not run the doctests")
1025 parser.add_option("--no-file", dest="filetests",
1026 action="store_false", default=True,
1027 help="do not run the file based tests")
1028 parser.add_option("--no-pyregr", dest="pyregr",
1029 action="store_false", default=True,
1030 help="do not run the regression tests of CPython in tests/pyregr/")
1031 parser.add_option("--cython-only", dest="cython_only",
1032 action="store_true", default=False,
1033 help="only compile pyx to c, do not run C compiler or run the tests")
1034 parser.add_option("--no-refnanny", dest="with_refnanny",
1035 action="store_false", default=True,
1036 help="do not regression test reference counting")
1037 parser.add_option("--no-fork", dest="fork",
1038 action="store_false", default=True,
1039 help="do not fork to run tests")
1040 parser.add_option("--sys-pyregr", dest="system_pyregr",
1041 action="store_true", default=False,
1042 help="run the regression tests of the CPython installation")
1043 parser.add_option("-x", "--exclude", dest="exclude",
1044 action="append", metavar="PATTERN",
1045 help="exclude tests matching the PATTERN")
1046 parser.add_option("-C", "--coverage", dest="coverage",
1047 action="store_true", default=False,
1048 help="collect source coverage data for the Compiler")
1049 parser.add_option("--coverage-xml", dest="coverage_xml",
1050 action="store_true", default=False,
1051 help="collect source coverage data for the Compiler in XML format")
1052 parser.add_option("-A", "--annotate", dest="annotate_source",
1053 action="store_true", default=True,
1054 help="generate annotated HTML versions of the test source files")
1055 parser.add_option("--no-annotate", dest="annotate_source",
1056 action="store_false",
1057 help="do not generate annotated HTML versions of the test source files")
1058 parser.add_option("-v", "--verbose", dest="verbosity",
1059 action="count", default=0,
1060 help="display test progress, pass twice to print test names")
1061 parser.add_option("-T", "--ticket", dest="tickets",
1063 help="a bug ticket number to run the respective test in 'tests/*'")
1064 parser.add_option("-3", dest="language_level",
1065 action="store_const", const=3, default=2,
1066 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1067 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1068 help="write test results in XML to directory DIR")
1069 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1070 action="store_true",
1071 help="exit without error code even on test failures")
1072 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1073 help="working directory")
1074 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1075 help="working directory")
1077 options, cmd_args = parser.parse_args()
1079 ROOTDIR = os.path.abspath(options.root_dir)
1080 WORKDIR = os.path.abspath(options.work_dir)
1082 if sys.version_info[0] >= 3:
1083 options.doctests = False
1084 if options.with_cython:
1086 # try if Cython is installed in a Py3 version
1087 import Cython.Compiler.Main
1089 # back out anything the import process loaded, then
1090 # 2to3 the Cython sources to make them re-importable
1091 cy_modules = [ name for name in sys.modules
1092 if name == 'Cython' or name.startswith('Cython.') ]
1093 for name in cy_modules:
1094 del sys.modules[name]
1095 # hasn't been refactored yet - do it now
1096 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1097 if sys.version_info >= (3,1):
1098 refactor_for_py3(DISTDIR, cy3_dir)
1099 elif os.path.isdir(cy3_dir):
1100 sys.path.insert(0, cy3_dir)
1102 options.with_cython = False
1104 WITH_CYTHON = options.with_cython
1106 if options.coverage or options.coverage_xml:
1108 options.coverage = options.coverage_xml = False
1110 from coverage import coverage as _coverage
1111 coverage = _coverage(branch=True)
1116 global CompilationOptions, pyrex_default_options, cython_compile
1117 from Cython.Compiler.Main import \
1118 CompilationOptions, \
1119 default_options as pyrex_default_options, \
1120 compile as cython_compile
1121 from Cython.Compiler import Errors
1122 Errors.LEVEL = 0 # show all warnings
1123 from Cython.Compiler import Options
1124 Options.generate_cleanup_code = 3 # complete cleanup code
1125 from Cython.Compiler import DebugFlags
1126 DebugFlags.debug_temp_code_comments = 1
1129 UNITTEST_MODULE = "Cython"
1130 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1132 if os.path.exists(WORKDIR):
1133 for path in os.listdir(WORKDIR):
1134 if path in ("support", "Cy3"): continue
1135 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1136 if not os.path.exists(WORKDIR):
1137 os.makedirs(WORKDIR)
1139 sys.stderr.write("Python %s\n" % sys.version)
1140 sys.stderr.write("\n")
1142 from Cython.Compiler.Version import version
1143 sys.stderr.write("Running tests against Cython %s\n" % version)
1145 sys.stderr.write("Running tests without Cython.\n")
1147 if options.with_refnanny:
1148 from pyximport.pyxbuild import pyx_to_dll
1149 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1151 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1152 sys.path.insert(0, os.path.split(libpath)[0])
1153 CFLAGS.append("-DCYTHON_REFNANNY=1")
1155 if options.xml_output_dir and options.fork:
1156 # doesn't currently work together
1157 sys.stderr.write("Disabling forked testing to support XML test output\n")
1158 options.fork = False
1160 if WITH_CYTHON and options.language_level == 3:
1161 sys.stderr.write("Using Cython language level 3.\n")
1163 sys.stderr.write("\n")
1167 for ticket_number in options.tickets:
1169 cmd_args.append('.*T%s$' % ticket_number)
1171 for selector in cmd_args:
1172 if selector.startswith('bugs'):
1176 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1178 selectors = [ lambda x:True ]
1180 # Chech which external modules are not present and exclude tests
1181 # which depends on them (by prefix)
1183 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1184 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1185 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1188 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1191 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1193 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1194 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1198 languages.append('c')
1200 languages.append('cpp')
1202 test_suite = unittest.TestSuite()
1204 if options.unittests:
1205 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1207 if options.doctests:
1208 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1210 if options.filetests and languages:
1211 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1212 options.annotate_source, options.cleanup_workdir,
1213 options.cleanup_sharedlibs, options.pyregr,
1214 options.cython_only, languages, test_bugs,
1215 options.fork, options.language_level)
1216 test_suite.addTest(filetests.build_suite())
1218 if options.system_pyregr and languages:
1219 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1220 options.annotate_source, options.cleanup_workdir,
1221 options.cleanup_sharedlibs, True,
1222 options.cython_only, languages, test_bugs,
1223 options.fork, options.language_level)
1225 filetests.handle_directory(
1226 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1229 if options.xml_output_dir:
1230 from Cython.Tests.xmlrunner import XMLTestRunner
1231 test_runner = XMLTestRunner(output=options.xml_output_dir,
1232 verbose=options.verbosity > 0)
1234 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1236 result = test_runner.run(test_suite)
1238 if options.coverage or options.coverage_xml:
1240 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1241 modules = [ module for name, module in sys.modules.items()
1242 if module is not None and
1243 name.startswith('Cython.Compiler.') and
1244 name[len('Cython.Compiler.'):] not in ignored_modules ]
1245 if options.coverage:
1246 coverage.report(modules, show_missing=0)
1247 if options.coverage_xml:
1248 coverage.xml_report(modules, outfile="coverage-report.xml")
1250 if missing_dep_excluder.tests_missing_deps:
1251 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1252 for test in missing_dep_excluder.tests_missing_deps:
1253 sys.stderr.write(" %s\n" % test)
1255 if options.with_refnanny:
1257 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1264 return_code = not result.wasSuccessful()
1267 check_thread_termination(ignore_seen=False)
1268 sys.exit(return_code)
1269 except PendingThreadsError:
1270 # normal program exit won't kill the threads, do it the hard way here
1271 os._exit(return_code)
1273 if __name__ == '__main__':
1276 except SystemExit: # <= Py2.4 ...
1279 traceback.print_exc()
1281 check_thread_termination(ignore_seen=False)
1282 except PendingThreadsError:
1283 # normal program exit won't kill the threads, do it the hard way here