Python doctest.DocTestFinder() Examples

The following are code examples for showing how to use doctest.DocTestFinder(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_zipimport_support.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example 2
Project: NiujiaoDebugger   Author: MrSrc   File: test_zipimport_support.py    GNU General Public License v3.0 6 votes vote down vote up
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.__qualname__)
    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 
Example 3
Project: Alexa-Ecovacs   Author: EtienneMD   File: doctest.py    MIT License 6 votes vote down vote up
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) 
Example 4
Project: ironpython2   Author: IronLanguages   File: test_zipimport_support.py    Apache License 2.0 6 votes vote down vote up
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 
Example 5
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_zipimport_support.py    GNU General Public License v3.0 6 votes vote down vote up
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 
Example 6
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_zipimport_support.py    GNU General Public License v2.0 6 votes vote down vote up
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.__qualname__)
    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 
Example 7
Project: Computable   Author: ktraunmueller   File: doctests.py    MIT License 6 votes vote down vote up
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:
                try:
                    if flag.startswith('+'):
                        self.optionflags |= getattr(doctest, flag[1:])
                    elif flag.startswith('-'):
                        self.optionflags &= ~getattr(doctest, flag[1:])
                    else:
                        raise ValueError(
                            "Must specify doctest options with starting " +
                            "'+' or '-'.  Got %s" % (flag,))
                except AttributeError:
                    raise ValueError("Unknown doctest option %s" %
                                     (flag[1:],)) 
Example 8
Project: oss-ftp   Author: aliyun   File: test_zipimport_support.py    MIT License 6 votes vote down vote up
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 
Example 9
Project: conf   Author: XonqNopp   File: testlib.py    GNU General Public License v3.0 6 votes vote down vote up
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) 
Example 10
Project: pytest-cython   Author: lgpage   File: plugin.py    MIT License 6 votes vote down vote up
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) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_doctest.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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
""" 
Example 12
Project: Repobot   Author: Desgard   File: ipdoctest.py    MIT License 5 votes vote down vote up
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 
Example 13
Project: Repobot   Author: Desgard   File: ipdoctest.py    MIT License 5 votes vote down vote up
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 
Example 14
Project: Repobot   Author: Desgard   File: ipunittest.py    MIT License 5 votes vote down vote up
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) 
Example 15
Project: razzy-spinner   Author: rafasashi   File: doctest_nose_plugin.py    GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example 16
Project: OpenBottle   Author: xiaozhuchacha   File: doctest_nose_plugin.py    MIT License 5 votes vote down vote up
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)) 
Example 17
Project: OpenBottle   Author: xiaozhuchacha   File: doctest_nose_plugin.py    MIT License 5 votes vote down vote up
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)) 
Example 18
Project: NiujiaoDebugger   Author: MrSrc   File: test_doctest.py    GNU General Public License v3.0 5 votes vote down vote up
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)
    >>> 800 < len(tests) < 820 # 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.
""" 
Example 19
Project: NiujiaoDebugger   Author: MrSrc   File: test_doctest.py    GNU General Public License v3.0 5 votes vote down vote up
def test_empty_namespace_package(self):
        pkg_name = 'doctest_empty_pkg'
        with tempfile.TemporaryDirectory() as parent_dir:
            pkg_dir = os.path.join(parent_dir, pkg_name)
            os.mkdir(pkg_dir)
            sys.path.append(parent_dir)
            try:
                mod = importlib.import_module(pkg_name)
            finally:
                support.forget(pkg_name)
                sys.path.pop()
            assert doctest.DocTestFinder().find(mod) == [] 
Example 20
Project: NiujiaoDebugger   Author: MrSrc   File: test_doctest.py    GNU General Public License v3.0 5 votes vote down vote up
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
""" 
Example 21
Project: Health-Checker   Author: KriAga   File: doctest_nose_plugin.py    MIT License 5 votes vote down vote up
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)) 
Example 22
Project: ironpython2   Author: IronLanguages   File: test_doctest.py    Apache License 2.0 5 votes vote down vote up
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
""" 
Example 23
Project: ip-navigator   Author: ip-tools   File: doctest_nose_plugin.py    GNU Affero General Public License v3.0 5 votes vote down vote up
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)) 
Example 24
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_doctest.py    GNU General Public License v2.0 5 votes vote down vote up
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)
    >>> 800 < len(tests) < 820 # 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.
