15 from StringIO import StringIO
17 from io import StringIO
20 import cPickle as pickle
26 except ImportError: # No threads, no problems
29 if sys.platform == 'win32':
30 # TODO: Figure out why this hackery (see http://thread.gmane.org/gmane.comp.python.cython.devel/8280/).
31 config_files = distutils_distro.find_config_files()
32 try: config_files.remove('setup.cfg')
33 except ValueError: pass
34 distutils_distro.parse_config_files(config_files)
36 cfgfiles = distutils_distro.find_config_files()
37 try: cfgfiles.remove('setup.cfg')
38 except ValueError: pass
39 distutils_distro.parse_config_files(cfgfiles)
44 from distutils.dist import Distribution
45 from distutils.core import Extension
46 from distutils.command.build_ext import build_ext as _build_ext
47 distutils_distro = Distribution()
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 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 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
200 if not (filename.endswith(".pyx") or filename.endswith(".py")):
202 if filename.startswith('.'): continue # certain emacs backup files
203 if context == 'pyregr' and not filename.startswith('test_'):
205 module = os.path.splitext(filename)[0]
206 fqmodule = "%s.%s" % (context, module)
207 if not [ 1 for match in self.selectors
208 if match(fqmodule) ]:
210 if self.exclude_selectors:
211 if [1 for match in self.exclude_selectors if match(fqmodule)]:
213 if context == 'pyregr':
214 test_class = CythonPyregrTestCase
215 elif context in TEST_RUN_DIRS:
216 if module.startswith("test_"):
217 test_class = CythonUnitTestCase
219 test_class = CythonRunTestCase
221 test_class = CythonCompileTestCase
222 for test in self.build_tests(test_class, path, workdir,
223 module, expect_errors):
225 if context == 'run' and filename.endswith('.py'):
226 # additionally test file in real Python
227 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
230 def build_tests(self, test_class, path, workdir, module, expect_errors):
232 if 'cpp' in module and 'cpp' in self.languages:
235 languages = self.languages[:1]
237 languages = self.languages
238 if 'cpp' in module and 'c' in languages:
239 languages = list(languages)
240 languages.remove('c')
241 tests = [ self.build_test(test_class, path, workdir, module,
242 language, expect_errors)
243 for language in languages ]
246 def build_test(self, test_class, path, workdir, module,
247 language, expect_errors):
248 workdir = os.path.join(workdir, language)
249 if not os.path.exists(workdir):
251 return test_class(path, workdir, module,
253 expect_errors=expect_errors,
254 annotate=self.annotate,
255 cleanup_workdir=self.cleanup_workdir,
256 cleanup_sharedlibs=self.cleanup_sharedlibs,
257 cython_only=self.cython_only,
259 language_level=self.language_level)
261 class CythonCompileTestCase(unittest.TestCase):
262 def __init__(self, test_directory, workdir, module, language='c',
263 expect_errors=False, annotate=False, cleanup_workdir=True,
264 cleanup_sharedlibs=True, cython_only=False, fork=True,
266 self.test_directory = test_directory
267 self.workdir = workdir
269 self.language = language
270 self.expect_errors = expect_errors
271 self.annotate = annotate
272 self.cleanup_workdir = cleanup_workdir
273 self.cleanup_sharedlibs = cleanup_sharedlibs
274 self.cython_only = cython_only
276 self.language_level = language_level
277 unittest.TestCase.__init__(self)
279 def shortDescription(self):
280 return "compiling (%s) %s" % (self.language, self.module)
283 if self.workdir not in sys.path:
284 sys.path.insert(0, self.workdir)
288 sys.path.remove(self.workdir)
292 del sys.modules[self.module]
295 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
296 cleanup_lib_files = self.cleanup_sharedlibs
297 if os.path.exists(self.workdir):
298 for rmfile in os.listdir(self.workdir):
299 if not cleanup_c_files:
300 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
302 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
304 if self.annotate and rmfile.endswith(".html"):
307 rmfile = os.path.join(self.workdir, rmfile)
308 if os.path.isdir(rmfile):
309 shutil.rmtree(rmfile, ignore_errors=True)
315 os.makedirs(self.workdir)
318 self.runCompileTest()
320 def runCompileTest(self):
321 self.compile(self.test_directory, self.module, self.workdir,
322 self.test_directory, self.expect_errors, self.annotate)
324 def find_module_source_file(self, source_file):
325 if not os.path.exists(source_file):
326 source_file = source_file[:-1]
329 def build_target_filename(self, module_name):
330 target = '%s.%s' % (module_name, self.language)
333 def copy_related_files(self, test_directory, target_directory, module_name):
334 is_related = re.compile('%s_.*[.].*' % module_name).match
335 for filename in os.listdir(test_directory):
336 if is_related(filename):
337 shutil.copy(os.path.join(test_directory, filename),
340 def find_source_files(self, workdir, module_name):
341 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
342 return [self.build_target_filename(module_name)] + [
343 filename for filename in os.listdir(workdir)
344 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
346 def split_source_and_output(self, test_directory, module, workdir):
347 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
348 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
350 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
352 for line in source_and_output:
354 if line.startswith("_ERRORS"):
360 source_and_output.close()
362 geterrors = out.geterrors
363 except AttributeError:
369 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
370 extra_compile_options=None):
371 include_dirs = INCLUDE_DIRS[:]
373 include_dirs.append(incdir)
374 source = self.find_module_source_file(
375 os.path.join(test_directory, module + '.pyx'))
376 target = os.path.join(targetdir, self.build_target_filename(module))
378 if extra_compile_options is None:
379 extra_compile_options = {}
384 from Cython.Compiler.Main import CompilationOptions
385 from Cython.Compiler.Main import compile as cython_compile
386 from Cython.Compiler.Main import default_options
388 options = CompilationOptions(
390 include_path = include_dirs,
391 output_file = target,
393 use_listing_file = False,
394 cplus = self.language == 'cpp',
395 language_level = self.language_level,
396 generate_pxi = False,
397 evaluate_tree_assertions = True,
398 **extra_compile_options
400 cython_compile(source, options=options,
401 full_module_name=module)
403 def run_distutils(self, test_directory, module, workdir, incdir,
404 extra_extension_args=None):
408 build_extension = build_ext(distutils_distro)
409 build_extension.include_dirs = INCLUDE_DIRS[:]
411 build_extension.include_dirs.append(incdir)
412 build_extension.finalize_options()
413 ext_include_dirs = []
414 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
416 ext_include_dirs += get_additional_include_dirs()
417 self.copy_related_files(test_directory, workdir, module)
419 if extra_extension_args is None:
420 extra_extension_args = {}
422 extension = Extension(
424 sources = self.find_source_files(workdir, module),
425 include_dirs = ext_include_dirs,
426 extra_compile_args = CFLAGS,
427 **extra_extension_args
429 if self.language == 'cpp':
430 extension.language = 'c++'
431 build_extension.extensions = [extension]
432 build_extension.build_temp = workdir
433 build_extension.build_lib = workdir
434 build_extension.run()
438 def compile(self, test_directory, module, workdir, incdir,
439 expect_errors, annotate):
440 expected_errors = errors = ()
442 expected_errors = self.split_source_and_output(
443 test_directory, module, workdir)
444 test_directory = workdir
447 old_stderr = sys.stderr
449 sys.stderr = ErrorWriter()
450 self.run_cython(test_directory, module, workdir, incdir, annotate)
451 errors = sys.stderr.geterrors()
453 sys.stderr = old_stderr
455 if errors or expected_errors:
457 for expected, error in zip(expected_errors, errors):
458 self.assertEquals(expected, error)
459 if len(errors) < len(expected_errors):
460 expected_error = expected_errors[len(errors)]
461 self.assertEquals(expected_error, None)
462 elif len(errors) > len(expected_errors):
463 unexpected_error = errors[len(expected_errors)]
464 self.assertEquals(None, unexpected_error)
465 except AssertionError:
466 print("\n=== Expected errors: ===")
467 print('\n'.join(expected_errors))
468 print("\n\n=== Got errors: ===")
469 print('\n'.join(errors))
473 if not self.cython_only:
474 self.run_distutils(test_directory, module, workdir, incdir)
476 class CythonRunTestCase(CythonCompileTestCase):
477 def shortDescription(self):
478 return "compiling (%s) and running %s" % (self.language, self.module)
480 def run(self, result=None):
482 result = self.defaultTestResult()
483 result.startTest(self)
487 self.runCompileTest()
488 self.run_tests(result)
490 check_thread_termination()
492 result.addError(self, sys.exc_info())
493 result.stopTest(self)
499 def run_tests(self, result):
500 if not self.cython_only:
501 self.run_doctests(self.module, result)
503 def run_doctests(self, module_name, result):
504 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
505 doctest.DocTestSuite(module_name).run(result)
509 # fork to make sure we do not keep the tested module loaded
510 result_handle, result_file = tempfile.mkstemp()
511 os.close(result_handle)
519 partial_result = PartialTestResult(result)
520 tests = doctest.DocTestSuite(module_name)
521 tests.run(partial_result)
525 # importing failed, try to fake a test class
527 failureException=sys.exc_info()[1],
528 _shortDescription=self.shortDescription(),
530 partial_result.addError(tests, sys.exc_info())
532 output = open(result_file, 'wb')
533 pickle.dump(partial_result.data(), output)
535 traceback.print_exc()
539 os._exit(result_code)
542 cid, result_code = os.waitpid(child_id, 0)
543 # os.waitpid returns the child's result code in the
544 # upper byte of result_code, and the signal it was
545 # killed by in the lower byte
546 if result_code & 255:
547 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
548 (module_name, result_code & 255))
549 result_code = result_code >> 8
550 if result_code in (0,1):
551 input = open(result_file, 'rb')
553 PartialTestResult.join_results(result, pickle.load(input))
557 raise Exception("Tests in module '%s' exited with status %d" %
558 (module_name, result_code))
560 try: os.unlink(result_file)
563 class PureDoctestTestCase(unittest.TestCase):
564 def __init__(self, module_name, module_path):
565 self.module_name = module_name
566 self.module_path = module_path
567 unittest.TestCase.__init__(self, 'run')
569 def shortDescription(self):
570 return "running pure doctests in %s" % self.module_name
572 def run(self, result=None):
574 result = self.defaultTestResult()
575 loaded_module_name = 'pure_doctest__' + self.module_name
576 result.startTest(self)
581 m = imp.load_source(loaded_module_name, self.module_path)
583 doctest.DocTestSuite(m).run(result)
586 if loaded_module_name in sys.modules:
587 del sys.modules[loaded_module_name]
588 check_thread_termination()
590 result.addError(self, sys.exc_info())
591 result.stopTest(self)
597 is_private_field = re.compile('^_[^_]').match
599 class _FakeClass(object):
600 def __init__(self, **kwargs):
601 self._shortDescription = kwargs.get('module_name')
602 self.__dict__.update(kwargs)
603 def shortDescription(self):
604 return self._shortDescription
606 try: # Py2.7+ and Py3.2+
607 from unittest.runner import _TextTestResult
609 from unittest import _TextTestResult
611 class PartialTestResult(_TextTestResult):
612 def __init__(self, base_result):
613 _TextTestResult.__init__(
614 self, self._StringIO(), True,
615 base_result.dots + base_result.showAll*2)
617 def strip_error_results(self, results):
618 for test_case, error in results:
619 for attr_name in filter(is_private_field, dir(test_case)):
620 if attr_name == '_dt_test':
621 test_case._dt_test = _FakeClass(
622 name=test_case._dt_test.name)
623 elif attr_name != '_shortDescription':
624 setattr(test_case, attr_name, None)
627 self.strip_error_results(self.failures)
628 self.strip_error_results(self.errors)
629 return (self.failures, self.errors, self.testsRun,
630 self.stream.getvalue())
632 def join_results(result, data):
633 """Static method for merging the result back into the main
636 failures, errors, tests_run, output = data
638 result.stream.write(output)
639 result.errors.extend(errors)
640 result.failures.extend(failures)
641 result.testsRun += tests_run
643 join_results = staticmethod(join_results)
645 class _StringIO(StringIO):
646 def writeln(self, line):
647 self.write("%s\n" % line)
650 class CythonUnitTestCase(CythonRunTestCase):
651 def shortDescription(self):
652 return "compiling (%s) tests in %s" % (self.language, self.module)
654 def run_tests(self, result):
655 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
658 class CythonPyregrTestCase(CythonRunTestCase):
659 def _run_unittest(self, result, *classes):
660 """Run tests from unittest.TestCase-derived classes."""
661 valid_types = (unittest.TestSuite, unittest.TestCase)
662 suite = unittest.TestSuite()
664 if isinstance(cls, str):
665 if cls in sys.modules:
666 suite.addTest(unittest.findTestCases(sys.modules[cls]))
668 raise ValueError("str arguments must be keys in sys.modules")
669 elif isinstance(cls, valid_types):
672 suite.addTest(unittest.makeSuite(cls))
675 def _run_doctest(self, result, module):
676 self.run_doctests(module, result)
678 def run_tests(self, result):
680 from test import test_support as support
681 except ImportError: # Py3k
682 from test import support
684 def run_unittest(*classes):
685 return self._run_unittest(result, *classes)
686 def run_doctest(module, verbosity=None):
687 return self._run_doctest(result, module)
689 support.run_unittest = run_unittest
690 support.run_doctest = run_doctest
693 module = __import__(self.module)
694 if hasattr(module, 'test_main'):
696 except (unittest.SkipTest, support.ResourceDenied):
697 result.addSkip(self, 'ok')
699 include_debugger = sys.version_info[:2] > (2, 5)
701 def collect_unittests(path, module_prefix, suite, selectors):
702 def file_matches(filename):
703 return filename.startswith("Test") and filename.endswith(".py")
705 def package_matches(dirname):
706 return dirname == "Tests"
708 loader = unittest.TestLoader()
713 cython_dir = os.path.dirname(os.path.abspath(__file__))
714 skipped_dirs = [os.path.join(cython_dir, 'Cython', 'Debugger')]
716 for dirpath, dirnames, filenames in os.walk(path):
717 if dirpath != path and "__init__.py" not in filenames:
718 skipped_dirs.append(dirpath + os.path.sep)
721 for dir in skipped_dirs:
722 if dirpath.startswith(dir):
726 parentname = os.path.split(dirpath)[-1]
727 if package_matches(parentname):
730 filepath = os.path.join(dirpath, f)[:-len(".py")]
731 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
732 if not [ 1 for match in selectors if match(modulename) ]:
734 module = __import__(modulename)
735 for x in modulename.split('.')[1:]:
736 module = getattr(module, x)
737 suite.addTests([loader.loadTestsFromModule(module)])
741 def collect_doctests(path, module_prefix, suite, selectors):
742 def package_matches(dirname):
743 if dirname == 'Debugger' and not include_debugger:
745 return dirname not in ("Mac", "Distutils", "Plex")
746 def file_matches(filename):
747 filename, ext = os.path.splitext(filename)
748 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
750 return (ext == '.py' and not
751 '~' in filename and not
752 '#' in filename and not
753 filename.startswith('.') and not
754 filename in blacklist)
755 import doctest, types
756 for dirpath, dirnames, filenames in os.walk(path):
757 for dir in list(dirnames):
758 if not package_matches(dir):
762 if not f.endswith('.py'): continue
763 filepath = os.path.join(dirpath, f)
764 if os.path.getsize(filepath) == 0: continue
765 filepath = filepath[:-len(".py")]
766 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
767 if not [ 1 for match in selectors if match(modulename) ]:
769 if 'in_gdb' in modulename:
770 # These should only be imported from gdb.
772 module = __import__(modulename)
773 for x in modulename.split('.')[1:]:
774 module = getattr(module, x)
775 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
777 suite.addTest(doctest.DocTestSuite(module))
778 except ValueError: # no tests
782 class EndToEndTest(unittest.TestCase):
784 This is a test of build/*.srctree files, where srctree defines a full
785 directory structure and its header gives a list of commands to run.
787 cython_root = os.path.dirname(os.path.abspath(__file__))
789 def __init__(self, treefile, workdir, cleanup_workdir=True):
790 self.treefile = treefile
791 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
792 self.cleanup_workdir = cleanup_workdir
793 cython_syspath = self.cython_root
794 for path in sys.path[::-1]:
795 if path.startswith(self.cython_root):
796 # Py3 installation and refnanny build prepend their
797 # fixed paths to sys.path => prefer that over the
799 cython_syspath = path + os.pathsep + cython_syspath
800 self.cython_syspath = cython_syspath
801 unittest.TestCase.__init__(self)
803 def shortDescription(self):
804 return "End-to-end %s" % self.treefile
807 from Cython.TestUtils import unpack_source_tree
808 _, self.commands = unpack_source_tree(
809 os.path.join('tests', 'build', self.treefile), self.workdir)
810 self.old_dir = os.getcwd()
811 os.chdir(self.workdir)
812 if self.workdir not in sys.path:
813 sys.path.insert(0, self.workdir)
816 if self.cleanup_workdir:
817 shutil.rmtree(self.workdir)
818 os.chdir(self.old_dir)
821 commands = (self.commands
822 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
823 .replace("PYTHON", sys.executable))
825 old_path = os.environ.get('PYTHONPATH')
826 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
827 for command in commands.split('\n'):
828 if sys.version_info[:2] >= (2,4):
830 p = subprocess.Popen(commands,
831 stderr=subprocess.PIPE,
832 stdout=subprocess.PIPE,
834 out, err = p.communicate()
841 res = os.system(command)
842 self.assertEqual(0, res, "non-zero exit status")
845 os.environ['PYTHONPATH'] = old_path
847 del os.environ['PYTHONPATH']
850 # TODO: Support cython_freeze needed here as well.
851 # TODO: Windows support.
853 class EmbedTest(unittest.TestCase):
855 working_dir = "Demos/embed"
858 self.old_dir = os.getcwd()
859 os.chdir(self.working_dir)
861 "make PYTHON='%s' clean > /dev/null" % sys.executable)
866 "make PYTHON='%s' clean > /dev/null" % sys.executable)
869 os.chdir(self.old_dir)
871 def test_embed(self):
872 from distutils import sysconfig
873 libname = sysconfig.get_config_var('LIBRARY')
874 libdir = sysconfig.get_config_var('LIBDIR')
875 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
876 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
877 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
878 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
879 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
880 # report the error for the original directory
881 libdir = sysconfig.get_config_var('LIBDIR')
882 self.assert_(os.system(
883 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
885 os.remove('make.output')
889 class MissingDependencyExcluder:
890 def __init__(self, deps):
891 # deps: { module name : matcher func }
892 self.exclude_matchers = []
893 for mod, matcher in deps.items():
897 self.exclude_matchers.append(matcher)
898 self.tests_missing_deps = []
899 def __call__(self, testname):
900 for matcher in self.exclude_matchers:
901 if matcher(testname):
902 self.tests_missing_deps.append(testname)
906 class VersionDependencyExcluder:
907 def __init__(self, deps):
908 # deps: { version : matcher func }
909 from sys import version_info
910 self.exclude_matchers = []
911 for ver, (compare, matcher) in deps.items():
912 if compare(version_info, ver):
913 self.exclude_matchers.append(matcher)
914 self.tests_missing_deps = []
915 def __call__(self, testname):
916 for matcher in self.exclude_matchers:
917 if matcher(testname):
918 self.tests_missing_deps.append(testname)
922 class FileListExcluder:
924 def __init__(self, list_file):
928 for line in f.readlines():
930 if line and line[0] != '#':
931 self.excludes[line.split()[0]] = True
935 def __call__(self, testname):
936 return testname in self.excludes or testname.split('.')[-1] in self.excludes
938 def refactor_for_py3(distdir, cy3_dir):
939 # need to convert Cython sources first
940 import lib2to3.refactor
941 from distutils.util import copydir_run_2to3
942 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
943 if fix.split('fix_')[-1] not in ('next',)
945 if not os.path.exists(cy3_dir):
947 import distutils.log as dlog
948 dlog.set_threshold(dlog.INFO)
949 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
953 recursive-exclude Cython *
954 recursive-include Cython *.py *.pyx *.pxd
955 recursive-include Cython/Debugger/Tests *
958 sys.path.insert(0, cy3_dir)
960 for keep_2x_file in KEEP_2X_FILES:
961 destfile = os.path.join(cy3_dir, keep_2x_file)
962 shutil.copy(keep_2x_file, destfile)
964 class PendingThreadsError(RuntimeError):
969 def check_thread_termination(ignore_seen=True):
970 if threading is None: # no threading enabled in CPython
972 current = threading.currentThread()
973 blocking_threads = []
974 for t in threading.enumerate():
975 if not t.isAlive() or t == current:
980 blocking_threads.append(t)
982 for seen in threads_seen:
986 threads_seen.append(t)
987 blocking_threads.append(t)
988 if not blocking_threads:
990 sys.stderr.write("warning: left-over threads found after running test:\n")
991 for t in blocking_threads:
992 sys.stderr.write('...%s\n' % repr(t))
993 raise PendingThreadsError("left-over threads found after running test")
996 from optparse import OptionParser
997 parser = OptionParser()
998 parser.add_option("--no-cleanup", dest="cleanup_workdir",
999 action="store_false", default=True,
1000 help="do not delete the generated C files (allows passing --no-cython on next run)")
1001 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1002 action="store_false", default=True,
1003 help="do not delete the generated shared libary files (allows manual module experimentation)")
1004 parser.add_option("--no-cython", dest="with_cython",
1005 action="store_false", default=True,
1006 help="do not run the Cython compiler, only the C compiler")
1007 parser.add_option("--no-c", dest="use_c",
1008 action="store_false", default=True,
1009 help="do not test C compilation")
1010 parser.add_option("--no-cpp", dest="use_cpp",
1011 action="store_false", default=True,
1012 help="do not test C++ compilation")
1013 parser.add_option("--no-unit", dest="unittests",
1014 action="store_false", default=True,
1015 help="do not run the unit tests")
1016 parser.add_option("--no-doctest", dest="doctests",
1017 action="store_false", default=True,
1018 help="do not run the doctests")
1019 parser.add_option("--no-file", dest="filetests",
1020 action="store_false", default=True,
1021 help="do not run the file based tests")
1022 parser.add_option("--no-pyregr", dest="pyregr",
1023 action="store_false", default=True,
1024 help="do not run the regression tests of CPython in tests/pyregr/")
1025 parser.add_option("--cython-only", dest="cython_only",
1026 action="store_true", default=False,
1027 help="only compile pyx to c, do not run C compiler or run the tests")
1028 parser.add_option("--no-refnanny", dest="with_refnanny",
1029 action="store_false", default=True,
1030 help="do not regression test reference counting")
1031 parser.add_option("--no-fork", dest="fork",
1032 action="store_false", default=True,
1033 help="do not fork to run tests")
1034 parser.add_option("--sys-pyregr", dest="system_pyregr",
1035 action="store_true", default=False,
1036 help="run the regression tests of the CPython installation")
1037 parser.add_option("-x", "--exclude", dest="exclude",
1038 action="append", metavar="PATTERN",
1039 help="exclude tests matching the PATTERN")
1040 parser.add_option("-C", "--coverage", dest="coverage",
1041 action="store_true", default=False,
1042 help="collect source coverage data for the Compiler")
1043 parser.add_option("--coverage-xml", dest="coverage_xml",
1044 action="store_true", default=False,
1045 help="collect source coverage data for the Compiler in XML format")
1046 parser.add_option("-A", "--annotate", dest="annotate_source",
1047 action="store_true", default=True,
1048 help="generate annotated HTML versions of the test source files")
1049 parser.add_option("--no-annotate", dest="annotate_source",
1050 action="store_false",
1051 help="do not generate annotated HTML versions of the test source files")
1052 parser.add_option("-v", "--verbose", dest="verbosity",
1053 action="count", default=0,
1054 help="display test progress, pass twice to print test names")
1055 parser.add_option("-T", "--ticket", dest="tickets",
1057 help="a bug ticket number to run the respective test in 'tests/*'")
1058 parser.add_option("-3", dest="language_level",
1059 action="store_const", const=3, default=2,
1060 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1061 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1062 help="write test results in XML to directory DIR")
1063 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1064 action="store_true",
1065 help="exit without error code even on test failures")
1067 options, cmd_args = parser.parse_args()
1069 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1070 ROOTDIR = os.path.join(DISTDIR, 'tests')
1071 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
1073 if sys.version_info[0] >= 3:
1074 options.doctests = False
1075 if options.with_cython:
1077 # try if Cython is installed in a Py3 version
1078 import Cython.Compiler.Main
1080 # back out anything the import process loaded, then
1081 # 2to3 the Cython sources to make them re-importable
1082 cy_modules = [ name for name in sys.modules
1083 if name == 'Cython' or name.startswith('Cython.') ]
1084 for name in cy_modules:
1085 del sys.modules[name]
1086 # hasn't been refactored yet - do it now
1087 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1088 if sys.version_info >= (3,1):
1089 refactor_for_py3(DISTDIR, cy3_dir)
1090 elif os.path.isdir(cy3_dir):
1091 sys.path.insert(0, cy3_dir)
1093 options.with_cython = False
1095 WITH_CYTHON = options.with_cython
1097 if options.coverage or options.coverage_xml:
1099 options.coverage = options.coverage_xml = False
1101 from coverage import coverage as _coverage
1102 coverage = _coverage(branch=True)
1107 global CompilationOptions, pyrex_default_options, cython_compile
1108 from Cython.Compiler.Main import \
1109 CompilationOptions, \
1110 default_options as pyrex_default_options, \
1111 compile as cython_compile
1112 from Cython.Compiler import Errors
1113 Errors.LEVEL = 0 # show all warnings
1114 from Cython.Compiler import Options
1115 Options.generate_cleanup_code = 3 # complete cleanup code
1116 from Cython.Compiler import DebugFlags
1117 DebugFlags.debug_temp_code_comments = 1
1120 UNITTEST_MODULE = "Cython"
1121 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1123 if os.path.exists(WORKDIR):
1124 for path in os.listdir(WORKDIR):
1125 if path in ("support", "Cy3"): continue
1126 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1127 if not os.path.exists(WORKDIR):
1128 os.makedirs(WORKDIR)
1130 sys.stderr.write("Python %s\n" % sys.version)
1131 sys.stderr.write("\n")
1133 from Cython.Compiler.Version import version
1134 sys.stderr.write("Running tests against Cython %s\n" % version)
1136 sys.stderr.write("Running tests without Cython.\n")
1138 if options.with_refnanny:
1139 from pyximport.pyxbuild import pyx_to_dll
1140 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1142 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1143 sys.path.insert(0, os.path.split(libpath)[0])
1144 CFLAGS.append("-DCYTHON_REFNANNY=1")
1146 if options.xml_output_dir and options.fork:
1147 # doesn't currently work together
1148 sys.stderr.write("Disabling forked testing to support XML test output\n")
1149 options.fork = False
1151 if WITH_CYTHON and options.language_level == 3:
1152 sys.stderr.write("Using Cython language level 3.\n")
1154 sys.stderr.write("\n")
1158 for ticket_number in options.tickets:
1160 cmd_args.append('.*T%s$' % ticket_number)
1162 for selector in cmd_args:
1163 if selector.startswith('bugs'):
1167 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1169 selectors = [ lambda x:True ]
1171 # Chech which external modules are not present and exclude tests
1172 # which depends on them (by prefix)
1174 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1175 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1176 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1179 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1182 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1184 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1185 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1189 languages.append('c')
1191 languages.append('cpp')
1193 test_suite = unittest.TestSuite()
1195 if options.unittests:
1196 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1198 if options.doctests:
1199 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1201 if options.filetests and languages:
1202 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1203 options.annotate_source, options.cleanup_workdir,
1204 options.cleanup_sharedlibs, options.pyregr,
1205 options.cython_only, languages, test_bugs,
1206 options.fork, options.language_level)
1207 test_suite.addTest(filetests.build_suite())
1209 if options.system_pyregr and languages:
1210 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1211 options.annotate_source, options.cleanup_workdir,
1212 options.cleanup_sharedlibs, True,
1213 options.cython_only, languages, test_bugs,
1214 options.fork, options.language_level)
1216 filetests.handle_directory(
1217 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1220 if options.xml_output_dir:
1221 from Cython.Tests.xmlrunner import XMLTestRunner
1222 test_runner = XMLTestRunner(output=options.xml_output_dir,
1223 verbose=options.verbosity > 0)
1225 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1227 result = test_runner.run(test_suite)
1229 if options.coverage or options.coverage_xml:
1231 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1232 modules = [ module for name, module in sys.modules.items()
1233 if module is not None and
1234 name.startswith('Cython.Compiler.') and
1235 name[len('Cython.Compiler.'):] not in ignored_modules ]
1236 if options.coverage:
1237 coverage.report(modules, show_missing=0)
1238 if options.coverage_xml:
1239 coverage.xml_report(modules, outfile="coverage-report.xml")
1241 if missing_dep_excluder.tests_missing_deps:
1242 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1243 for test in missing_dep_excluder.tests_missing_deps:
1244 sys.stderr.write(" %s\n" % test)
1246 if options.with_refnanny:
1248 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1255 return_code = not result.wasSuccessful()
1258 check_thread_termination(ignore_seen=False)
1259 sys.exit(return_code)
1260 except PendingThreadsError:
1261 # normal program exit won't kill the threads, do it the hard way here
1262 os._exit(return_code)
1264 if __name__ == '__main__':
1267 except SystemExit: # <= Py2.4 ...
1270 traceback.print_exc()
1272 check_thread_termination(ignore_seen=False)
1273 except PendingThreadsError:
1274 # normal program exit won't kill the threads, do it the hard way here