14 from StringIO import StringIO
16 from io import StringIO
19 import cPickle as pickle
26 from distutils.dist import Distribution
27 from distutils.core import Extension
28 from distutils.command.build_ext import build_ext as _build_ext
29 distutils_distro = Distribution()
31 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr', 'build']
32 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
34 # Lists external modules, and a matcher matching tests
35 # which should be excluded if the module is not present.
37 'numpy' : re.compile('.*\.numpy_.*').match,
38 'pstats' : re.compile('.*\.pstats_.*').match,
39 'posix' : re.compile('.*\.posix_.*').match,
42 def get_numpy_include_dirs():
44 return [numpy.get_include()]
47 # test name matcher , callable returning list
48 (re.compile('numpy_.*').match, get_numpy_include_dirs),
52 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
53 # (2,4) : (operator.le, ...) excludes ... when PyVer <= 2.4.x
54 (2,5) : (operator.lt, lambda x: x in ['run.any',
57 (2,4) : (operator.le, lambda x: x in ['run.extern_builtins_T258'
59 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
62 # The next line should start (3,); but this is a dictionary, so
63 # we can only have one (3,) key. Since 2.7 is supposed to be the
64 # last 2.x release, things would have to change drastically for this
66 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
67 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
68 'compile.extsetslice',
69 'compile.extdelslice',
70 'run.special_methods_T561_py2']),
73 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
74 CFLAGS = os.getenv('CFLAGS', '').split()
76 class build_ext(_build_ext):
77 def build_extension(self, ext):
78 if ext.language == 'c++':
80 try: # Py2.7+ & Py3.2+
81 compiler_obj = self.compiler_obj
82 except AttributeError:
83 compiler_obj = self.compiler
84 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
87 _build_ext.build_extension(self, ext)
89 class ErrorWriter(object):
90 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
93 self.write = self.output.append
95 def _collect(self, collect_errors, collect_warnings):
96 s = ''.join(self.output)
98 for line in s.split('\n'):
99 match = self.match_error(line)
101 is_warning, line, column, message = match.groups()
102 if (is_warning and collect_warnings) or \
103 (not is_warning and collect_errors):
104 result.append( (int(line), int(column), message.strip()) )
106 return [ "%d:%d: %s" % values for values in result ]
109 return self._collect(True, False)
111 def getwarnings(self):
112 return self._collect(False, True)
115 return self._collect(True, True)
117 class TestBuilder(object):
118 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
119 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
120 languages, test_bugs, fork, language_level):
121 self.rootdir = rootdir
122 self.workdir = workdir
123 self.selectors = selectors
124 self.exclude_selectors = exclude_selectors
125 self.annotate = annotate
126 self.cleanup_workdir = cleanup_workdir
127 self.cleanup_sharedlibs = cleanup_sharedlibs
128 self.with_pyregr = with_pyregr
129 self.cython_only = cython_only
130 self.languages = languages
131 self.test_bugs = test_bugs
133 self.language_level = language_level
135 def build_suite(self):
136 suite = unittest.TestSuite()
137 test_dirs = TEST_DIRS
138 filenames = os.listdir(self.rootdir)
140 for filename in filenames:
141 if not WITH_CYTHON and filename == "errors":
142 # we won't get any errors without running Cython
144 path = os.path.join(self.rootdir, filename)
145 if os.path.isdir(path) and filename in test_dirs:
146 if filename == 'pyregr' and not self.with_pyregr:
149 self.handle_directory(path, filename))
150 if sys.platform not in ['win32'] and sys.version_info[0] < 3:
151 # Non-Windows makefile, can't run Cython under Py3.
152 if [1 for selector in self.selectors if selector("embedded")]:
153 suite.addTest(unittest.makeSuite(EmbedTest))
156 def handle_directory(self, path, context):
157 workdir = os.path.join(self.workdir, context)
158 if not os.path.exists(workdir):
161 expect_errors = (context == 'errors')
162 suite = unittest.TestSuite()
163 filenames = os.listdir(path)
165 for filename in filenames:
166 if context == "build" and filename.endswith(".srctree"):
167 if not [ 1 for match in self.selectors if match(filename) ]:
169 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
171 if not (filename.endswith(".pyx") or filename.endswith(".py")):
173 if filename.startswith('.'): continue # certain emacs backup files
174 if context == 'pyregr' and not filename.startswith('test_'):
176 module = os.path.splitext(filename)[0]
177 fqmodule = "%s.%s" % (context, module)
178 if not [ 1 for match in self.selectors
179 if match(fqmodule) ]:
181 if self.exclude_selectors:
182 if [1 for match in self.exclude_selectors if match(fqmodule)]:
184 if context in TEST_RUN_DIRS:
185 if module.startswith("test_"):
186 test_class = CythonUnitTestCase
188 test_class = CythonRunTestCase
190 test_class = CythonCompileTestCase
191 for test in self.build_tests(test_class, path, workdir,
192 module, expect_errors):
194 if context == 'run' and filename.endswith('.py'):
195 # additionally test file in real Python
196 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
199 def build_tests(self, test_class, path, workdir, module, expect_errors):
201 if 'cpp' in module and 'cpp' in self.languages:
204 languages = self.languages[:1]
206 languages = self.languages
207 if 'cpp' in module and 'c' in languages:
208 languages = list(languages)
209 languages.remove('c')
210 tests = [ self.build_test(test_class, path, workdir, module,
211 language, expect_errors)
212 for language in languages ]
215 def build_test(self, test_class, path, workdir, module,
216 language, expect_errors):
217 workdir = os.path.join(workdir, language)
218 if not os.path.exists(workdir):
220 return test_class(path, workdir, module,
222 expect_errors=expect_errors,
223 annotate=self.annotate,
224 cleanup_workdir=self.cleanup_workdir,
225 cleanup_sharedlibs=self.cleanup_sharedlibs,
226 cython_only=self.cython_only,
228 language_level=self.language_level)
230 class CythonCompileTestCase(unittest.TestCase):
231 def __init__(self, test_directory, workdir, module, language='c',
232 expect_errors=False, annotate=False, cleanup_workdir=True,
233 cleanup_sharedlibs=True, cython_only=False, fork=True,
235 self.test_directory = test_directory
236 self.workdir = workdir
238 self.language = language
239 self.expect_errors = expect_errors
240 self.annotate = annotate
241 self.cleanup_workdir = cleanup_workdir
242 self.cleanup_sharedlibs = cleanup_sharedlibs
243 self.cython_only = cython_only
245 self.language_level = language_level
246 unittest.TestCase.__init__(self)
248 def shortDescription(self):
249 return "compiling (%s) %s" % (self.language, self.module)
252 if self.workdir not in sys.path:
253 sys.path.insert(0, self.workdir)
257 sys.path.remove(self.workdir)
261 del sys.modules[self.module]
264 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
265 cleanup_lib_files = self.cleanup_sharedlibs
266 if os.path.exists(self.workdir):
267 for rmfile in os.listdir(self.workdir):
268 if not cleanup_c_files:
269 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
271 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
273 if self.annotate and rmfile.endswith(".html"):
276 rmfile = os.path.join(self.workdir, rmfile)
277 if os.path.isdir(rmfile):
278 shutil.rmtree(rmfile, ignore_errors=True)
284 os.makedirs(self.workdir)
287 self.runCompileTest()
289 def runCompileTest(self):
290 self.compile(self.test_directory, self.module, self.workdir,
291 self.test_directory, self.expect_errors, self.annotate)
293 def find_module_source_file(self, source_file):
294 if not os.path.exists(source_file):
295 source_file = source_file[:-1]
298 def build_target_filename(self, module_name):
299 target = '%s.%s' % (module_name, self.language)
302 def copy_related_files(self, test_directory, target_directory, module_name):
303 is_related = re.compile('%s_.*[.].*' % module_name).match
304 for filename in os.listdir(test_directory):
305 if is_related(filename):
306 shutil.copy(os.path.join(test_directory, filename),
309 def find_source_files(self, workdir, module_name):
310 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
311 return [self.build_target_filename(module_name)] + [
312 filename for filename in os.listdir(workdir)
313 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
315 def split_source_and_output(self, test_directory, module, workdir):
316 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
317 source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
319 out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
321 for line in source_and_output:
323 if line.startswith("_ERRORS"):
329 source_and_output.close()
331 geterrors = out.geterrors
332 except AttributeError:
338 def run_cython(self, test_directory, module, targetdir, incdir, annotate):
339 include_dirs = INCLUDE_DIRS[:]
341 include_dirs.append(incdir)
342 source = self.find_module_source_file(
343 os.path.join(test_directory, module + '.pyx'))
344 target = os.path.join(targetdir, self.build_target_filename(module))
345 options = CompilationOptions(
346 pyrex_default_options,
347 include_path = include_dirs,
348 output_file = target,
350 use_listing_file = False,
351 cplus = self.language == 'cpp',
352 language_level = self.language_level,
353 generate_pxi = False,
354 evaluate_tree_assertions = True,
356 cython_compile(source, options=options,
357 full_module_name=module)
359 def run_distutils(self, test_directory, module, workdir, incdir):
363 build_extension = build_ext(distutils_distro)
364 build_extension.include_dirs = INCLUDE_DIRS[:]
366 build_extension.include_dirs.append(incdir)
367 build_extension.finalize_options()
368 ext_include_dirs = []
369 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
371 ext_include_dirs += get_additional_include_dirs()
372 self.copy_related_files(test_directory, workdir, module)
373 extension = Extension(
375 sources = self.find_source_files(workdir, module),
376 include_dirs = ext_include_dirs,
377 extra_compile_args = CFLAGS,
379 if self.language == 'cpp':
380 extension.language = 'c++'
381 build_extension.extensions = [extension]
382 build_extension.build_temp = workdir
383 build_extension.build_lib = workdir
384 build_extension.run()
388 def compile(self, test_directory, module, workdir, incdir,
389 expect_errors, annotate):
390 expected_errors = errors = ()
392 expected_errors = self.split_source_and_output(
393 test_directory, module, workdir)
394 test_directory = workdir
397 old_stderr = sys.stderr
399 sys.stderr = ErrorWriter()
400 self.run_cython(test_directory, module, workdir, incdir, annotate)
401 errors = sys.stderr.geterrors()
403 sys.stderr = old_stderr
405 if errors or expected_errors:
407 for expected, error in zip(expected_errors, errors):
408 self.assertEquals(expected, error)
409 if len(errors) < len(expected_errors):
410 expected_error = expected_errors[len(errors)]
411 self.assertEquals(expected_error, None)
412 elif len(errors) > len(expected_errors):
413 unexpected_error = errors[len(expected_errors)]
414 self.assertEquals(None, unexpected_error)
415 except AssertionError:
416 print("\n=== Expected errors: ===")
417 print('\n'.join(expected_errors))
418 print("\n\n=== Got errors: ===")
419 print('\n'.join(errors))
423 if not self.cython_only:
424 self.run_distutils(test_directory, module, workdir, incdir)
426 class CythonRunTestCase(CythonCompileTestCase):
427 def shortDescription(self):
428 return "compiling (%s) and running %s" % (self.language, self.module)
430 def run(self, result=None):
432 result = self.defaultTestResult()
433 result.startTest(self)
436 self.runCompileTest()
437 if not self.cython_only:
438 self.run_doctests(self.module, result)
440 result.addError(self, sys.exc_info())
441 result.stopTest(self)
447 def run_doctests(self, module_name, result):
448 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
449 doctest.DocTestSuite(module_name).run(result)
453 # fork to make sure we do not keep the tested module loaded
454 result_handle, result_file = tempfile.mkstemp()
455 os.close(result_handle)
463 partial_result = PartialTestResult(result)
464 tests = doctest.DocTestSuite(module_name)
465 tests.run(partial_result)
469 # importing failed, try to fake a test class
471 failureException=sys.exc_info()[1],
472 _shortDescription=self.shortDescription(),
474 partial_result.addError(tests, sys.exc_info())
476 output = open(result_file, 'wb')
477 pickle.dump(partial_result.data(), output)
480 traceback.print_exc()
484 os._exit(result_code)
487 cid, result_code = os.waitpid(child_id, 0)
488 # os.waitpid returns the child's result code in the
489 # upper byte of result_code, and the signal it was
490 # killed by in the lower byte
491 if result_code & 255:
492 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
493 (module_name, result_code & 255))
494 result_code = result_code >> 8
495 if result_code in (0,1):
496 input = open(result_file, 'rb')
498 PartialTestResult.join_results(result, pickle.load(input))
502 raise Exception("Tests in module '%s' exited with status %d" %
503 (module_name, result_code))
505 try: os.unlink(result_file)
508 class PureDoctestTestCase(unittest.TestCase):
509 def __init__(self, module_name, module_path):
510 self.module_name = module_name
511 self.module_path = module_path
512 unittest.TestCase.__init__(self, 'run')
514 def shortDescription(self):
515 return "running pure doctests in %s" % self.module_name
517 def run(self, result=None):
519 result = self.defaultTestResult()
520 loaded_module_name = 'pure_doctest__' + self.module_name
521 result.startTest(self)
526 m = imp.load_source(loaded_module_name, self.module_path)
528 doctest.DocTestSuite(m).run(result)
531 if loaded_module_name in sys.modules:
532 del sys.modules[loaded_module_name]
534 result.addError(self, sys.exc_info())
535 result.stopTest(self)
541 is_private_field = re.compile('^_[^_]').match
543 class _FakeClass(object):
544 def __init__(self, **kwargs):
545 self._shortDescription = kwargs.get('module_name')
546 self.__dict__.update(kwargs)
547 def shortDescription(self):
548 return self._shortDescription
550 try: # Py2.7+ and Py3.2+
551 from unittest.runner import _TextTestResult
553 from unittest import _TextTestResult
555 class PartialTestResult(_TextTestResult):
556 def __init__(self, base_result):
557 _TextTestResult.__init__(
558 self, self._StringIO(), True,
559 base_result.dots + base_result.showAll*2)
561 def strip_error_results(self, results):
562 for test_case, error in results:
563 for attr_name in filter(is_private_field, dir(test_case)):
564 if attr_name == '_dt_test':
565 test_case._dt_test = _FakeClass(
566 name=test_case._dt_test.name)
567 elif attr_name != '_shortDescription':
568 setattr(test_case, attr_name, None)
571 self.strip_error_results(self.failures)
572 self.strip_error_results(self.errors)
573 return (self.failures, self.errors, self.testsRun,
574 self.stream.getvalue())
576 def join_results(result, data):
577 """Static method for merging the result back into the main
580 failures, errors, tests_run, output = data
582 result.stream.write(output)
583 result.errors.extend(errors)
584 result.failures.extend(failures)
585 result.testsRun += tests_run
587 join_results = staticmethod(join_results)
589 class _StringIO(StringIO):
590 def writeln(self, line):
591 self.write("%s\n" % line)
594 class CythonUnitTestCase(CythonCompileTestCase):
595 def shortDescription(self):
596 return "compiling (%s) tests in %s" % (self.language, self.module)
598 def run(self, result=None):
600 result = self.defaultTestResult()
601 result.startTest(self)
604 self.runCompileTest()
605 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
607 result.addError(self, sys.exc_info())
608 result.stopTest(self)
614 def collect_unittests(path, module_prefix, suite, selectors):
615 def file_matches(filename):
616 return filename.startswith("Test") and filename.endswith(".py")
618 def package_matches(dirname):
619 return dirname == "Tests"
621 loader = unittest.TestLoader()
625 for dirpath, dirnames, filenames in os.walk(path):
626 if dirpath != path and "__init__.py" not in filenames:
627 skipped_dirs.append(dirpath + os.path.sep)
630 for dir in skipped_dirs:
631 if dirpath.startswith(dir):
635 parentname = os.path.split(dirpath)[-1]
636 if package_matches(parentname):
639 filepath = os.path.join(dirpath, f)[:-len(".py")]
640 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
641 if not [ 1 for match in selectors if match(modulename) ]:
643 module = __import__(modulename)
644 for x in modulename.split('.')[1:]:
645 module = getattr(module, x)
646 suite.addTests([loader.loadTestsFromModule(module)])
648 def collect_doctests(path, module_prefix, suite, selectors):
649 def package_matches(dirname):
650 return dirname not in ("Mac", "Distutils", "Plex")
651 def file_matches(filename):
652 return (filename.endswith(".py") and not ('~' in filename
653 or '#' in filename or filename.startswith('.')))
654 import doctest, types
655 for dirpath, dirnames, filenames in os.walk(path):
656 parentname = os.path.split(dirpath)[-1]
657 if package_matches(parentname):
660 if not f.endswith('.py'): continue
661 filepath = os.path.join(dirpath, f)
662 if os.path.getsize(filepath) == 0: continue
663 if 'no doctest' in open(filepath).next(): continue
664 filepath = filepath[:-len(".py")]
665 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
666 if not [ 1 for match in selectors if match(modulename) ]:
668 module = __import__(modulename)
669 for x in modulename.split('.')[1:]:
670 module = getattr(module, x)
671 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
673 suite.addTest(doctest.DocTestSuite(module))
674 except ValueError: # no tests
678 class EndToEndTest(unittest.TestCase):
680 This is a test of build/*.srctree files, where srctree defines a full
681 directory structure and its header gives a list of commands to run.
683 cython_root = os.path.dirname(os.path.abspath(__file__))
685 def __init__(self, treefile, workdir, cleanup_workdir=True):
686 self.treefile = treefile
687 self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
688 self.cleanup_workdir = cleanup_workdir
689 cython_syspath = self.cython_root
690 for path in sys.path[::-1]:
691 if path.startswith(self.cython_root):
692 # Py3 installation and refnanny build prepend their
693 # fixed paths to sys.path => prefer that over the
695 cython_syspath = path + os.pathsep + cython_syspath
696 self.cython_syspath = cython_syspath
697 unittest.TestCase.__init__(self)
699 def shortDescription(self):
700 return "End-to-end %s" % self.treefile
703 from Cython.TestUtils import unpack_source_tree
704 _, self.commands = unpack_source_tree(os.path.join('tests', 'build', self.treefile), self.workdir)
705 self.old_dir = os.getcwd()
706 os.chdir(self.workdir)
707 if self.workdir not in sys.path:
708 sys.path.insert(0, self.workdir)
711 if self.cleanup_workdir:
712 shutil.rmtree(self.workdir)
713 os.chdir(self.old_dir)
716 commands = (self.commands
717 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
718 .replace("PYTHON", sys.executable))
719 old_path = os.environ.get('PYTHONPATH')
721 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + (old_path or '')
722 print(os.environ['PYTHONPATH'])
723 self.assertEqual(0, os.system(commands))
726 os.environ['PYTHONPATH'] = old_path
728 del os.environ['PYTHONPATH']
731 # TODO: Support cython_freeze needed here as well.
732 # TODO: Windows support.
734 class EmbedTest(unittest.TestCase):
736 working_dir = "Demos/embed"
739 self.old_dir = os.getcwd()
740 os.chdir(self.working_dir)
742 "make PYTHON='%s' clean > /dev/null" % sys.executable)
747 "make PYTHON='%s' clean > /dev/null" % sys.executable)
750 os.chdir(self.old_dir)
752 def test_embed(self):
753 from distutils import sysconfig
754 libname = sysconfig.get_config_var('LIBRARY')
755 libdir = sysconfig.get_config_var('LIBDIR')
756 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
757 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
758 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
759 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
760 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
761 # report the error for the original directory
762 libdir = sysconfig.get_config_var('LIBDIR')
763 self.assert_(os.system(
764 "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
766 os.remove('make.output')
770 class MissingDependencyExcluder:
771 def __init__(self, deps):
772 # deps: { module name : matcher func }
773 self.exclude_matchers = []
774 for mod, matcher in deps.items():
778 self.exclude_matchers.append(matcher)
779 self.tests_missing_deps = []
780 def __call__(self, testname):
781 for matcher in self.exclude_matchers:
782 if matcher(testname):
783 self.tests_missing_deps.append(testname)
787 class VersionDependencyExcluder:
788 def __init__(self, deps):
789 # deps: { version : matcher func }
790 from sys import version_info
791 self.exclude_matchers = []
792 for ver, (compare, matcher) in deps.items():
793 if compare(version_info, ver):
794 self.exclude_matchers.append(matcher)
795 self.tests_missing_deps = []
796 def __call__(self, testname):
797 for matcher in self.exclude_matchers:
798 if matcher(testname):
799 self.tests_missing_deps.append(testname)
803 class FileListExcluder:
805 def __init__(self, list_file):
809 for line in f.readlines():
811 if line and line[0] != '#':
812 self.excludes[line.split()[0]] = True
816 def __call__(self, testname):
817 return testname in self.excludes or testname.split('.')[-1] in self.excludes
819 def refactor_for_py3(distdir, cy3_dir):
820 # need to convert Cython sources first
821 import lib2to3.refactor
822 from distutils.util import copydir_run_2to3
823 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
824 if fix.split('fix_')[-1] not in ('next',)
826 if not os.path.exists(cy3_dir):
828 import distutils.log as dlog
829 dlog.set_threshold(dlog.INFO)
830 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
834 recursive-exclude Cython *
835 recursive-include Cython *.py *.pyx *.pxd
837 sys.path.insert(0, cy3_dir)
840 if __name__ == '__main__':
841 from optparse import OptionParser
842 parser = OptionParser()
843 parser.add_option("--no-cleanup", dest="cleanup_workdir",
844 action="store_false", default=True,
845 help="do not delete the generated C files (allows passing --no-cython on next run)")
846 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
847 action="store_false", default=True,
848 help="do not delete the generated shared libary files (allows manual module experimentation)")
849 parser.add_option("--no-cython", dest="with_cython",
850 action="store_false", default=True,
851 help="do not run the Cython compiler, only the C compiler")
852 parser.add_option("--no-c", dest="use_c",
853 action="store_false", default=True,
854 help="do not test C compilation")
855 parser.add_option("--no-cpp", dest="use_cpp",
856 action="store_false", default=True,
857 help="do not test C++ compilation")
858 parser.add_option("--no-unit", dest="unittests",
859 action="store_false", default=True,
860 help="do not run the unit tests")
861 parser.add_option("--no-doctest", dest="doctests",
862 action="store_false", default=True,
863 help="do not run the doctests")
864 parser.add_option("--no-file", dest="filetests",
865 action="store_false", default=True,
866 help="do not run the file based tests")
867 parser.add_option("--no-pyregr", dest="pyregr",
868 action="store_false", default=True,
869 help="do not run the regression tests of CPython in tests/pyregr/")
870 parser.add_option("--cython-only", dest="cython_only",
871 action="store_true", default=False,
872 help="only compile pyx to c, do not run C compiler or run the tests")
873 parser.add_option("--no-refnanny", dest="with_refnanny",
874 action="store_false", default=True,
875 help="do not regression test reference counting")
876 parser.add_option("--no-fork", dest="fork",
877 action="store_false", default=True,
878 help="do not fork to run tests")
879 parser.add_option("--sys-pyregr", dest="system_pyregr",
880 action="store_true", default=False,
881 help="run the regression tests of the CPython installation")
882 parser.add_option("-x", "--exclude", dest="exclude",
883 action="append", metavar="PATTERN",
884 help="exclude tests matching the PATTERN")
885 parser.add_option("-C", "--coverage", dest="coverage",
886 action="store_true", default=False,
887 help="collect source coverage data for the Compiler")
888 parser.add_option("--coverage-xml", dest="coverage_xml",
889 action="store_true", default=False,
890 help="collect source coverage data for the Compiler in XML format")
891 parser.add_option("-A", "--annotate", dest="annotate_source",
892 action="store_true", default=True,
893 help="generate annotated HTML versions of the test source files")
894 parser.add_option("--no-annotate", dest="annotate_source",
895 action="store_false",
896 help="do not generate annotated HTML versions of the test source files")
897 parser.add_option("-v", "--verbose", dest="verbosity",
898 action="count", default=0,
899 help="display test progress, pass twice to print test names")
900 parser.add_option("-T", "--ticket", dest="tickets",
902 help="a bug ticket number to run the respective test in 'tests/*'")
903 parser.add_option("-3", dest="language_level",
904 action="store_const", const=3, default=2,
905 help="set language level to Python 3 (useful for running the CPython regression tests)'")
906 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
907 help="write test results in XML to directory DIR")
908 parser.add_option("--exit-ok", dest="exit_ok", default=False,
910 help="exit without error code even on test failures")
912 options, cmd_args = parser.parse_args()
914 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
915 ROOTDIR = os.path.join(DISTDIR, 'tests')
916 WORKDIR = os.path.join(os.getcwd(), 'BUILD')
918 if sys.version_info[0] >= 3:
919 options.doctests = False
920 if options.with_cython:
922 # try if Cython is installed in a Py3 version
923 import Cython.Compiler.Main
925 # back out anything the import process loaded, then
926 # 2to3 the Cython sources to make them re-importable
927 cy_modules = [ name for name in sys.modules
928 if name == 'Cython' or name.startswith('Cython.') ]
929 for name in cy_modules:
930 del sys.modules[name]
931 # hasn't been refactored yet - do it now
932 cy3_dir = os.path.join(WORKDIR, 'Cy3')
933 if sys.version_info >= (3,1):
934 refactor_for_py3(DISTDIR, cy3_dir)
935 elif os.path.isdir(cy3_dir):
936 sys.path.insert(0, cy3_dir)
938 options.with_cython = False
940 WITH_CYTHON = options.with_cython
942 if options.coverage or options.coverage_xml:
944 options.coverage = options.coverage_xml = False
946 from coverage import coverage as _coverage
947 coverage = _coverage(branch=True)
952 from Cython.Compiler.Main import \
953 CompilationOptions, \
954 default_options as pyrex_default_options, \
955 compile as cython_compile
956 from Cython.Compiler import Errors
957 Errors.LEVEL = 0 # show all warnings
958 from Cython.Compiler import Options
959 Options.generate_cleanup_code = 3 # complete cleanup code
960 from Cython.Compiler import DebugFlags
961 DebugFlags.debug_temp_code_comments = 1
964 UNITTEST_MODULE = "Cython"
965 UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
967 if os.path.exists(WORKDIR):
968 for path in os.listdir(WORKDIR):
969 if path in ("support", "Cy3"): continue
970 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
971 if not os.path.exists(WORKDIR):
974 sys.stderr.write("Python %s\n" % sys.version)
975 sys.stderr.write("\n")
977 from Cython.Compiler.Version import version
978 sys.stderr.write("Running tests against Cython %s\n" % version)
980 sys.stderr.write("Running tests without Cython.\n")
982 if options.with_refnanny:
983 from pyximport.pyxbuild import pyx_to_dll
984 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
986 pyxbuild_dir=os.path.join(WORKDIR, "support"))
987 sys.path.insert(0, os.path.split(libpath)[0])
988 CFLAGS.append("-DCYTHON_REFNANNY=1")
990 if options.xml_output_dir and options.fork:
991 # doesn't currently work together
992 sys.stderr.write("Disabling forked testing to support XML test output\n")
995 if WITH_CYTHON and options.language_level == 3:
996 sys.stderr.write("Using Cython language level 3.\n")
998 sys.stderr.write("\n")
1002 for ticket_number in options.tickets:
1004 cmd_args.append('.*T%s$' % ticket_number)
1006 for selector in cmd_args:
1007 if selector.startswith('bugs'):
1011 selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1013 selectors = [ lambda x:True ]
1015 # Chech which external modules are not present and exclude tests
1016 # which depends on them (by prefix)
1018 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1019 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1020 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1023 exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1026 exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1028 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1029 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1033 languages.append('c')
1035 languages.append('cpp')
1037 test_suite = unittest.TestSuite()
1039 if options.unittests:
1040 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1042 if options.doctests:
1043 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1045 if options.filetests and languages:
1046 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1047 options.annotate_source, options.cleanup_workdir,
1048 options.cleanup_sharedlibs, options.pyregr,
1049 options.cython_only, languages, test_bugs,
1050 options.fork, options.language_level)
1051 test_suite.addTest(filetests.build_suite())
1053 if options.system_pyregr and languages:
1054 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1055 options.annotate_source, options.cleanup_workdir,
1056 options.cleanup_sharedlibs, True,
1057 options.cython_only, languages, test_bugs,
1058 options.fork, options.language_level)
1060 filetests.handle_directory(
1061 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1064 if options.xml_output_dir:
1065 from Cython.Tests.xmlrunner import XMLTestRunner
1066 test_runner = XMLTestRunner(output=options.xml_output_dir,
1067 verbose=options.verbosity > 0)
1069 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1071 result = test_runner.run(test_suite)
1073 if options.coverage or options.coverage_xml:
1075 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1076 modules = [ module for name, module in sys.modules.items()
1077 if module is not None and
1078 name.startswith('Cython.Compiler.') and
1079 name[len('Cython.Compiler.'):] not in ignored_modules ]
1080 if options.coverage:
1081 coverage.report(modules, show_missing=0)
1082 if options.coverage_xml:
1083 coverage.xml_report(modules, outfile="coverage-report.xml")
1085 if missing_dep_excluder.tests_missing_deps:
1086 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1087 for test in missing_dep_excluder.tests_missing_deps:
1088 sys.stderr.write(" %s\n" % test)
1090 if options.with_refnanny:
1092 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1097 sys.exit(not result.wasSuccessful())