""" 
Example 25
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_doctest.py    GNU General Public License v2.0 5 votes vote down vote up
def test_empty_namespace_package(self):
        pkg_name = 'doctest_empty_pkg'
        with tempfile.TemporaryDirectory() as parent_dir:
            pkg_dir = os.path.join(parent_dir, pkg_name)
            os.mkdir(pkg_dir)
            sys.path.append(parent_dir)
            try:
                mod = importlib.import_module(pkg_name)
            finally:
                support.forget(pkg_name)
                sys.path.pop()
            assert doctest.DocTestFinder().find(mod) == [] 
Example 26
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_doctest.py    GNU General Public License v2.0 5 votes vote down vote up
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
""" 
Example 27
Project: vwoptimize   Author: denik   File: shelldoctest.py    MIT License 5 votes vote down vote up
def testmod(m=None, name=None, globs=None, verbose=None,
            report=True, optionflags=doctest.ELLIPSIS, extraglobs=None,
            raise_on_error=False, exclude_empty=False,
            verbose_level=None, filters=None,
            ):
    if globs == None:
        globs = dict()
    globs.update({"system_command": system_command})
    global master
    if m is None:
        m = sys.modules.get('__main__')
    if not inspect.ismodule(m):
        raise TypeError("testmod: module required; %r" % (m,))
    if name is None:
        name = m.__name__
    finder = doctest.DocTestFinder(parser=ShellDocTestParser(), exclude_empty=exclude_empty)
    if raise_on_error:
        runner = doctest.DebugRunner(verbose=verbose, optionflags=optionflags)
    else:
        runner = ShellDocTestRunner(verbose=verbose, verbose_level=verbose_level, optionflags=optionflags)
    tests = finder.find(m, name, globs=globs, extraglobs=extraglobs)
    if filters:
        _tests = list()
        z = dict([(k,v) for v,k in enumerate(filters)])
        for test in tests:
            test.examples = sorted(filter(lambda x: x.label in filters, test.examples),
                                cmp=lambda x,y: cmp(z[x.label], z[y.label]))
            _tests.append(test)
        tests = _tests
    for test in tests:
        runner.run(test)
    if report:
        runner.summarize()
    if master is None:
        master = runner
    else:
        master.merge(runner)
    if sys.version_info < (2, 6):
        return runner.failures, runner.tries
    return doctest.TestResults(runner.failures, runner.tries) 
Example 28
Project: Computable   Author: ktraunmueller   File: ipdoctest.py    MIT License 5 votes vote down vote up
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 
Example 29
Project: Computable   Author: ktraunmueller   File: ipdoctest.py    MIT License 5 votes vote down vote up
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 
Example 30
Project: oss-ftp   Author: aliyun   File: test_doctest.py    MIT License 5 votes vote down vote up
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
""" 
Example 31
Project: conf   Author: XonqNopp   File: testlib.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.skipped = kwargs.pop('skipped', ())
        doctest.DocTestFinder.__init__(self, *args, **kwargs) 
Example 32
Project: conf   Author: XonqNopp   File: testlib.py    GNU General Public License v3.0 5 votes vote down vote up
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) 
Example 33
Project: conf   Author: XonqNopp   File: testlib.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.skipped = kwargs.pop('skipped', ())
        doctest.DocTestFinder.__init__(self, *args, **kwargs) 
Example 34
Project: conf   Author: XonqNopp   File: testlib.py    GNU General Public License v3.0 5 votes vote down vote up
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) 
Example 35
Project: eden   Author: facebookexperimental   File: test-doctest.py    GNU General Public License v2.0 5 votes vote down vote up
def testmod(name, optionflags=0, testtarget=None):
    __import__(name)
    mod = sys.modules[name]
    if testtarget is not None:
        mod = getattr(mod, testtarget)

    # minimal copy of doctest.testmod()
    finder = doctest.DocTestFinder()
    checker = None
    if ispy3:
        checker = py3docchecker()
    runner = doctest.DocTestRunner(checker=checker, optionflags=optionflags)
    for test in finder.find(mod, name):
        runner.run(test)
    runner.summarize() 
Example 36
Project: FancyWord   Author: EastonLee   File: doctest_nose_plugin.py    GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example 37
Project: url_shortener   Author: martydill   File: ipdoctest.py    MIT License 5 votes vote down vote up
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 
Example 38
Project: url_shortener   Author: martydill   File: ipdoctest.py    MIT License 5 votes vote down vote up
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 
Example 39
Project: url_shortener   Author: martydill   File: ipunittest.py    MIT License 5 votes vote down vote up
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) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_doctest.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def basics(): r"""
Unit tests for the `DocTestRunner` class.

