我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用doctest.DocTestFinder()。
def collect(self): import doctest if self.fspath.basename == "conftest.py": module = self.config.pluginmanager._importconftest(self.fspath) else: try: # XXX patch pyimport in pytest._pytest.doctest.DoctestModule module = _patch_pyimport(self.fspath) except ImportError: if self.config.getoption('--cython-ignore-import-errors'): pytest.skip('unable to import module %r' % self.fspath) else: raise # uses internal doctest module parsing mechanism finder = doctest.DocTestFinder() optionflags = get_optionflags(self) checker = None if _get_checker is None else _get_checker() runner = doctest.DebugRunner(verbose=0, optionflags=optionflags, checker=checker) for test in finder.find(module, module.__name__): if test.examples: # skip empty doctests yield DoctestItem(test.name, self, runner, test)
def collect(self): import doctest if self.fspath.basename == "conftest.py": module = self.config.pluginmanager._importconftest(self.fspath) else: try: module = self.fspath.pyimport() except ImportError: if self.config.getvalue('doctest_ignore_import_errors'): pytest.skip('unable to import module %r' % self.fspath) else: raise # uses internal doctest module parsing mechanism finder = doctest.DocTestFinder() optionflags = get_optionflags(self) runner = doctest.DebugRunner(verbose=0, optionflags=optionflags, checker=_get_checker()) for test in finder.find(module, module.__name__): if test.examples: # skip empty doctests yield DoctestItem(test.name, self, runner, test)
def run_test_module(test_modules_list=None, test_prefix=None): suite = unittest.TestSuite() finder = doctest.DocTestFinder(exclude_empty=False) # finder for doctest if test_prefix: unittest.TestLoader.testMethodPrefix = test_prefix if not test_modules_list: test_modules_list = [] elif not isinstance(test_modules_list, list): test_modules_list = [test_modules_list] test_modules_list.append('__main__') for test in test_modules_list: # Doctest suite.addTest(doctest.DocTestSuite(test, test_finder=finder)) # unittest suite.addTest(unittest.loader.TestLoader().loadTestsFromModule(test)) TestRunner().run(suite)
def _run_object_doctest(obj, module): finder = doctest.DocTestFinder(verbose=verbose, recurse=False) runner = doctest.DocTestRunner(verbose=verbose) # Use the object's fully qualified name if it has one # Otherwise, use the module's name try: name = "%s.%s" % (obj.__module__, obj.__name__) except AttributeError: name = module.__name__ for example in finder.find(obj, name, module): runner.run(example) f, t = runner.failures, runner.tries if f: raise test.support.TestFailed("%d of %d doctests failed" % (f, t)) if verbose: print ('doctest (%s) ... %d tests with zero failures' % (module.__name__, t)) return f, t
def _run_object_doctest(obj, module): # Direct doctest output (normally just errors) to real stdout; doctest # output shouldn't be compared by regrtest. save_stdout = sys.stdout sys.stdout = test.test_support.get_original_stdout() try: finder = doctest.DocTestFinder(verbose=verbose, recurse=False) runner = doctest.DocTestRunner(verbose=verbose) # Use the object's fully qualified name if it has one # Otherwise, use the module's name try: name = "%s.%s" % (obj.__module__, obj.__name__) except AttributeError: name = module.__name__ for example in finder.find(obj, name, module): runner.run(example) f, t = runner.failures, runner.tries if f: raise test.test_support.TestFailed("%d of %d doctests failed" % (f, t)) finally: sys.stdout = save_stdout if verbose: print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t) return f, t
def _monkey_patch_testing_apply_setting(): """ this monkey patches the init methods of unittest.TestCase and doctest.DocTestFinder, in order to apply internal settings. """ import unittest import doctest _old_init = unittest.TestCase.__init__ def _new_init(self, *args, **kwargs): _old_init(self, *args, **kwargs) _setup_testing() unittest.TestCase.__init__ = _new_init _old_init_doc_test_finder = doctest.DocTestFinder.__init__ def _patched_init(self, *args, **kw): _setup_testing() _old_init_doc_test_finder(self, *args, **kw) doctest.DocTestFinder.__init__ = _patched_init
def __call__(self, result=None, runcondition=None, options=None):\ # pylint: disable=W0613 try: finder = DocTestFinder(skipped=self.skipped) suite = doctest.DocTestSuite(self.module, test_finder=finder) # XXX iirk doctest.DocTestCase._TestCase__exc_info = sys.exc_info except AttributeError: suite = SkippedSuite() # doctest may gork the builtins dictionnary # This happen to the "_" entry used by gettext old_builtins = builtins.__dict__.copy() try: return suite.run(result) finally: builtins.__dict__.clear() builtins.__dict__.update(old_builtins)
def collect(self): import doctest if self.fspath.basename == "conftest.py": module = self.config.pluginmanager._importconftest(self.fspath) else: try: module = self.fspath.pyimport() except ImportError: if self.config.getvalue('doctest_ignore_import_errors'): pytest.skip('unable to import module %r' % self.fspath) else: raise # satisfy `FixtureRequest` constructor... fixture_request = _setup_fixtures(self) doctest_globals = dict(getfixture=fixture_request.getfuncargvalue) # uses internal doctest module parsing mechanism finder = doctest.DocTestFinder() optionflags = get_optionflags(self) runner = doctest.DebugRunner(verbose=0, optionflags=optionflags, checker=_get_unicode_checker()) for test in finder.find(module, module.__name__, extraglobs=doctest_globals): if test.examples: # skip empty doctests yield DoctestItem(test.name, self, runner, test)
def configure(self, options, config): """Configure plugin. """ Plugin.configure(self, options, config) self.doctest_result_var = options.doctest_result_var self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.fixtures = options.doctestFixtures self.finder = doctest.DocTestFinder() self.optionflags = 0 if options.doctestOptions: flags = ",".join(options.doctestOptions).split(',') for flag in flags: if not flag or flag[0] not in '+-': raise ValueError( "Must specify doctest options with starting " + "'+' or '-'. Got %s" % (flag,)) mode, option_name = flag[0], flag[1:] option_flag = doctest.OPTIONFLAGS_BY_NAME.get(option_name) if not option_flag: raise ValueError("Unknown doctest option %s" % (option_name,)) if mode == '+': self.optionflags |= option_flag elif mode == '-': self.optionflags &= ~option_flag
def configure(self, options, config): Plugin.configure(self, options, config) # Pull standard doctest plugin out of config; we will do doctesting config.plugins.plugins = [p for p in config.plugins.plugins if p.name != 'doctest'] self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.parser = doctest.DocTestParser() self.finder = DocTestFinder() self.checker = IPDoctestOutputChecker() self.globs = None self.extraglobs = None
def configure(self, options, config): #print "Configuring nose plugin:", self.name # dbg Plugin.configure(self, options, config) # Pull standard doctest plugin out of config; we will do doctesting config.plugins.plugins = [p for p in config.plugins.plugins if p.name != 'doctest'] self.doctest_tests = options.ipdoctest_tests self.extension = tolist(options.ipdoctest_extension) self.parser = IPDocTestParser() self.finder = DocTestFinder(parser=self.parser) self.checker = IPDoctestOutputChecker() self.globs = None self.extraglobs = None
def __init__(self, verbose=False): """New decorator. Parameters ---------- verbose : boolean, optional (False) Passed to the doctest finder and runner to control verbosity. """ self.verbose = verbose # We can reuse the same finder for all instances self.finder = DocTestFinder(verbose=verbose, recurse=False)
def displayhook(): r""" Test that changing sys.displayhook doesn't matter for doctest. >>> import sys >>> orig_displayhook = sys.displayhook >>> def my_displayhook(x): ... print('hi!') >>> sys.displayhook = my_displayhook >>> def f(): ... ''' ... >>> 3 ... 3 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> r = doctest.DocTestRunner(verbose=False).run(test) >>> post_displayhook = sys.displayhook We need to restore sys.displayhook now, so that we'll be able to test results. >>> sys.displayhook = orig_displayhook Ok, now we can check that everything is ok. >>> r TestResults(failed=0, attempted=1) >>> post_displayhook is my_displayhook True """
def configure(self, options, config): # it is overriden in order to fix doctest options discovery Plugin.configure(self, options, config) self.doctest_result_var = options.doctest_result_var self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.fixtures = options.doctestFixtures self.finder = doctest.DocTestFinder() #super(DoctestPluginHelper, self).configure(options, config) self.optionflags = 0 self.options = {} if options.doctestOptions: stroptions = ",".join(options.doctestOptions).split(',') for stroption in stroptions: try: if stroption.startswith('+'): self.optionflags |= doctest.OPTIONFLAGS_BY_NAME[stroption[1:]] continue elif stroption.startswith('-'): self.optionflags &= ~doctest.OPTIONFLAGS_BY_NAME[stroption[1:]] continue try: key,value=stroption.split('=') except ValueError: pass else: if not key in self.OPTION_BY_NAME: raise ValueError() self.options[key]=value continue except (AttributeError, ValueError, KeyError): raise ValueError("Unknown doctest option {}".format(stroption)) else: raise ValueError("Doctest option is not a flag or a key/value pair: {} ".format(stroption))
def non_Python_modules(): r""" Finding Doctests in Modules Not Written in Python ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DocTestFinder can also find doctests in most modules not written in Python. We'll use builtins as an example, since it almost certainly isn't written in plain ol' Python and is guaranteed to be available. >>> import builtins >>> tests = doctest.DocTestFinder().find(builtins) >>> 790 < len(tests) < 800 # approximate number of objects with docstrings True >>> real_tests = [t for t in tests if len(t.examples) > 0] >>> len(real_tests) # objects that actually have doctests 8 >>> for t in real_tests: ... print('{} {}'.format(len(t.examples), t.name)) ... 1 builtins.bin 3 builtins.float.as_integer_ratio 2 builtins.float.fromhex 2 builtins.float.hex 1 builtins.hex 1 builtins.int 2 builtins.int.bit_length 1 builtins.oct Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio', 'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod, and 'int' is a type. """
def __init__(self, *args, **kwargs): self.skipped = kwargs.pop('skipped', ()) doctest.DocTestFinder.__init__(self, *args, **kwargs)
def _get_test(self, obj, name, module, globs, source_lines): """override default _get_test method to be able to skip tests according to skipped attribute's value """ if getattr(obj, '__name__', '') in self.skipped: return None return doctest.DocTestFinder._get_test(self, obj, name, module, globs, source_lines)
def _do_discovery(self, options): start_dir = options.start pattern = options.pattern top_level_dir = options.top loader = unittest.TestLoader() self.test = loader.discover(start_dir, pattern, top_level_dir) finder = doctest.DocTestFinder(exclude_empty=False) for name in glob.glob('mechanize/*.py'): name = os.path.basename(name).rpartition('.')[0] self.test.addTest( doctest.DocTestSuite('mechanize.' + name, test_finder=finder)) self.test.addTest(doctest.DocFileSuite( *glob.glob('test/*.doctest'), module_relative=False))