Python doctest 模块,DocTestFinder() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用doctest.DocTestFinder()

项目:pytest-cython    作者:lgpage    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
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)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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
项目:godot-python    作者:touilleMan    | 项目源码 | 文件源码
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)
项目:godot-python    作者:touilleMan    | 项目源码 | 文件源码
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)
项目:coordinates    作者:markovmodel    | 项目源码 | 文件源码
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
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
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
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
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
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
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)
项目:node-gn    作者:Shouqun    | 项目源码 | 文件源码
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)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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
项目:GSM-scanner    作者:yosriayed    | 项目源码 | 文件源码
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)
项目:depot_tools    作者:webrtc-uwp    | 项目源码 | 文件源码
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)
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
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
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
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
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
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)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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
"""
项目:Price-Comparator    作者:Thejas-1    | 项目源码 | 文件源码
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))
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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
"""
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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
"""
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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
"""
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
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))
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
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
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
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
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
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)
项目:neighborhood_mood_aws    作者:jarrellmark    | 项目源码 | 文件源码
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))
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
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
"""
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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.
"""
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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
"""
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
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
"""
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.skipped = kwargs.pop('skipped', ())
        doctest.DocTestFinder.__init__(self, *args, **kwargs)
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
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)
项目:node-gn    作者:Shouqun    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.skipped = kwargs.pop('skipped', ())
        doctest.DocTestFinder.__init__(self, *args, **kwargs)
项目:node-gn    作者:Shouqun    | 项目源码 | 文件源码
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)
项目:hate-to-hugs    作者:sdoran35    | 项目源码 | 文件源码
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))
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
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))
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
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))
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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.
"""
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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
"""
项目:beepboop    作者:nicolehe    | 项目源码 | 文件源码
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))
项目:kind2anki    作者:prz3m    | 项目源码 | 文件源码
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))