DocTestRunner is used to run DocTest test cases, and to accumulate
statistics.  Here's a simple DocTest case we can use:

    >>> def f(x):
    ...     '''
    ...     >>> x = 12
    ...     >>> print x
    ...     12
    ...     >>> x//2
    ...     6
    ...     '''
    >>> test = doctest.DocTestFinder().find(f)[0]

The main DocTestRunner interface is the `run` method, which runs a
given DocTest case in a given namespace (globs).  It returns a tuple
`(f,t)`, where `f` is the number of failed tests and `t` is the number
of tried tests.

    >>> doctest.DocTestRunner(verbose=False).run(test)
    TestResults(failed=0, attempted=3)

If any example produces incorrect output, then the test runner reports
the failure and proceeds to the next example:

    >>> def f(x):
    ...     '''
    ...     >>> x = 12
    ...     >>> print x
    ...     14
    ...     >>> x//2
    ...     6
    ...     '''
    >>> test = doctest.DocTestFinder().find(f)[0]
    >>> doctest.DocTestRunner(verbose=True).run(test)
    ... # doctest: +ELLIPSIS
    Trying:
        x = 12
    Expecting nothing
    ok
    Trying:
        print x
    Expecting:
        14
    **********************************************************************
    File ..., line 4, in f
    Failed example:
        print x
    Expected:
        14
    Got:
        12
    Trying:
        x//2
    Expecting:
        6
    ok
    TestResults(failed=1, attempted=3)
""" 
Example 41
Project: Repobot   Author: Desgard   File: ipdoctest.py    MIT License 4 votes vote down vote up
def _find(self, tests, obj, name, module, source_lines, globs, seen):
        """
        Find tests for the given object and any contained objects, and
        add them to `tests`.
        """
        print('_find for:', obj, name, module)  # dbg
        if hasattr(obj,"skip_doctest"):
            #print 'SKIPPING DOCTEST FOR:',obj  # dbg
            obj = DocTestSkip(obj)
        
        doctest.DocTestFinder._find(self,tests, obj, name, module,
                                    source_lines, globs, seen)

        # Below we re-run pieces of the above method with manual modifications,
        # because the original code is buggy and fails to correctly identify
        # doctests in extension modules.

        # Local shorthands
        from inspect import isroutine, isclass

        # Look for tests in a module's contained objects.
        if inspect.ismodule(obj) and self._recurse:
            for valname, val in obj.__dict__.items():
                valname1 = '%s.%s' % (name, valname)
                if ( (isroutine(val) or isclass(val))
                     and self._from_module(module, val) ):

                    self._find(tests, val, valname1, module, source_lines,
                               globs, seen)

        # Look for tests in a class's contained objects.
        if inspect.isclass(obj) and self._recurse:
            #print 'RECURSE into class:',obj  # dbg
            for valname, val in obj.__dict__.items():
                # Special handling for staticmethod/classmethod.
                if isinstance(val, staticmethod):
                    val = getattr(obj, valname)
                if isinstance(val, classmethod):
                    val = getattr(obj, valname).__func__

                # Recurse to methods, properties, and nested classes.
                if ((inspect.isfunction(val) or inspect.isclass(val) or
                     inspect.ismethod(val) or
                      isinstance(val, property)) and
                      self._from_module(module, val)):
                    valname = '%s.%s' % (name, valname)
                    self._find(tests, val, valname, module, source_lines,
                               globs, seen) 
Example 42
Project: LaserTOF   Author: kyleuckert   File: utils.py    MIT License 4 votes vote down vote up
def rundocs(filename=None, raise_on_error=True):
    """
    Run doctests found in the given file.

    By default `rundocs` raises an AssertionError on failure.

    Parameters
    ----------
    filename : str
        The path to the file for which the doctests are run.
    raise_on_error : bool
        Whether to raise an AssertionError when a doctest fails. Default is
        True.

    Notes
    -----
    The doctests can be run by the user/developer by adding the ``doctests``
    argument to the ``test()`` call. For example, to run all tests (including
    doctests) for `numpy.lib`:

    >>> np.lib.test(doctests=True) #doctest: +SKIP
    """
    from numpy.compat import npy_load_module
    import doctest
    if filename is None:
        f = sys._getframe(1)
        filename = f.f_globals['__file__']
    name = os.path.splitext(os.path.basename(filename))[0]
    m = npy_load_module(name, filename)

    tests = doctest.DocTestFinder().find(m)
    runner = doctest.DocTestRunner(verbose=False)

    msg = []
    if raise_on_error:
        out = lambda s: msg.append(s)
    else:
        out = None

    for test in tests:
        runner.run(test, out=out)

    if runner.failures > 0 and raise_on_error:
        raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg)) 
Example 43
Project: LaserTOF   Author: kyleuckert   File: noseclasses.py    MIT License 4 votes vote down vote up
def _find(self, tests, obj, name, module, source_lines, globs, seen):
        """
        Find tests for the given object and any contained objects, and
        add them to `tests`.
        """

        doctest.DocTestFinder._find(self, tests, obj, name, module,
                                    source_lines, globs, seen)

        # Below we re-run pieces of the above method with manual modifications,
        # because the original code is buggy and fails to correctly identify
        # doctests in extension modules.

        # Local shorthands
        from inspect import (
            isroutine, isclass, ismodule, isfunction, ismethod
            )

        # Look for tests in a module's contained objects.
        if ismodule(obj) and self._recurse:
            for valname, val in obj.__dict__.items():
                valname1 = '%s.%s' % (name, valname)
                if ( (isroutine(val) or isclass(val))
                     and self._from_module(module, val)):

                    self._find(tests, val, valname1, module, source_lines,
                               globs, seen)

        # Look for tests in a class's contained objects.
        if isclass(obj) and self._recurse:
            for valname, val in obj.__dict__.items():
                # Special handling for staticmethod/classmethod.
                if isinstance(val, staticmethod):
                    val = getattr(obj, valname)
                if isinstance(val, classmethod):
                    val = getattr(obj, valname).__func__

                # Recurse to methods, properties, and nested classes.
                if ((isfunction(val) or isclass(val) or
                     ismethod(val) or isinstance(val, property)) and
                      self._from_module(module, val)):
                    valname = '%s.%s' % (name, valname)
                    self._find(tests, val, valname, module, source_lines,
                               globs, seen)


# second-chance checker; if the default comparison doesn't
# pass, then see if the expected output string contains flags that
# tell us to ignore the output 
Example 44
Project: NiujiaoDebugger   Author: MrSrc   File: test_doctest.py    GNU General Public License v3.0 4 votes vote down vote up
def basics(): r"""
Unit tests for the `DocTestRunner` class.

