14 from StringIO import StringIO
16 from io import StringIO
19 import cPickle as pickle
25 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 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr', 'build']
37 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
39 # Lists external modules, and a matcher matching tests
40 # which should be excluded if the module is not present.
42 'numpy' : re.compile('.*\.numpy_.*').match,
43 'pstats' : re.compile('.*\.pstats_.*').match,
44 'posix' : re.compile('.*\.posix_.*').match,
47 def get_numpy_include_dirs():
49 return [numpy.get_include()]
52 # test name matcher , callable returning list
53 (re.compile('numpy_.*').match, get_numpy_include_dirs),
57 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
58 # (2,4) : (operator.le, ...) excludes ... when PyVer <= 2.4.x
59 (2,5) : (operator.lt, lambda x: x in ['run.any',
62 (2,4) : (operator.le, lambda x: x in ['run.extern_builtins_T258'
64 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
67 # The next line should start (3,); but this is a dictionary, so
68 # we can only have one (3,) key. Since 2.7 is supposed to be the
69 # last 2.x release, things would have to change drastically for this
71 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
72 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
73 'compile.extsetslice',
74 'compile.extdelslice',
75 'run.special_methods_T561_py2']),
78 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
79 CFLAGS = os.getenv('CFLAGS', '').split()
81 class build_ext(_build_ext):
82 def build_extension(self, ext):
83 if ext.language == 'c++':
85 try: # Py2.7+ & Py3.2+
86 compiler_obj = self.compiler_obj
87 except AttributeError:
88 compiler_obj = self.compiler
89 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
92 _build_ext.build_extension(self, ext)
94 class ErrorWriter(object):
95 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
98 self.write = self.output.append
100 def _collect(self, collect_errors, collect_warnings):
101 s = ''.join(self.output)
103 for line in s.split('\n'):
104 match = self.match_error(line)
106 is_warning, line, column, message = match.groups()
107 if (is_warning and collect_warnings) or \
108 (not is_warning and collect_errors):
109 result.append( (int(line), int(column), message.strip()) )
111 return [ "%d:%d: %s" % values for values in result ]
114 return self._collect(True, False)
116 def getwarnings(self):
117 return self._collect(False, True)
120 return self._collect(True, True)
122 class TestBuilder(object):
123 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
124 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
125 languages, test_bugs, fork, language_level):
126 self.rootdir = rootdir
127 self.workdir = workdir
128 self.selectors = selectors
129 self.exclude_selectors = exclude_selectors
130 self.annotate = annotate
131 self.cleanup_workdir = cleanup_workdir
132 self.cleanup_sharedlibs = cleanup_sharedlibs
133 self.with_pyregr = with_pyregr
134 self.cython_only = cython_only
135 self.languages = languages
136 self.test_bugs = test_bugs
138 self.language_level = language_level
140 def build_suite(self):
141 suite = unittest.TestSuite()
142 test_dirs = TEST_DIRS
143 filenames = os.listdir(self.rootdir)
145 for filename in filenames:
146 if not WITH_CYTHON and filename == "errors":
147 # we won't get any errors without running Cython
149 path = os.path.join(self.rootdir, filename)
150 if os.path.isdir(path) and filename in test_dirs:
151 if filename == 'pyregr' and not self.with_pyregr:
154 self.handle_directory(path, filename))
155 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
156 # Non-Windows makefile, can't run Cython under Py3.
157 if [1 for selector in self.selectors if selector("embedded")]:
158 suite.addTest(unittest.makeSuite(EmbedTest))
161 def handle_directory(self, path, context):
162 workdir = os.path.join(self.workdir, context)
163 if not os.path.exists(workdir):
166 expect_errors = (context == 'errors')
167 suite = unittest.TestSuite()
168 filenames = os.listdir(path)
170 for filename in filenames:
171 if context == "build" and filename.endswith(".srctree"):
172 if not [ 1 for match in self.selectors if match(filename) ]:
174 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
176 if not (filename.endswith(".pyx") or filename.endswith(".py")):
178 if filename.startswith('.'): continue # certain emacs backup files
179 if context == 'pyregr' and not filename.startswith('test_'):
181 module = os.path.splitext(filename)[0]
182 fqmodule = "%s.%s" % (context, module)
183 if not [ 1 for match in self.selectors
184 if match(fqmodule) ]:
186 if self.exclude_selectors:
187 if [1 for match in self.exclude_selectors if match(fqmodule)]:
189 if context in TEST_RUN_DIRS:
190 if module.startswith("test_"):
191 test_class = CythonUnitTestCase
193 test_class = CythonRunTestCase
195 test_class = CythonCompileTestCase
196 for test in self.build_tests(test_class, path, workdir,
197 module, expect_errors):
199 if context == 'run' and filename.endswith('.py'):
200 # additionally test file in real Python
201 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
204 def build_tests(self, test_class, path, workdir, module, expect_errors):
206 if 'cpp' in module and 'cpp' in self.languages:
209 languages = self.languages[:1]
211 languages = self.languages
212 if 'cpp' in module and 'c' in languages:
213 languages = list(languages)
214 languages.remove('c')
215 tests = [ self.build_test(test_class, path, workdir, module,
216 language, expect_errors)
217 for language in languages ]
220 def build_test(self, test_class, path, workdir, module,
221 language, expect_errors):
222 workdir = os.path.join(workdir, language)
223 if not os.path.exists(workdir):
225 return test_class(path, workdir, module,
227 expect_errors=expect_errors,
228 annotate=self.annotate,
229 cleanup_workdir=self.cleanup_workdir,
230 cleanup_sharedlibs=self.cleanup_sharedlibs,
231 cython_only=self.cython_only,
233 language_level=self.language_level)
235 class CythonCompileTestCase(unittest.TestCase):
236 def __init__(self, test_directory, workdir, module, language='c',
237 expect_errors=False, annotate=False, cleanup_workdir=True,
238 cleanup_sharedlibs=True, cython_only=False, fork=True,
240 self.test_directory = test_directory
241 self.workdir = workdir
243 self.language = language
244 self.expect_errors = expect_errors
245 self.annotate = annotate
246 self.cleanup_workdir = cleanup_workdir
247 self.cleanup_sharedlibs = cleanup_sharedlibs
248 self.cython_only = cython_only
250 self.language_level = language_level
251 unittest.TestCase.__init__(self)
253 def shortDescription(self):
254 return "compiling (%s) %s" % (self.language, self.module)
257 if self.workdir not in sys.path:
258 sys.path.insert(0, self.workdir)
262 sys.path.remove(self.workdir)
266 del sys.modules[self.module]
269 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
270 cleanup_lib_files = self.cleanup_sharedlibs
271 if os.path.exists(self.workdir):
272 for rmfile in os.listdir(self.workdir):
273 if not cleanup_c_files:
274 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
276 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
278 if self.annotate and rmfile.endswith(".html"):
281 rmfile = os.path.join(self.workdir, rmfile)
282 if os.path.isdir(rmfile):
283 shutil.rmtree(rmfile, ignore_errors=True)
289 os.makedirs(self.workdir)
292 self.runCompileTest()
294 def runCompileTest(self):
295 self.compile(self.test_directory, self.module, self.workdir,
296 self.test_directory, self.expect_errors, self.annotate)
298 def find_module_source_file(self, source_file):
299 if not os.path.exists(source_file):
300 source_file = source_file[:-1]
303 def build_target_filename(self, module_name):
304 target = '%s.%s' % (module_name, self.language)
307 def copy_related_files(self, test_directory, target_directory, module_name):
308 is_related = re.compile('%s_.*[.].*' % module_name).match
309 for filename in os.listdir(test_directory):
310 if is_related(filename):
311 shutil.copy(os.path.join(test_directory, filename),
314 def find_source_files(self, workdir, module_name):
315 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
316 return [self.build_target_filename(module_name)] + [
317 filename for filename in os.listdir(workdir)
318 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
320 def split_source_and_output(self, test_directory, module, workdir):
321 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
322 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
324 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
326 for line in source_and_output:
328 if line.startswith("_ERRORS"):
334 source_and_output.close()
336 geterrors = out.geterrors
337 except AttributeError:
343 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
344 include_dirs = INCLUDE_DIRS[:]
346 include_dirs.append(incdir)
347 source = self.find_module_source_file(
348 os.path.join(test_directory, module + '.pyx'))
349 target = os.path.join(targetdir, self.build_target_filename(module))
350 options = CompilationOptions(
351 pyrex_default_options,
352 include_path = include_dirs,
353 output_file = target,
355 use_listing_file = False,
356 cplus = self.language == 'cpp',
357 language_level = self.language_level,
358 generate_pxi = False,
359 evaluate_tree_assertions = True,
361 cython_compile(source, options=options,
362 full_module_name=module)
364 def run_distutils(self, test_directory, module, workdir, incdir):
368 build_extension = build_ext(distutils_distro)
369 build_extension.include_dirs = INCLUDE_DIRS[:]
371 build_extension.include_dirs.append(incdir)
372 build_extension.finalize_options()
373 ext_include_dirs = []
374 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
376 ext_include_dirs += get_additional_include_dirs()
377 self.copy_related_files(test_directory, workdir, module)
378 extension = Extension(
380 sources = self.find_source_files(workdir, module),
381 include_dirs = ext_include_dirs,
382 extra_compile_args = CFLAGS,
384 if self.language == 'cpp':
385 extension.language = 'c++'
386 build_extension.extensions = [extension]
387 build_extension.build_temp = workdir
388 build_extension.build_lib = workdir
389 build_extension.run()
393 def compile(self, test_directory, module, workdir, incdir,
394 expect_errors, annotate):
395 expected_errors = errors = ()
397 expected_errors = self.split_source_and_output(
398 test_directory, module, workdir)
399 test_directory = workdir
402 old_stderr = sys.stderr
404 sys.stderr = ErrorWriter()
405 self.run_cython(test_directory, module, workdir, incdir, annotate)
406 errors = sys.stderr.geterrors()
408 sys.stderr = old_stderr
410 if errors or expected_errors:
412 for expected, error in zip(expected_errors, errors):
413 self.assertEquals(expected, error)
414 if len(errors) < len(expected_errors):
415 expected_error = expected_errors[len(errors)]
416 self.assertEquals(expected_error, None)
417 elif len(errors) > len(expected_errors):
418 unexpected_error = errors[len(expected_errors)]
419 self.assertEquals(None, unexpected_error)
420 except AssertionError:
421 print("\n=== Expected errors: ===")
422 print('\n'.join(expected_errors))
423 print("\n\n=== Got errors: ===")
424 print('\n'.join(errors))
428 if not self.cython_only:
429 self.run_distutils(test_directory, module, workdir, incdir)
431 class CythonRunTestCase(CythonCompileTestCase):
432 def shortDescription(self):
433 return "compiling (%s) and running %s" % (self.language, self.module)
435 def run(self, result=None):
437 result = self.defaultTestResult()
438 result.startTest(self)
442 self.runCompileTest()
443 if not self.cython_only:
444 self.run_doctests(self.module, result)
446 check_thread_termination()
448 result.addError(self, sys.exc_info())
449 result.stopTest(self)
455 def run_doctests(self, module_name, result):
456 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
457 doctest.DocTestSuite(module_name).run(result)
461 # fork to make sure we do not keep the tested module loaded
462 result_handle, result_file = tempfile.mkstemp()
463 os.close(result_handle)
471 partial_result = PartialTestResult(result)
472 tests = doctest.DocTestSuite(module_name)
473 tests.run(partial_result)
477 # importing failed, try to fake a test class
479 failureException=sys.exc_info()[1],
480 _shortDescription=self.shortDescription(),
482 partial_result.addError(tests, sys.exc_info())
484 output = open(result_file, 'wb')
485 pickle.dump(partial_result.data(), output)
488 traceback.print_exc()
492 os._exit(result_code)
495 cid, result_code = os.waitpid(child_id, 0)
496 # os.waitpid returns the child's result code in the
497 # upper byte of result_code, and the signal it was
498 # killed by in the lower byte
499 if result_code & 255:
500 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
501 (module_name, result_code & 255))
502 result_code = result_code >> 8
503 if result_code in (0,1):
504 input = open(result_file, 'rb')
506 PartialTestResult.join_results(result, pickle.load(input))
510 raise Exception("Tests in module '%s' exited with status %d" %
511 (module_name, result_code))
513 try: os.unlink(result_file)
516 class PureDoctestTestCase(unittest.TestCase):
517 def __init__(self, module_name, module_path):
518 self.module_name = module_name
519 self.module_path = module_path
520 unittest.TestCase.__init__(self, 'run')
522 def shortDescription(self):
523 return "running pure doctests in %s" % self.module_name
525 def run(self, result=None):
527 result = self.defaultTestResult()
528 loaded_module_name = 'pure_doctest__' + self.module_name
529 result.startTest(self)
534 m = imp.load_source(loaded_module_name, self.module_path)
536 doctest.DocTestSuite(m).run(result)
539 if loaded_module_name in sys.modules:
540 del sys.modules[loaded_module_name]
541 check_thread_termination()
543 result.addError(self, sys.exc_info())
544 result.stopTest(self)
550 is_private_field = re.compile('^_[^_]').match
552 class _FakeClass(object):
553 def __init__(self, **kwargs):
554 self._shortDescription = kwargs.get('module_name')
555 self.__dict__.update(kwargs)
556 def shortDescription(self):
557 return self._shortDescription
559 try: # Py2.7+ and Py3.2+
560 from unittest.runner import _TextTestResult
562 from unittest import _TextTestResult
564 class PartialTestResult(_TextTestResult):
565 def __init__(self, base_result):
566 _TextTestResult.__init__(
567 self, self._StringIO(), True,
568 base_result.dots + base_result.showAll*2)
570 def strip_error_results(self, results):
571 for test_case, error in results:
572 for attr_name in filter(is_private_field, dir(test_case)):
573 if attr_name == '_dt_test':
574 test_case._dt_test = _FakeClass(
575 name=test_case._dt_test.name)
576 elif attr_name != '_shortDescription':
577 setattr(test_case, attr_name, None)
580 self.strip_error_results(self.failures)
581 self.strip_error_results(self.errors)
582 return (self.failures, self.errors, self.testsRun,
583 self.stream.getvalue())
585 def join_results(result, data):
586 """Static method for merging the result back into the main
589 failures, errors, tests_run, output = data
591 result.stream.write(output)
592 result.errors.extend(errors)
593 result.failures.extend(failures)
594 result.testsRun += tests_run
596 join_results = staticmethod(join_results)
598 class _StringIO(StringIO):
599 def writeln(self, line):
600 self.write("%s\n" % line)
603 class CythonUnitTestCase(CythonCompileTestCase):
604 def shortDescription(self):
605 return "compiling (%s) tests in %s" % (self.language, self.module)
607 def run(self, result=None):
609 result = self.defaultTestResult()
610 result.startTest(self)
614 self.runCompileTest()
615 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
617 check_thread_termination()
619 result.addError(self, sys.exc_info())
620 result.stopTest(self)
626 def collect_unittests(path, module_prefix, suite, selectors):
627 def file_matches(filename):
628 return filename.startswith("Test") and filename.endswith(".py")
630 def package_matches(dirname):
631 return dirname == "Tests"
633 loader = unittest.TestLoader()
637 for dirpath, dirnames, filenames in os.walk(path):
638 if dirpath != path and "__init__.py" not in filenames:
639 skipped_dirs.append(dirpath + os.path.sep)
642 for dir in skipped_dirs:
643 if dirpath.startswith(dir):
647 parentname = os.path.split(dirpath)[-1]
648 if package_matches(parentname):
651 filepath = os.path.join(dirpath, f)[:-len(".py")]
652 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
653 if not [ 1 for match in selectors if match(modulename) ]:
655 module = __import__(modulename)
656 for x in modulename.split('.')[1:]:
657 module = getattr(module, x)
658 suite.addTests([loader.loadTestsFromModule(module)])
660 def collect_doctests(path, module_prefix, suite, selectors):
661 def package_matches(dirname):
662 return dirname not in ("Mac", "Distutils", "Plex")
663 def file_matches(filename):
664 return (filename.endswith(".py") and not ('~' in filename
665 or '#' in filename or filename.startswith('.')))
666 import doctest, types
667 for dirpath, dirnames, filenames in os.walk(path):
668 parentname = os.path.split(dirpath)[-1]
669 if package_matches(parentname):
672 if not f.endswith('.py'): continue
673 filepath = os.path.join(dirpath, f)
674 if os.path.getsize(filepath) == 0: continue
675 if 'no doctest' in open(filepath).next(): continue
676 filepath = filepath[:-len(".py")]
677 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
678 if not [ 1 for match in selectors if match(modulename) ]:
680 module = __import__(modulename)
681 for x in modulename.split('.')[1:]:
682 module = getattr(module, x)
683 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
685 suite.addTest(doctest.DocTestSuite(module))
686 except ValueError: # no tests
690 class EndToEndTest(unittest.TestCase):
692 This is a test of build/*.srctree files, where srctree defines a full
693 directory structure and its header gives a list of commands to run.
695 cython_root = os.path.dirname(os.path.abspath(__file__))
697 def __init__(self, treefile, workdir, cleanup_workdir=True):
698 self.treefile = treefile
699 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
700 self.cleanup_workdir = cleanup_workdir
701 cython_syspath = self.cython_root
702 for path in sys.path[::-1]:
703 if path.startswith(self.cython_root):
704 # Py3 installation and refnanny build prepend their
705 # fixed paths to sys.path => prefer that over the
707 cython_syspath = path + os.pathsep + cython_syspath
708 self.cython_syspath = cython_syspath
709 unittest.TestCase.__init__(self)
711 def shortDescription(self):
712 return "End-to-end %s" % self.treefile
715 from Cython.TestUtils import unpack_source_tree
716 _, self.commands = unpack_source_tree(os.path.join('tests', 'build', self.treefile), self.workdir)
717 self.old_dir = os.getcwd()
718 os.chdir(self.workdir)
719 if self.workdir not in sys.path:
720 sys.path.insert(0, self.workdir)
723 if self.cleanup_workdir:
724 shutil.rmtree(self.workdir)
725 os.chdir(self.old_dir)
728 commands = (self.commands
729 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
730 .replace("PYTHON", sys.executable))
731 old_path = os.environ.get('PYTHONPATH')
733 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + (old_path or '')
734 print(os.environ['PYTHONPATH'])
735 self.assertEqual(0, os.system(commands))
738 os.environ['PYTHONPATH'] = old_path
740 del os.environ['PYTHONPATH']
743 # TODO: Support cython_freeze needed here as well.
744 # TODO: Windows support.
746 class EmbedTest(unittest.TestCase):
748 working_dir = "Demos/embed"
751 self.old_dir = os.getcwd()
752 os.chdir(self.working_dir)
754 "make PYTHON='%s' clean > /dev/null" % sys.executable)
759 "make PYTHON='%s' clean > /dev/null" % sys.executable)
762 os.chdir(self.old_dir)
764 def test_embed(self):
765 from distutils import sysconfig
766 libname = sysconfig.get_config_var('LIBRARY')
767 libdir = sysconfig.get_config_var('LIBDIR')
768 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
769 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
770 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
771 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
772 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
773 # report the error for the original directory
774 libdir = sysconfig.get_config_var('LIBDIR')
775 self.assert_(os.system(
776 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
778 os.remove('make.output')
782 class MissingDependencyExcluder:
783 def __init__(self, deps):
784 # deps: { module name : matcher func }
785 self.exclude_matchers = []
786 for mod, matcher in deps.items():
790 self.exclude_matchers.append(matcher)
791 self.tests_missing_deps = []
792 def __call__(self, testname):
793 for matcher in self.exclude_matchers:
794 if matcher(testname):
795 self.tests_missing_deps.append(testname)
799 class VersionDependencyExcluder:
800 def __init__(self, deps):
801 # deps: { version : matcher func }
802 from sys import version_info
803 self.exclude_matchers = []
804 for ver, (compare, matcher) in deps.items():
805 if compare(version_info, ver):
806 self.exclude_matchers.append(matcher)
807 self.tests_missing_deps = []
808 def __call__(self, testname):
809 for matcher in self.exclude_matchers:
810 if matcher(testname):
811 self.tests_missing_deps.append(testname)
815 class FileListExcluder:
817 def __init__(self, list_file):
821 for line in f.readlines():
823 if line and line[0] != '#':
824 self.excludes[line.split()[0]] = True
828 def __call__(self, testname):
829 return testname in self.excludes or testname.split('.')[-1] in self.excludes
831 def refactor_for_py3(distdir, cy3_dir):
832 # need to convert Cython sources first
833 import lib2to3.refactor
834 from distutils.util import copydir_run_2to3
835 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
836 if fix.split('fix_')[-1] not in ('next',)
838 if not os.path.exists(cy3_dir):
840 import distutils.log as dlog
841 dlog.set_threshold(dlog.INFO)
842 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
846 recursive-exclude Cython *
847 recursive-include Cython *.py *.pyx *.pxd
849 sys.path.insert(0, cy3_dir)
851 def check_thread_termination():
852 if threading is None: # no threading enabled in CPython
854 current = threading.currentThread()
855 blocking_threads = []
856 for t in threading.enumerate():
857 if not t.isAlive() or t == current:
861 blocking_threads.append(t)
862 if not blocking_threads:
864 sys.stderr.write("warning: left-over threads found after running test:\n")
865 for t in blocking_threads:
866 sys.stderr.write('...%s\n' % repr(t))
867 raise RuntimeError("left-over threads found after running test")
869 if __name__ == '__main__':
870 from optparse import OptionParser
871 parser = OptionParser()
872 parser.add_option("--no-cleanup", dest="cleanup_workdir",
873 action="store_false", default=True,
874 help="do not delete the generated C files (allows passing --no-cython on next run)")
875 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
876 action="store_false", default=True,
877 help="do not delete the generated shared libary files (allows manual module experimentation)")
878 parser.add_option("--no-cython", dest="with_cython",
879 action="store_false", default=True,
880 help="do not run the Cython compiler, only the C compiler")
881 parser.add_option("--no-c", dest="use_c",
882 action="store_false", default=True,
883 help="do not test C compilation")
884 parser.add_option("--no-cpp", dest="use_cpp",
885 action="store_false", default=True,
886 help="do not test C++ compilation")
887 parser.add_option("--no-unit", dest="unittests",
888 action="store_false", default=True,
889 help="do not run the unit tests")
890 parser.add_option("--no-doctest", dest="doctests",
891 action="store_false", default=True,
892 help="do not run the doctests")
893 parser.add_option("--no-file", dest="filetests",
894 action="store_false", default=True,
895 help="do not run the file based tests")
896 parser.add_option("--no-pyregr", dest="pyregr",
897 action="store_false", default=True,
898 help="do not run the regression tests of CPython in tests/pyregr/")
899 parser.add_option("--cython-only", dest="cython_only",
900 action="store_true", default=False,
901 help="only compile pyx to c, do not run C compiler or run the tests")
902 parser.add_option("--no-refnanny", dest="with_refnanny",
903 action="store_false", default=True,
904 help="do not regression test reference counting")
905 parser.add_option("--no-fork", dest="fork",
906 action="store_false", default=True,
907 help="do not fork to run tests")
908 parser.add_option("--sys-pyregr", dest="system_pyregr",
909 action="store_true", default=False,
910 help="run the regression tests of the CPython installation")
911 parser.add_option("-x", "--exclude", dest="exclude",
912 action="append", metavar="PATTERN",
913 help="exclude tests matching the PATTERN")
914 parser.add_option("-C", "--coverage", dest="coverage",
915 action="store_true", default=False,
916 help="collect source coverage data for the Compiler")
917 parser.add_option("--coverage-xml", dest="coverage_xml",
918 action="store_true", default=False,
919 help="collect source coverage data for the Compiler in XML format")
920 parser.add_option("-A", "--annotate", dest="annotate_source",
921 action="store_true", default=True,
922 help="generate annotated HTML versions of the test source files")
923 parser.add_option("--no-annotate", dest="annotate_source",
924 action="store_false",
925 help="do not generate annotated HTML versions of the test source files")
926 parser.add_option("-v", "--verbose", dest="verbosity",
927 action="count", default=0,
928 help="display test progress, pass twice to print test names")
929 parser.add_option("-T", "--ticket", dest="tickets",
931 help="a bug ticket number to run the respective test in 'tests/*'")
932 parser.add_option("-3", dest="language_level",
933 action="store_const", const=3, default=2,
934 help="set language level to Python 3 (useful for running the CPython regression tests)'")
935 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
936 help="write test results in XML to directory DIR")
937 parser.add_option("--exit-ok", dest="exit_ok", default=False,
939 help="exit without error code even on test failures")
941 options, cmd_args = parser.parse_args()
943 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
944 ROOTDIR = os.path.join(DISTDIR, 'tests')
945 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
947 if sys.version_info[0] >= 3:
948 options.doctests = False
949 if options.with_cython:
951 # try if Cython is installed in a Py3 version
952 import Cython.Compiler.Main
954 # back out anything the import process loaded, then
955 # 2to3 the Cython sources to make them re-importable
956 cy_modules = [ name for name in sys.modules
957 if name == 'Cython' or name.startswith('Cython.') ]
958 for name in cy_modules:
959 del sys.modules[name]
960 # hasn't been refactored yet - do it now
961 cy3_dir = os.path.join(WORKDIR, 'Cy3')
962 if sys.version_info >= (3,1):
963 refactor_for_py3(DISTDIR, cy3_dir)
964 elif os.path.isdir(cy3_dir):
965 sys.path.insert(0, cy3_dir)
967 options.with_cython = False
969 WITH_CYTHON = options.with_cython
971 if options.coverage or options.coverage_xml:
973 options.coverage = options.coverage_xml = False
975 from coverage import coverage as _coverage
976 coverage = _coverage(branch=True)
981 from Cython.Compiler.Main import \
982 CompilationOptions, \
983 default_options as pyrex_default_options, \
984 compile as cython_compile
985 from Cython.Compiler import Errors
986 Errors.LEVEL = 0 # show all warnings
987 from Cython.Compiler import Options
988 Options.generate_cleanup_code = 3 # complete cleanup code
989 from Cython.Compiler import DebugFlags
990 DebugFlags.debug_temp_code_comments = 1
993 UNITTEST_MODULE = "Cython"
994 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
996 if os.path.exists(WORKDIR):
997 for path in os.listdir(WORKDIR):
998 if path in ("support", "Cy3"): continue
999 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1000 if not os.path.exists(WORKDIR):
1001 os.makedirs(WORKDIR)
1003 sys.stderr.write("Python %s\n" % sys.version)
1004 sys.stderr.write("\n")
1006 from Cython.Compiler.Version import version
1007 sys.stderr.write("Running tests against Cython %s\n" % version)
1009 sys.stderr.write("Running tests without Cython.\n")
1011 if options.with_refnanny:
1012 from pyximport.pyxbuild import pyx_to_dll
1013 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1015 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1016 sys.path.insert(0, os.path.split(libpath)[0])
1017 CFLAGS.append("-DCYTHON_REFNANNY=1")
1019 if options.xml_output_dir and options.fork:
1020 # doesn't currently work together
1021 sys.stderr.write("Disabling forked testing to support XML test output\n")
1022 options.fork = False
1024 if WITH_CYTHON and options.language_level == 3:
1025 sys.stderr.write("Using Cython language level 3.\n")
1027 sys.stderr.write("\n")
1031 for ticket_number in options.tickets:
1033 cmd_args.append('.*T%s$' % ticket_number)
1035 for selector in cmd_args:
1036 if selector.startswith('bugs'):
1040 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1042 selectors = [ lambda x:True ]
1044 # Chech which external modules are not present and exclude tests
1045 # which depends on them (by prefix)
1047 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1048 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1049 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1052 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1055 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1057 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1058 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1062 languages.append('c')
1064 languages.append('cpp')
1066 test_suite = unittest.TestSuite()
1068 if options.unittests:
1069 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1071 if options.doctests:
1072 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1074 if options.filetests and languages:
1075 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1076 options.annotate_source, options.cleanup_workdir,
1077 options.cleanup_sharedlibs, options.pyregr,
1078 options.cython_only, languages, test_bugs,
1079 options.fork, options.language_level)
1080 test_suite.addTest(filetests.build_suite())
1082 if options.system_pyregr and languages:
1083 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1084 options.annotate_source, options.cleanup_workdir,
1085 options.cleanup_sharedlibs, True,
1086 options.cython_only, languages, test_bugs,
1087 options.fork, options.language_level)
1089 filetests.handle_directory(
1090 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1093 if options.xml_output_dir:
1094 from Cython.Tests.xmlrunner import XMLTestRunner
1095 test_runner = XMLTestRunner(output=options.xml_output_dir,
1096 verbose=options.verbosity > 0)
1098 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1100 result = test_runner.run(test_suite)
1102 if options.coverage or options.coverage_xml:
1104 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1105 modules = [ module for name, module in sys.modules.items()
1106 if module is not None and
1107 name.startswith('Cython.Compiler.') and
1108 name[len('Cython.Compiler.'):] not in ignored_modules ]
1109 if options.coverage:
1110 coverage.report(modules, show_missing=0)
1111 if options.coverage_xml:
1112 coverage.xml_report(modules, outfile="coverage-report.xml")
1114 if missing_dep_excluder.tests_missing_deps:
1115 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1116 for test in missing_dep_excluder.tests_missing_deps:
1117 sys.stderr.write(" %s\n" % test)
1119 if options.with_refnanny:
1121 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1126 sys.exit(not result.wasSuccessful())