16 from StringIO import StringIO
18 from io import StringIO
21 import cPickle as pickle
26 from io import open as io_open
28 from codecs import open as io_open
32 except ImportError: # No threads, no problems
36 from collections import defaultdict
38 class defaultdict(object):
39 def __init__(self, default_factory=lambda : None):
41 self.default_factory = default_factory
42 def __getitem__(self, key):
43 if key not in self._dict:
44 self._dict[key] = self.default_factory()
45 return self._dict[key]
46 def __setitem__(self, key, value):
47 self._dict[key] = value
49 return repr(self._dict)
54 from distutils.dist import Distribution
55 from distutils.core import Extension
56 from distutils.command.build_ext import build_ext as _build_ext
57 distutils_distro = Distribution()
59 if sys.platform == 'win32':
60 # TODO: Figure out why this hackery (see http://thread.gmane.org/gmane.comp.python.cython.devel/8280/).
61 config_files = distutils_distro.find_config_files()
62 try: config_files.remove('setup.cfg')
63 except ValueError: pass
64 distutils_distro.parse_config_files(config_files)
66 cfgfiles = distutils_distro.find_config_files()
67 try: cfgfiles.remove('setup.cfg')
68 except ValueError: pass
69 distutils_distro.parse_config_files(cfgfiles)
72 'numpy' : 'tag:numpy',
73 'pstats' : 'tag:pstats',
74 'posix' : 'tag:posix',
77 def get_numpy_include_dirs():
79 return [numpy.get_include()]
83 # test name matcher , callable returning list
84 (re.compile('numpy_.*').match, get_numpy_include_dirs),
89 # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
90 # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
91 (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
94 (2,5) : (operator.lt, lambda x: x in ['run.any',
96 'run.relativeimport_T542',
98 (2,6) : (operator.lt, lambda x: x in ['run.print_function',
100 'run.pure_py', # decorators, with statement
102 # The next line should start (3,); but this is a dictionary, so
103 # we can only have one (3,) key. Since 2.7 is supposed to be the
104 # last 2.x release, things would have to change drastically for this
106 (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
107 (3,): (operator.ge, lambda x: x in ['run.non_future_division',
108 'compile.extsetslice',
109 'compile.extdelslice',
110 'run.special_methods_T561_py2']),
113 # files that should not be converted to Python 3 code with 2to3
115 os.path.join('Cython', 'Debugger', 'Tests', 'test_libcython_in_gdb.py'),
116 os.path.join('Cython', 'Debugger', 'Tests', 'test_libpython_in_gdb.py'),
117 os.path.join('Cython', 'Debugger', 'libcython.py'),
118 os.path.join('Cython', 'Debugger', 'libpython.py'),
122 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
123 CFLAGS = os.getenv('CFLAGS', '').split()
126 uncomputed = object()
129 res = f._cache.get(args, uncomputed)
130 if res is uncomputed:
131 res = f._cache[args] = f(*args)
135 def parse_tags(filepath):
136 tags = defaultdict(list)
137 f = io_open(filepath, encoding='ISO-8859-1', errors='replace')
147 tag = line[1:ix].strip()
148 values = line[ix+1:].split(',')
149 tags[tag].extend([value.strip() for value in values])
154 parse_tags = memoize(parse_tags)
157 class build_ext(_build_ext):
158 def build_extension(self, ext):
159 if ext.language == 'c++':
161 try: # Py2.7+ & Py3.2+
162 compiler_obj = self.compiler_obj
163 except AttributeError:
164 compiler_obj = self.compiler
165 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
168 _build_ext.build_extension(self, ext)
170 class ErrorWriter(object):
171 match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
174 self.write = self.output.append
176 def _collect(self, collect_errors, collect_warnings):
177 s = ''.join(self.output)
179 for line in s.split('\n'):
180 match = self.match_error(line)
182 is_warning, line, column, message = match.groups()
183 if (is_warning and collect_warnings) or \
184 (not is_warning and collect_errors):
185 result.append( (int(line), int(column), message.strip()) )
187 return [ "%d:%d: %s" % values for values in result ]
190 return self._collect(True, False)
192 def getwarnings(self):
193 return self._collect(False, True)
196 return self._collect(True, True)
198 class TestBuilder(object):
199 def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
200 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
201 languages, test_bugs, fork, language_level):
202 self.rootdir = rootdir
203 self.workdir = workdir
204 self.selectors = selectors
205 self.exclude_selectors = exclude_selectors
206 self.annotate = annotate
207 self.cleanup_workdir = cleanup_workdir
208 self.cleanup_sharedlibs = cleanup_sharedlibs
209 self.with_pyregr = with_pyregr
210 self.cython_only = cython_only
211 self.languages = languages
212 self.test_bugs = test_bugs
214 self.language_level = language_level
216 def build_suite(self):
217 suite = unittest.TestSuite()
218 filenames = os.listdir(self.rootdir)
220 for filename in filenames:
221 path = os.path.join(self.rootdir, filename)
222 if os.path.isdir(path):
223 if filename == 'pyregr' and not self.with_pyregr:
225 if filename == 'broken' and not self.test_bugs:
228 self.handle_directory(path, filename))
229 if sys.platform not in ['win32']:
230 # Non-Windows makefile.
231 if [1 for selector in self.selectors if selector("embedded")] \
232 and not [1 for selector in self.exclude_selectors if selector("embedded")]:
233 suite.addTest(unittest.makeSuite(EmbedTest))
236 def handle_directory(self, path, context):
237 workdir = os.path.join(self.workdir, context)
238 if not os.path.exists(workdir):
241 suite = unittest.TestSuite()
242 filenames = os.listdir(path)
244 for filename in filenames:
245 filepath = os.path.join(path, filename)
246 module, ext = os.path.splitext(filename)
247 if ext not in ('.py', '.pyx', '.srctree'):
249 if filename.startswith('.'):
250 continue # certain emacs backup files
251 tags = parse_tags(filepath)
252 fqmodule = "%s.%s" % (context, module)
253 if not [ 1 for match in self.selectors
254 if match(fqmodule, tags) ]:
256 if self.exclude_selectors:
257 if [1 for match in self.exclude_selectors
258 if match(fqmodule, tags)]:
261 mode = 'run' # default
263 mode = tags['mode'][0]
264 elif context == 'pyregr':
267 if ext == '.srctree':
268 suite.addTest(EndToEndTest(filepath, workdir, self.cleanup_workdir))
271 # Choose the test suite.
273 if not filename.startswith('test_'):
275 test_class = CythonPyregrTestCase
277 if module.startswith("test_"):
278 test_class = CythonUnitTestCase
280 test_class = CythonRunTestCase
282 test_class = CythonCompileTestCase
284 for test in self.build_tests(test_class, path, workdir,
285 module, mode == 'error', tags):
287 if mode == 'run' and ext == '.py':
288 # additionally test file in real Python
289 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
293 def build_tests(self, test_class, path, workdir, module, expect_errors, tags):
294 if 'werror' in tags['tags']:
295 warning_errors = True
297 warning_errors = False
300 if 'cpp' in tags['tag'] and 'cpp' in self.languages:
303 languages = self.languages[:1]
305 languages = self.languages
306 if 'cpp' in tags['tag'] and 'c' in languages:
307 languages = list(languages)
308 languages.remove('c')
309 tests = [ self.build_test(test_class, path, workdir, module,
310 language, expect_errors, warning_errors)
311 for language in languages ]
314 def build_test(self, test_class, path, workdir, module,
315 language, expect_errors, warning_errors):
316 workdir = os.path.join(workdir, language)
317 if not os.path.exists(workdir):
319 return test_class(path, workdir, module,
321 expect_errors=expect_errors,
322 annotate=self.annotate,
323 cleanup_workdir=self.cleanup_workdir,
324 cleanup_sharedlibs=self.cleanup_sharedlibs,
325 cython_only=self.cython_only,
327 language_level=self.language_level,
328 warning_errors=warning_errors)
330 class CythonCompileTestCase(unittest.TestCase):
331 def __init__(self, test_directory, workdir, module, language='c',
332 expect_errors=False, annotate=False, cleanup_workdir=True,
333 cleanup_sharedlibs=True, cython_only=False, fork=True,
334 language_level=2, warning_errors=False):
335 self.test_directory = test_directory
336 self.workdir = workdir
338 self.language = language
339 self.expect_errors = expect_errors
340 self.annotate = annotate
341 self.cleanup_workdir = cleanup_workdir
342 self.cleanup_sharedlibs = cleanup_sharedlibs
343 self.cython_only = cython_only
345 self.language_level = language_level
346 self.warning_errors = warning_errors
347 unittest.TestCase.__init__(self)
349 def shortDescription(self):
350 return "compiling (%s) %s" % (self.language, self.module)
353 from Cython.Compiler import Options
354 Options.warning_errors = self.warning_errors
356 if self.workdir not in sys.path:
357 sys.path.insert(0, self.workdir)
360 from Cython.Compiler import Options
361 Options.warning_errors = False
364 sys.path.remove(self.workdir)
368 del sys.modules[self.module]
371 cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
372 cleanup_lib_files = self.cleanup_sharedlibs
373 if os.path.exists(self.workdir):
374 for rmfile in os.listdir(self.workdir):
375 if not cleanup_c_files:
376 if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
378 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
380 if self.annotate and rmfile.endswith(".html"):
383 rmfile = os.path.join(self.workdir, rmfile)
384 if os.path.isdir(rmfile):
385 shutil.rmtree(rmfile, ignore_errors=True)
391 os.makedirs(self.workdir)
394 self.runCompileTest()
396 def runCompileTest(self):
397 self.compile(self.test_directory, self.module, self.workdir,
398 self.test_directory, self.expect_errors, self.annotate)
400 def find_module_source_file(self, source_file):
401 if not os.path.exists(source_file):
402 source_file = source_file[:-1]
405 def build_target_filename(self, module_name):
406 target = '%s.%s' % (module_name, self.language)
409 def copy_related_files(self, test_directory, target_directory, module_name):
410 is_related = re.compile('%s_.*[.].*' % module_name).match
411 for filename in os.listdir(test_directory):
412 if is_related(filename):
413 shutil.copy(os.path.join(test_directory, filename),
416 def find_source_files(self, workdir, module_name):
417 is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
418 return [self.build_target_filename(module_name)] + [
419 filename for filename in os.listdir(workdir)
420 if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
422 def split_source_and_output(self, test_directory, module, workdir):
423 source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
424 source_and_output = io_open(source_file, 'rU', encoding='ISO-8859-1')
426 out = io_open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
427 'w', encoding='ISO-8859-1')
428 for line in source_and_output:
430 if line.startswith("_ERRORS"):
436 source_and_output.close()
438 geterrors = out.geterrors
439 except AttributeError:
445 def run_cython(self, test_directory, module, targetdir, incdir, annotate,
446 extra_compile_options=None):
447 include_dirs = INCLUDE_DIRS[:]
449 include_dirs.append(incdir)
450 source = self.find_module_source_file(
451 os.path.join(test_directory, module + '.pyx'))
452 target = os.path.join(targetdir, self.build_target_filename(module))
454 if extra_compile_options is None:
455 extra_compile_options = {}
460 from Cython.Compiler.Main import CompilationOptions
461 from Cython.Compiler.Main import compile as cython_compile
462 from Cython.Compiler.Main import default_options
464 options = CompilationOptions(
466 include_path = include_dirs,
467 output_file = target,
469 use_listing_file = False,
470 cplus = self.language == 'cpp',
471 language_level = self.language_level,
472 generate_pxi = False,
473 evaluate_tree_assertions = True,
474 **extra_compile_options
476 cython_compile(source, options=options,
477 full_module_name=module)
479 def run_distutils(self, test_directory, module, workdir, incdir,
480 extra_extension_args=None):
484 build_extension = build_ext(distutils_distro)
485 build_extension.include_dirs = INCLUDE_DIRS[:]
487 build_extension.include_dirs.append(incdir)
488 build_extension.finalize_options()
490 build_extension.compiler = COMPILER
491 ext_include_dirs = []
492 for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
494 ext_include_dirs += get_additional_include_dirs()
495 ext_compile_flags = CFLAGS[:]
496 if build_extension.compiler == 'mingw32':
497 ext_compile_flags.append('-Wno-format')
498 if extra_extension_args is None:
499 extra_extension_args = {}
501 self.copy_related_files(test_directory, workdir, module)
502 extension = Extension(
504 sources = self.find_source_files(workdir, module),
505 include_dirs = ext_include_dirs,
506 extra_compile_args = ext_compile_flags,
507 **extra_extension_args
509 if self.language == 'cpp':
510 extension.language = 'c++'
511 build_extension.extensions = [extension]
512 build_extension.build_temp = workdir
513 build_extension.build_lib = workdir
514 build_extension.run()
518 def compile(self, test_directory, module, workdir, incdir,
519 expect_errors, annotate):
520 expected_errors = errors = ()
522 expected_errors = self.split_source_and_output(
523 test_directory, module, workdir)
524 test_directory = workdir
527 old_stderr = sys.stderr
529 sys.stderr = ErrorWriter()
530 self.run_cython(test_directory, module, workdir, incdir, annotate)
531 errors = sys.stderr.geterrors()
533 sys.stderr = old_stderr
535 if errors or expected_errors:
537 for expected, error in zip(expected_errors, errors):
538 self.assertEquals(expected, error)
539 if len(errors) < len(expected_errors):
540 expected_error = expected_errors[len(errors)]
541 self.assertEquals(expected_error, None)
542 elif len(errors) > len(expected_errors):
543 unexpected_error = errors[len(expected_errors)]
544 self.assertEquals(None, unexpected_error)
545 except AssertionError:
546 print("\n=== Expected errors: ===")
547 print('\n'.join(expected_errors))
548 print("\n\n=== Got errors: ===")
549 print('\n'.join(errors))
553 if not self.cython_only:
554 self.run_distutils(test_directory, module, workdir, incdir)
556 class CythonRunTestCase(CythonCompileTestCase):
557 def shortDescription(self):
558 return "compiling (%s) and running %s" % (self.language, self.module)
560 def run(self, result=None):
562 result = self.defaultTestResult()
563 result.startTest(self)
567 self.runCompileTest()
568 self.run_tests(result)
570 check_thread_termination()
572 result.addError(self, sys.exc_info())
573 result.stopTest(self)
579 def run_tests(self, result):
580 if not self.cython_only:
581 self.run_doctests(self.module, result)
583 def run_doctests(self, module_name, result):
584 if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
585 doctest.DocTestSuite(module_name).run(result)
589 # fork to make sure we do not keep the tested module loaded
590 result_handle, result_file = tempfile.mkstemp()
591 os.close(result_handle)
599 partial_result = PartialTestResult(result)
600 tests = doctest.DocTestSuite(module_name)
601 tests.run(partial_result)
605 # importing failed, try to fake a test class
607 failureException=sys.exc_info()[1],
608 _shortDescription=self.shortDescription(),
610 partial_result.addError(tests, sys.exc_info())
612 output = open(result_file, 'wb')
613 pickle.dump(partial_result.data(), output)
615 traceback.print_exc()
619 os._exit(result_code)
622 cid, result_code = os.waitpid(child_id, 0)
623 # os.waitpid returns the child's result code in the
624 # upper byte of result_code, and the signal it was
625 # killed by in the lower byte
626 if result_code & 255:
627 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
628 (module_name, result_code & 255))
629 result_code = result_code >> 8
630 if result_code in (0,1):
631 input = open(result_file, 'rb')
633 PartialTestResult.join_results(result, pickle.load(input))
637 raise Exception("Tests in module '%s' exited with status %d" %
638 (module_name, result_code))
640 try: os.unlink(result_file)
643 class PureDoctestTestCase(unittest.TestCase):
644 def __init__(self, module_name, module_path):
645 self.module_name = module_name
646 self.module_path = module_path
647 unittest.TestCase.__init__(self, 'run')
649 def shortDescription(self):
650 return "running pure doctests in %s" % self.module_name
652 def run(self, result=None):
654 result = self.defaultTestResult()
655 loaded_module_name = 'pure_doctest__' + self.module_name
656 result.startTest(self)
661 m = imp.load_source(loaded_module_name, self.module_path)
663 doctest.DocTestSuite(m).run(result)
666 if loaded_module_name in sys.modules:
667 del sys.modules[loaded_module_name]
668 check_thread_termination()
670 result.addError(self, sys.exc_info())
671 result.stopTest(self)
677 is_private_field = re.compile('^_[^_]').match
679 class _FakeClass(object):
680 def __init__(self, **kwargs):
681 self._shortDescription = kwargs.get('module_name')
682 self.__dict__.update(kwargs)
683 def shortDescription(self):
684 return self._shortDescription
686 try: # Py2.7+ and Py3.2+
687 from unittest.runner import _TextTestResult
689 from unittest import _TextTestResult
691 class PartialTestResult(_TextTestResult):
692 def __init__(self, base_result):
693 _TextTestResult.__init__(
694 self, self._StringIO(), True,
695 base_result.dots + base_result.showAll*2)
697 def strip_error_results(self, results):
698 for test_case, error in results:
699 for attr_name in filter(is_private_field, dir(test_case)):
700 if attr_name == '_dt_test':
701 test_case._dt_test = _FakeClass(
702 name=test_case._dt_test.name)
703 elif attr_name != '_shortDescription':
704 setattr(test_case, attr_name, None)
707 self.strip_error_results(self.failures)
708 self.strip_error_results(self.errors)
709 return (self.failures, self.errors, self.testsRun,
710 self.stream.getvalue())
712 def join_results(result, data):
713 """Static method for merging the result back into the main
716 failures, errors, tests_run, output = data
718 result.stream.write(output)
719 result.errors.extend(errors)
720 result.failures.extend(failures)
721 result.testsRun += tests_run
723 join_results = staticmethod(join_results)
725 class _StringIO(StringIO):
726 def writeln(self, line):
727 self.write("%s\n" % line)
730 class CythonUnitTestCase(CythonRunTestCase):
731 def shortDescription(self):
732 return "compiling (%s) tests in %s" % (self.language, self.module)
734 def run_tests(self, result):
735 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
738 class CythonPyregrTestCase(CythonRunTestCase):
739 def _run_unittest(self, result, *classes):
740 """Run tests from unittest.TestCase-derived classes."""
741 valid_types = (unittest.TestSuite, unittest.TestCase)
742 suite = unittest.TestSuite()
744 if isinstance(cls, str):
745 if cls in sys.modules:
746 suite.addTest(unittest.findTestCases(sys.modules[cls]))
748 raise ValueError("str arguments must be keys in sys.modules")
749 elif isinstance(cls, valid_types):
752 suite.addTest(unittest.makeSuite(cls))
755 def _run_doctest(self, result, module):
756 self.run_doctests(module, result)
758 def run_tests(self, result):
760 from test import test_support as support
761 except ImportError: # Py3k
762 from test import support
764 def run_unittest(*classes):
765 return self._run_unittest(result, *classes)
766 def run_doctest(module, verbosity=None):
767 return self._run_doctest(result, module)
769 support.run_unittest = run_unittest
770 support.run_doctest = run_doctest
773 module = __import__(self.module)
774 if hasattr(module, 'test_main'):
776 except (unittest.SkipTest, support.ResourceDenied):
777 result.addSkip(self, 'ok')
779 include_debugger = sys.version_info[:2] > (2, 5)
781 def collect_unittests(path, module_prefix, suite, selectors):
782 def file_matches(filename):
783 return filename.startswith("Test") and filename.endswith(".py")
785 def package_matches(dirname):
786 return dirname == "Tests"
788 loader = unittest.TestLoader()
793 skipped_dirs = ['Cython' + os.path.sep + 'Debugger' + os.path.sep]
795 for dirpath, dirnames, filenames in os.walk(path):
796 if dirpath != path and "__init__.py" not in filenames:
797 skipped_dirs.append(dirpath + os.path.sep)
800 for dir in skipped_dirs:
801 if dirpath.startswith(dir):
805 parentname = os.path.split(dirpath)[-1]
806 if package_matches(parentname):
809 filepath = os.path.join(dirpath, f)[:-len(".py")]
810 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
811 if not [ 1 for match in selectors if match(modulename) ]:
813 module = __import__(modulename)
814 for x in modulename.split('.')[1:]:
815 module = getattr(module, x)
816 suite.addTests([loader.loadTestsFromModule(module)])
820 def collect_doctests(path, module_prefix, suite, selectors):
821 def package_matches(dirname):
822 if dirname == 'Debugger' and not include_debugger:
824 return dirname not in ("Mac", "Distutils", "Plex")
825 def file_matches(filename):
826 filename, ext = os.path.splitext(filename)
827 blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb',
829 return (ext == '.py' and not
830 '~' in filename and not
831 '#' in filename and not
832 filename.startswith('.') and not
833 filename in blacklist)
834 import doctest, types
835 for dirpath, dirnames, filenames in os.walk(path):
836 for dir in list(dirnames):
837 if not package_matches(dir):
841 if not f.endswith('.py'): continue
842 filepath = os.path.join(dirpath, f)
843 if os.path.getsize(filepath) == 0: continue
844 filepath = filepath[:-len(".py")]
845 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
846 if not [ 1 for match in selectors if match(modulename) ]:
848 if 'in_gdb' in modulename:
849 # These should only be imported from gdb.
851 module = __import__(modulename)
852 for x in modulename.split('.')[1:]:
853 module = getattr(module, x)
854 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
856 suite.addTest(doctest.DocTestSuite(module))
857 except ValueError: # no tests
861 class EndToEndTest(unittest.TestCase):
863 This is a test of build/*.srctree files, where srctree defines a full
864 directory structure and its header gives a list of commands to run.
866 cython_root = os.path.dirname(os.path.abspath(__file__))
868 def __init__(self, treefile, workdir, cleanup_workdir=True):
869 self.name = os.path.splitext(os.path.basename(treefile))[0]
870 self.treefile = treefile
871 self.workdir = os.path.join(workdir, self.name)
872 self.cleanup_workdir = cleanup_workdir
873 cython_syspath = self.cython_root
874 for path in sys.path[::-1]:
875 if path.startswith(self.cython_root):
876 # Py3 installation and refnanny build prepend their
877 # fixed paths to sys.path => prefer that over the
879 cython_syspath = path + os.pathsep + cython_syspath
880 self.cython_syspath = cython_syspath
881 unittest.TestCase.__init__(self)
883 def shortDescription(self):
884 return "End-to-end %s" % self.name
887 from Cython.TestUtils import unpack_source_tree
888 _, self.commands = unpack_source_tree(self.treefile, self.workdir)
889 self.old_dir = os.getcwd()
890 os.chdir(self.workdir)
891 if self.workdir not in sys.path:
892 sys.path.insert(0, self.workdir)
895 if self.cleanup_workdir:
896 for trial in range(5):
898 shutil.rmtree(self.workdir)
903 os.chdir(self.old_dir)
906 commands = (self.commands
907 .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
908 .replace("PYTHON", sys.executable))
910 old_path = os.environ.get('PYTHONPATH')
911 os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
912 for command in commands.split('\n'):
913 if sys.version_info[:2] >= (2,4):
915 p = subprocess.Popen(commands,
916 stderr=subprocess.PIPE,
917 stdout=subprocess.PIPE,
919 out, err = p.communicate()
926 res = os.system(command)
927 self.assertEqual(0, res, "non-zero exit status")
930 os.environ['PYTHONPATH'] = old_path
932 del os.environ['PYTHONPATH']
935 # TODO: Support cython_freeze needed here as well.
936 # TODO: Windows support.
938 class EmbedTest(unittest.TestCase):
940 working_dir = "Demos/embed"
943 self.old_dir = os.getcwd()
944 os.chdir(self.working_dir)
946 "make PYTHON='%s' clean > /dev/null" % sys.executable)
951 "make PYTHON='%s' clean > /dev/null" % sys.executable)
954 os.chdir(self.old_dir)
956 def test_embed(self):
957 from distutils import sysconfig
958 libname = sysconfig.get_config_var('LIBRARY')
959 libdir = sysconfig.get_config_var('LIBDIR')
960 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
961 libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
962 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
963 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
964 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
965 # report the error for the original directory
966 libdir = sysconfig.get_config_var('LIBDIR')
968 if sys.version_info[0] >=3 and CY3_DIR:
969 cython = os.path.join(CY3_DIR, cython)
970 cython = os.path.abspath(os.path.join('..', '..', cython))
971 self.assert_(os.system(
972 "make PYTHON='%s' CYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, cython, libdir)) == 0)
974 os.remove('make.output')
978 class MissingDependencyExcluder:
979 def __init__(self, deps):
980 # deps: { module name : matcher func }
981 self.exclude_matchers = []
982 for mod, matcher in deps.items():
986 self.exclude_matchers.append(string_selector(matcher))
987 self.tests_missing_deps = []
988 def __call__(self, testname, tags=None):
989 for matcher in self.exclude_matchers:
990 if matcher(testname, tags):
991 self.tests_missing_deps.append(testname)
995 class VersionDependencyExcluder:
996 def __init__(self, deps):
997 # deps: { version : matcher func }
998 from sys import version_info
999 self.exclude_matchers = []
1000 for ver, (compare, matcher) in deps.items():
1001 if compare(version_info, ver):
1002 self.exclude_matchers.append(matcher)
1003 self.tests_missing_deps = []
1004 def __call__(self, testname, tags=None):
1005 for matcher in self.exclude_matchers:
1006 if matcher(testname):
1007 self.tests_missing_deps.append(testname)
1011 class FileListExcluder:
1013 def __init__(self, list_file):
1017 for line in f.readlines():
1019 if line and line[0] != '#':
1020 self.excludes[line.split()[0]] = True
1024 def __call__(self, testname, tags=None):
1025 return testname in self.excludes or testname.split('.')[-1] in self.excludes
1029 def __init__(self, tag, value):
1033 def __call__(self, testname, tags=None):
1037 return self.value in tags[self.tag]
1039 class RegExSelector:
1041 def __init__(self, pattern_string):
1042 self.pattern = re.compile(pattern_string, re.I|re.U)
1044 def __call__(self, testname, tags=None):
1045 return self.pattern.search(testname)
1047 def string_selector(s):
1050 return RegExSelector(s)
1052 return TagsSelector(s[:ix], s[ix+1:])
1055 def refactor_for_py3(distdir, cy3_dir):
1056 # need to convert Cython sources first
1057 import lib2to3.refactor
1058 from distutils.util import copydir_run_2to3
1059 fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
1060 if fix.split('fix_')[-1] not in ('next',)
1062 if not os.path.exists(cy3_dir):
1063 os.makedirs(cy3_dir)
1064 import distutils.log as dlog
1065 dlog.set_threshold(dlog.INFO)
1066 copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
1070 recursive-exclude Cython *
1071 recursive-include Cython *.py *.pyx *.pxd
1072 recursive-include Cython/Debugger/Tests *
1076 sys.path.insert(0, cy3_dir)
1078 for keep_2x_file in KEEP_2X_FILES:
1079 destfile = os.path.join(cy3_dir, keep_2x_file)
1080 shutil.copy(keep_2x_file, destfile)
1082 class PendingThreadsError(RuntimeError):
1087 def check_thread_termination(ignore_seen=True):
1088 if threading is None: # no threading enabled in CPython
1090 current = threading.currentThread()
1091 blocking_threads = []
1092 for t in threading.enumerate():
1093 if not t.isAlive() or t == current:
1098 blocking_threads.append(t)
1100 for seen in threads_seen:
1104 threads_seen.append(t)
1105 blocking_threads.append(t)
1106 if not blocking_threads:
1108 sys.stderr.write("warning: left-over threads found after running test:\n")
1109 for t in blocking_threads:
1110 sys.stderr.write('...%s\n' % repr(t))
1111 raise PendingThreadsError("left-over threads found after running test")
1115 DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1117 from optparse import OptionParser
1118 parser = OptionParser()
1119 parser.add_option("--no-cleanup", dest="cleanup_workdir",
1120 action="store_false", default=True,
1121 help="do not delete the generated C files (allows passing --no-cython on next run)")
1122 parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
1123 action="store_false", default=True,
1124 help="do not delete the generated shared libary files (allows manual module experimentation)")
1125 parser.add_option("--no-cython", dest="with_cython",
1126 action="store_false", default=True,
1127 help="do not run the Cython compiler, only the C compiler")
1128 parser.add_option("--compiler", dest="compiler", default=None,
1129 help="C compiler type")
1130 parser.add_option("--no-c", dest="use_c",
1131 action="store_false", default=True,
1132 help="do not test C compilation")
1133 parser.add_option("--no-cpp", dest="use_cpp",
1134 action="store_false", default=True,
1135 help="do not test C++ compilation")
1136 parser.add_option("--no-unit", dest="unittests",
1137 action="store_false", default=True,
1138 help="do not run the unit tests")
1139 parser.add_option("--no-doctest", dest="doctests",
1140 action="store_false", default=True,
1141 help="do not run the doctests")
1142 parser.add_option("--no-file", dest="filetests",
1143 action="store_false", default=True,
1144 help="do not run the file based tests")
1145 parser.add_option("--no-pyregr", dest="pyregr",
1146 action="store_false", default=True,
1147 help="do not run the regression tests of CPython in tests/pyregr/")
1148 parser.add_option("--cython-only", dest="cython_only",
1149 action="store_true", default=False,
1150 help="only compile pyx to c, do not run C compiler or run the tests")
1151 parser.add_option("--no-refnanny", dest="with_refnanny",
1152 action="store_false", default=True,
1153 help="do not regression test reference counting")
1154 parser.add_option("--no-fork", dest="fork",
1155 action="store_false", default=True,
1156 help="do not fork to run tests")
1157 parser.add_option("--sys-pyregr", dest="system_pyregr",
1158 action="store_true", default=False,
1159 help="run the regression tests of the CPython installation")
1160 parser.add_option("-x", "--exclude", dest="exclude",
1161 action="append", metavar="PATTERN",
1162 help="exclude tests matching the PATTERN")
1163 parser.add_option("-C", "--coverage", dest="coverage",
1164 action="store_true", default=False,
1165 help="collect source coverage data for the Compiler")
1166 parser.add_option("--coverage-xml", dest="coverage_xml",
1167 action="store_true", default=False,
1168 help="collect source coverage data for the Compiler in XML format")
1169 parser.add_option("-A", "--annotate", dest="annotate_source",
1170 action="store_true", default=True,
1171 help="generate annotated HTML versions of the test source files")
1172 parser.add_option("--no-annotate", dest="annotate_source",
1173 action="store_false",
1174 help="do not generate annotated HTML versions of the test source files")
1175 parser.add_option("-v", "--verbose", dest="verbosity",
1176 action="count", default=0,
1177 help="display test progress, pass twice to print test names")
1178 parser.add_option("-T", "--ticket", dest="tickets",
1180 help="a bug ticket number to run the respective test in 'tests/*'")
1181 parser.add_option("-3", dest="language_level",
1182 action="store_const", const=3, default=2,
1183 help="set language level to Python 3 (useful for running the CPython regression tests)'")
1184 parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1185 help="write test results in XML to directory DIR")
1186 parser.add_option("--exit-ok", dest="exit_ok", default=False,
1187 action="store_true",
1188 help="exit without error code even on test failures")
1189 parser.add_option("--root-dir", dest="root_dir", default=os.path.join(DISTDIR, 'tests'),
1190 help="working directory")
1191 parser.add_option("--work-dir", dest="work_dir", default=os.path.join(os.getcwd(), 'BUILD'),
1192 help="working directory")
1194 options, cmd_args = parser.parse_args()
1196 ROOTDIR = os.path.abspath(options.root_dir)
1197 WORKDIR = os.path.abspath(options.work_dir)
1199 if sys.version_info[0] >= 3:
1200 options.doctests = False
1201 if options.with_cython:
1203 # try if Cython is installed in a Py3 version
1204 import Cython.Compiler.Main
1206 # back out anything the import process loaded, then
1207 # 2to3 the Cython sources to make them re-importable
1208 cy_modules = [ name for name in sys.modules
1209 if name == 'Cython' or name.startswith('Cython.') ]
1210 for name in cy_modules:
1211 del sys.modules[name]
1212 # hasn't been refactored yet - do it now
1214 CY3_DIR = cy3_dir = os.path.join(WORKDIR, 'Cy3')
1215 if sys.version_info >= (3,1):
1216 refactor_for_py3(DISTDIR, cy3_dir)
1217 elif os.path.isdir(cy3_dir):
1218 sys.path.insert(0, cy3_dir)
1220 options.with_cython = False
1222 WITH_CYTHON = options.with_cython
1224 if options.coverage or options.coverage_xml:
1226 options.coverage = options.coverage_xml = False
1228 from coverage import coverage as _coverage
1229 coverage = _coverage(branch=True)
1234 global CompilationOptions, pyrex_default_options, cython_compile
1235 from Cython.Compiler.Main import \
1236 CompilationOptions, \
1237 default_options as pyrex_default_options, \
1238 compile as cython_compile
1239 from Cython.Compiler import Errors
1240 Errors.LEVEL = 0 # show all warnings
1241 from Cython.Compiler import Options
1242 Options.generate_cleanup_code = 3 # complete cleanup code
1243 from Cython.Compiler import DebugFlags
1244 DebugFlags.debug_temp_code_comments = 1
1247 UNITTEST_MODULE = "Cython"
1248 UNITTEST_ROOT = os.path.join(os.path.dirname(__file__), UNITTEST_MODULE)
1250 if os.path.exists(WORKDIR):
1251 for path in os.listdir(WORKDIR):
1252 if path in ("support", "Cy3"): continue
1253 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1254 if not os.path.exists(WORKDIR):
1255 os.makedirs(WORKDIR)
1257 sys.stderr.write("Python %s\n" % sys.version)
1258 sys.stderr.write("\n")
1260 from Cython.Compiler.Version import version
1261 sys.stderr.write("Running tests against Cython %s\n" % version)
1263 sys.stderr.write("Running tests without Cython.\n")
1265 if options.with_refnanny:
1266 from pyximport.pyxbuild import pyx_to_dll
1267 libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1269 pyxbuild_dir=os.path.join(WORKDIR, "support"))
1270 sys.path.insert(0, os.path.split(libpath)[0])
1271 CFLAGS.append("-DCYTHON_REFNANNY=1")
1273 if options.xml_output_dir and options.fork:
1274 # doesn't currently work together
1275 sys.stderr.write("Disabling forked testing to support XML test output\n")
1276 options.fork = False
1278 if WITH_CYTHON and options.language_level == 3:
1279 sys.stderr.write("Using Cython language level 3.\n")
1281 sys.stderr.write("\n")
1285 for ticket_number in options.tickets:
1287 cmd_args.append('ticket:%s' % ticket_number)
1289 for selector in cmd_args:
1290 if selector.startswith('bugs'):
1294 selectors = [ string_selector(r) for r in cmd_args ]
1296 selectors = [ lambda x, tags=None: True ]
1298 # Chech which external modules are not present and exclude tests
1299 # which depends on them (by prefix)
1301 missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES)
1302 version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES)
1303 exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1306 exclude_selectors += [ string_selector(r) for r in options.exclude ]
1309 exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, "bugs.txt")) ]
1311 if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1312 exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1315 if options.compiler:
1316 COMPILER = options.compiler
1319 languages.append('c')
1321 languages.append('cpp')
1323 test_suite = unittest.TestSuite()
1325 if options.unittests:
1326 collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1328 if options.doctests:
1329 collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1331 if options.filetests and languages:
1332 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1333 options.annotate_source, options.cleanup_workdir,
1334 options.cleanup_sharedlibs, options.pyregr,
1335 options.cython_only, languages, test_bugs,
1336 options.fork, options.language_level)
1337 test_suite.addTest(filetests.build_suite())
1339 if options.system_pyregr and languages:
1340 filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1341 options.annotate_source, options.cleanup_workdir,
1342 options.cleanup_sharedlibs, True,
1343 options.cython_only, languages, test_bugs,
1344 options.fork, options.language_level)
1346 filetests.handle_directory(
1347 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1350 if options.xml_output_dir:
1351 from Cython.Tests.xmlrunner import XMLTestRunner
1352 test_runner = XMLTestRunner(output=options.xml_output_dir,
1353 verbose=options.verbosity > 0)
1355 test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1357 result = test_runner.run(test_suite)
1359 if options.coverage or options.coverage_xml:
1361 ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1362 modules = [ module for name, module in sys.modules.items()
1363 if module is not None and
1364 name.startswith('Cython.Compiler.') and
1365 name[len('Cython.Compiler.'):] not in ignored_modules ]
1366 if options.coverage:
1367 coverage.report(modules, show_missing=0)
1368 if options.coverage_xml:
1369 coverage.xml_report(modules, outfile="coverage-report.xml")
1371 if missing_dep_excluder.tests_missing_deps:
1372 sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1373 for test in missing_dep_excluder.tests_missing_deps:
1374 sys.stderr.write(" %s\n" % test)
1376 if options.with_refnanny:
1378 sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1385 return_code = not result.wasSuccessful()
1388 check_thread_termination(ignore_seen=False)
1389 sys.exit(return_code)
1390 except PendingThreadsError:
1391 # normal program exit won't kill the threads, do it the hard way here
1392 os._exit(return_code)
1394 if __name__ == '__main__':
1397 except SystemExit: # <= Py2.4 ...
1400 traceback.print_exc()
1402 check_thread_termination(ignore_seen=False)
1403 except PendingThreadsError:
1404 # normal program exit won't kill the threads, do it the hard way here