DocTestRunner is used to run DocTest test cases, and to accumulate
statistics.  Here's a simple DocTest case we can use:

    >>> def f(x):
    ...     '''
    ...     >>> x = 12
    ...     >>> print(x)
    ...     12
    ...     >>> x//2
    ...     6
    ...     '''
    >>> test = doctest.DocTestFinder().find(f)[0]

The main DocTestRunner interface is the `run` method, which runs a
given DocTest case in a given namespace (globs).  It returns a tuple
`(f,t)`, where `f` is the number of failed tests and `t` is the number
of tried tests.

    >>> doctest.DocTestRunner(verbose=False).run(test)
    TestResults(failed=0, attempted=3)

If any example produces incorrect output, then the test runner reports
the failure and proceeds to the next example:

    >>> def f(x):
    ...     '''
    ...     >>> x = 12
    ...     >>> print(x)
    ...     14
    ...     >>> x//2
    ...     6
    ...     '''
    >>> test = doctest.DocTestFinder().find(f)[0]
    >>> doctest.DocTestRunner(verbose=True).run(test)
    ... # doctest: +ELLIPSIS
    Trying:
        x = 12
    Expecting nothing
    ok
    Trying:
        print(x)
    Expecting:
        14
    **********************************************************************
    File ..., line 4, in f
    Failed example:
        print(x)
    Expected:
        14
    Got:
        12
    Trying:
        x//2
    Expecting:
        6
    ok
    TestResults(failed=1, attempted=3)
""" 
Example 45
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: utils.py    MIT License 4 votes vote down vote up
def rundocs(filename=None, raise_on_error=True):
    """
    Run doctests found in the given file.

    By default `rundocs` raises an AssertionError on failure.

    Parameters
    ----------
    filename : str
        The path to the file for which the doctests are run.
    raise_on_error : bool
        Whether to raise an AssertionError when a doctest fails. Default is
        True.

    Notes
    -----
    The doctests can be run by the user/developer by adding the ``doctests``
    argument to the ``test()`` call. For example, to run all tests (including
    doctests) for `numpy.lib`:

    >>> np.lib.test(doctests=True)  # doctest: +SKIP
    """
    from numpy.compat import npy_load_module
    import doctest
    if filename is None:
        f = sys._getframe(1)
        filename = f.f_globals['__file__']
    name = os.path.splitext(os.path.basename(filename))[0]
    m = npy_load_module(name, filename)

    tests = doctest.DocTestFinder().find(m)
    runner = doctest.DocTestRunner(verbose=False)

    msg = []
    if raise_on_error:
        out = lambda s: msg.append(s)
    else:
        out = None

    for test in tests:
        runner.run(test, out=out)

    if runner.failures > 0 and raise_on_error:
        raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg)) 
Example 46
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: noseclasses.py    MIT License 4 votes vote down vote up
def _find(self, tests, obj, name, module, source_lines, globs, seen):
        """
        Find tests for the given object and any contained objects, and
        add them to `tests`.
        """

        doctest.DocTestFinder._find(self, tests, obj, name, module,
                                    source_lines, globs, seen)

        # Below we re-run pieces of the above method with manual modifications,
        # because the original code is buggy and fails to correctly identify
        # doctests in extension modules.

        # Local shorthands
        from inspect import (
            isroutine, isclass, ismodule, isfunction, ismethod
            )

        # Look for tests in a module's contained objects.
        if ismodule(obj) and self._recurse:
            for valname, val in obj.__dict__.items():
                valname1 = '%s.%s' % (name, valname)
                if ( (isroutine(val) or isclass(val))
                     and self._from_module(module, val)):

                    self._find(tests, val, valname1, module, source_lines,
                               globs, seen)

        # Look for tests in a class's contained objects.
        if isclass(obj) and self._recurse:
            for valname, val in obj.__dict__.items():
                # Special handling for staticmethod/classmethod.
                if isinstance(val, staticmethod):
                    val = getattr(obj, valname)
                if isinstance(val, classmethod):
                    val = getattr(obj, valname).__func__

                # Recurse to methods, properties, and nested classes.
                if ((isfunction(val) or isclass(val) or
                     ismethod(val) or isinstance(val, property)) and
                      self._from_module(module, val)):
                    valname = '%s.%s' % (name, valname)
                    self._find(tests, val, valname, module, source_lines,
                               globs, seen)


# second-chance checker; if the default comparison doesn't
# pass, then see if the expected output string contains flags that
# tell us to ignore the output 
Example 47
Project: recruit   Author: Frank-qlu   File: utils.py    Apache License 2.0 4 votes vote down vote up
def rundocs(filename=None, raise_on_error=True):
    """
    Run doctests found in the given file.

    By default `rundocs` raises an AssertionError on failure.

    Parameters
    ----------
    filename : str
        The path to the file for which the doctests are run.
    raise_on_error : bool
        Whether to raise an AssertionError when a doctest fails. Default is
        True.

    Notes
    -----
    The doctests can be run by the user/developer by adding the ``doctests``
    argument to the ``test()`` call. For example, to run all tests (including
    doctests) for `numpy.lib`:

    >>> np.lib.test(doctests=True)  # doctest: +SKIP
    """
    from numpy.compat import npy_load_module
    import doctest
    if filename is None:
        f = sys._getframe(1)
        filename = f.f_globals['__file__']
    name = os.path.splitext(os.path.basename(filename))[0]
    m = npy_load_module(name, filename)

    tests = doctest.DocTestFinder().find(m)
    runner = doctest.DocTestRunner(verbose=False)

    msg = []
    if raise_on_error:
        out = lambda s: msg.append(s)
    else:
        out = None

    for test in tests:
        runner.run(test, out=out)

    if runner.failures > 0 and raise_on_error:
        raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg)) 
Example 48
Project: recruit   Author: Frank-qlu   File: noseclasses.py    Apache License 2.0 4 votes vote down vote up
def _find(self, tests, obj, name, module, source_lines, globs, seen):
        """
        Find tests for the given object and any contained objects, and
        add them to `tests`.
        """

        doctest.DocTestFinder._find(self, tests, obj, name, module,
                                    source_lines, globs, seen)

        # Below we re-run pieces of the above method with manual modifications,
        # because the original code is buggy and fails to correctly identify
        # doctests in extension modules.

        # Local shorthands
        from inspect import (
            isroutine, isclass, ismodule, isfunction, ismethod
            )

        # Look for tests in a module's contained objects.
        if ismodule(obj) and self._recurse:
            for valname, val in obj.__dict__.items():
                valname1 = '%s.%s' % (name, valname)
                if ( (isroutine(val) or isclass(val))
                     and self._from_module(module, val)):

                    self._find(tests, val, valname1, module, source_lines,
                               globs, seen)

        # Look for tests in a class's contained objects.
        if isclass(obj) and self._recurse:
            for valname, val in obj.__dict__.items():
                # Special handling for staticmethod/classmethod.
                if isinstance(val, staticmethod):
                    val = getattr(obj, valname)
                if isinstance(val, classmethod):
                    val = getattr(obj, valname).__func__

                # Recurse to methods, properties, and nested classes.
                if ((isfunction(val) or isclass(val) or
                     ismethod(val) or isinstance(val, property)) and
                      self._from_module(module, val)):
                    valname = '%s.%s' % (name, valname)
                    self._find(tests, val, valname, module, source_lines,
                               globs, seen)


# second-chance checker; if the default comparison doesn't
# pass, then see if the expected output string contains flags that
# tell us to ignore the output 
Example 49
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: utils.py    GNU General Public License v3.0 4 votes vote down vote up
def rundocs(filename=None, raise_on_error=True):
    """
    Run doctests found in the given file.

    By default `rundocs` raises an AssertionError on failure.

    Parameters
    ----------
    filename : str
        The path to the file for which the doctests are run.
    raise_on_error : bool
        Whether to raise an AssertionError when a doctest fails. Default is
        True.

    Notes
    -----
    The doctests can be run by the user/developer by adding the ``doctests``
    argument to the ``test()`` call. For example, to run all tests (including
    doctests) for `numpy.lib`:

    >>> np.lib.test(doctests=True) #doctest: +SKIP
    """
    import doctest, imp
    if filename is None:
        f = sys._getframe(1)
        filename = f.f_globals['__file__']
    name = os.path.splitext(os.path.basename(filename))[0]
    path = [os.path.dirname(filename)]
    file, pathname, description = imp.find_module(name, path)
    try:
        m = imp.load_module(name, file, pathname, description)
    finally:
        file.close()

    tests = doctest.DocTestFinder().find(m)
    runner = doctest.DocTestRunner(verbose=False)

    msg = []
    if raise_on_error:
        out = lambda s: msg.append(s)
    else:
        out = None

    for test in tests:
        runner.run(test, out=out)

    if runner.failures > 0 and raise_on_error:
        raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg)) 
Example 50
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: noseclasses.py    GNU General Public License v3.0 4 votes vote down vote up
def _find(self, tests, obj, name, module, source_lines, globs, seen):
        """
        Find tests for the given object and any contained objects, and
        add them to `tests`.
        """

        doctest.DocTestFinder._find(self, tests, obj, name, module,
                                    source_lines, globs, seen)

        # Below we re-run pieces of the above method with manual modifications,
        # because the original code is buggy and fails to correctly identify
        # doctests in extension modules.

        # Local shorthands
        from inspect import isroutine, isclass, ismodule, isfunction, \
                            ismethod

        # Look for tests in a module's contained objects.
        if ismodule(obj) and self._recurse:
            for valname, val in obj.__dict__.items():
                valname1 = '%s.%s' % (name, valname)
                if ( (isroutine(val) or isclass(val))
                     and self._from_module(module, val) ):

                    self._find(tests, val, valname1, module, source_lines,
                               globs, seen)


        # Look for tests in a class's contained objects.
        if isclass(obj) and self._recurse:
            #print 'RECURSE into class:',obj  # dbg
            for valname, val in obj.__dict__.items():
                #valname1 = '%s.%s' % (name, valname)  # dbg
                #print 'N',name,'VN:',valname,'val:',str(val)[:77] # dbg
                # Special handling for staticmethod/classmethod.
                if isinstance(val, staticmethod):
                    val = getattr(obj, valname)
                if isinstance(val, classmethod):
                    val = getattr(obj, valname).__func__

                # Recurse to methods, properties, and nested classes.
                if ((isfunction(val) or isclass(val) or
                     ismethod(val) or isinstance(val, property)) and
                      self._from_module(module, val)):
                    valname = '%s.%s' % (name, valname)
                    self._find(tests, val, valname, module, source_lines,
                               globs, seen)


# second-chance checker; if the default comparison doesn't
# pass, then see if the expected output string contains flags that
# tell us to ignore the output