Exemple #1
0
        def collect(self):
            # When running directly from pytest we need to make sure that we
            # don't accidentally import setup.py!
            if self.fspath.basename == "setup.py":
                return
            elif self.fspath.basename == "conftest.py":
                try:
                    module = self.config._conftest.importconftest(self.fspath)
                except AttributeError:  # pytest >= 2.8.0
                    module = self.config.pluginmanager._importconftest(
                        self.fspath)
            else:
                try:
                    module = self.fspath.pyimport()
                    # Just ignore searching modules that can't be imported when
                    # collecting doctests
                except ImportError:
                    return

            # uses internal doctest module parsing mechanism
            finder = DocTestFinderPlus()
            runner = doctest.DebugRunner(verbose=False,
                                         optionflags=opts,
                                         checker=OutputChecker())
            for test in finder.find(module):
                if test.examples:  # skip empty doctests
                    if config.getoption('remote_data', 'none') != 'any':
                        for example in test.examples:
                            if example.options.get(REMOTE_DATA):
                                example.options[doctest.SKIP] = True

                    yield doctest_plugin.DoctestItem(test.name, self, runner,
                                                     test)
Exemple #2
0
 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)
Exemple #3
0
def rundoctest(text, ns=None, eraise=False):
    """Run a the input source as a doctest, in the caller's namespace.

    :Parameters:
      text : str
        Source to execute.

    :Keywords:
      ns : dict (None)
        Namespace where the code should be executed.  If not given, the
        caller's locals and globals are used.
      eraise : bool (False)
        If true, immediately raise any exceptions instead of reporting them at
        the end.  This allows you to then do interactive debugging via
        IPython's facilities (use %debug after the fact, or with %pdb for
        automatic activation).
    """

    name = 'interactive doctest'
    filename = '<IPython console>'

    if eraise:
        runner = doctest.DebugRunner()
    else:
        runner = doctest.DocTestRunner()

    parser = doctest.DocTestParser()
    if ns is None:
        f = sys._getframe(1)
        ns = f.f_globals.copy()
        ns.update(f.f_locals)

    test = parser.get_doctest(text, ns, name, filename, 0)
    runner.run(test)
    runner.summarize(True)
Exemple #4
0
        def collect(self):
            if PYTEST_GE_6_3:
                fspath = self.path
                filepath = self.path.name
            else:
                fspath = self.fspath
                filepath = self.fspath.basename

            encoding = self.config.getini("doctest_encoding")
            text = fspath.read_text(encoding)
            filename = str(fspath)
            globs = {"__name__": "__main__"}

            optionflags = get_optionflags(self) | FIX

            runner = doctest.DebugRunner(verbose=False,
                                         optionflags=optionflags,
                                         checker=OutputChecker())

            parser = DocTestParserPlus()
            test = parser.get_doctest(text, globs, filepath, filename, 0)
            if test.examples:
                try:
                    yield doctest_plugin.DoctestItem.from_parent(
                        self, name=test.name, runner=runner, dtest=test)
                except AttributeError:
                    # pytest < 5.4
                    yield doctest_plugin.DoctestItem(test.name, self, runner,
                                                     test)
Exemple #5
0
    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.from_parent(self,
                                              name=test.name,
                                              runner=runner,
                                              dtest=test)
    def collect(self):
        # Adapted from pytest
        import doctest
        if self.fspath.basename == "conftest.py":
            # Copied from pytest-doctestplus
            if PYTEST_GT_5:
                module = self.config.pluginmanager._importconftest(
                    self.fspath, self.config.getoption("importmode"))
            else:
                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())
        # End copied from pytest

        for method in module.__dict__.values():
            if _is_numpy_ufunc(method):
                for test in finder.find(method, module=module):
                    if test.examples:  # skip empty doctests
                        yield DoctestItem.from_parent(self,
                                                      name=test.name,
                                                      runner=runner,
                                                      dtest=test)
Exemple #7
0
        def collect(self):
            if self.fspath.basename == "conftest.py":
                try:
                    module = self.config._conftest.importconftest(self.fspath)
                except AttributeError:  # pytest >= 2.8.0
                    module = self.config.pluginmanager._importconftest(
                        self.fspath)
            else:
                try:
                    module = self.fspath.pyimport()
                    # Just ignore searching modules that can't be imported when
                    # collecting doctests
                except ImportError:
                    raise StopIteration

            # uses internal doctest module parsing mechanism
            finder = DocTestFinderPlus()
            runner = doctest.DebugRunner(verbose=False, optionflags=opts)
            for test in finder.find(module):
                if test.examples:  # skip empty doctests
                    if not config.getvalue("remote_data"):
                        for example in test.examples:
                            if example.options.get(REMOTE_DATA):
                                example.options[doctest.SKIP] = True

                    yield doctest_plugin.DoctestItem(test.name, self, runner,
                                                     test)
Exemple #8
0
    def collect(self):
        import numpy as np
        # Copied from pytest
        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())
        # End copied from pytest

        for method in module.__dict__.values():
            if isinstance(method, np.ufunc) or isinstance(
                    getattr(method, '__wrapped__', None), np.ufunc):
                for test in finder.find(method, module=module):
                    if test.examples:  # skip empty doctests
                        yield DoctestItem(test.name, self, runner, test)
Exemple #9
0
        def collect(self):
            # When running directly from pytest we need to make sure that we
            # don't accidentally import setup.py!
            if self.fspath.basename == "setup.py":
                return
            elif self.fspath.basename == "conftest.py":
                module = self.config.pluginmanager._importconftest(self.fspath)
            else:
                try:
                    module = self.fspath.pyimport()
                except ImportError:
                    pytest.skip("unable to import module %r" % self.fspath)
                    # NOT USED: While correct, this breaks existing behavior.
                    # if self.config.getvalue("doctest_ignore_import_errors"):
                    #     pytest.skip("unable to import module %r" % self.fspath)
                    # else:
                    #     raise

            options = get_optionflags(self) | FIX

            # uses internal doctest module parsing mechanism
            finder = DocTestFinderPlus()
            runner = doctest.DebugRunner(verbose=False,
                                         optionflags=options,
                                         checker=OutputChecker())

            for test in finder.find(module):
                if test.examples:  # skip empty doctests
                    if config.getoption('remote_data', 'none') != 'any':

                        ignore_warnings_context_needed = False

                        for example in test.examples:

                            # If warnings are to be ignored we need to catch them by
                            # wrapping the source in a context manager.
                            if example.options.get(IGNORE_WARNINGS, False):
                                example.source = (
                                    "with _doctestplus_ignore_all_warnings():\n"
                                    + indent(example.source, '    '))
                                ignore_warnings_context_needed = True

                            if example.options.get(REMOTE_DATA):
                                example.options[doctest.SKIP] = True

                        # We insert the definition of the context manager to ignore
                        # warnings at the start of the file if needed.
                        if ignore_warnings_context_needed:
                            test.examples.insert(
                                0,
                                doctest.Example(source=IGNORE_WARNINGS_CONTEXT,
                                                want=''))

                    try:
                        yield doctest_plugin.DoctestItem.from_parent(
                            self, name=test.name, runner=runner, dtest=test)
                    except AttributeError:
                        # pytest < 5.4
                        yield doctest_plugin.DoctestItem(
                            test.name, self, runner, test)
Exemple #10
0
    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())

        encoding = self.config.getini("doctest_encoding")
        _fix_spoof_python2(runner, encoding)

        for test in finder.find(module, module.__name__):
            if test.examples:  # skip empty doctests
                yield DoctestItem(test.name, self, runner, test)
Exemple #11
0
def check_multi_rank_docstr(module):
    # supply customized flag ONLY_CHECK_RANK_{x} for docstr
    check_flags = [
        doctest.register_optionflag(f"ONLY_CHECK_RANK_{i}")
        for i in range(oneflow.env.get_world_size())
    ]
    finder = doctest.DocTestFinder()
    runner = doctest.DebugRunner(CondSkipChecker(check_flags))
    for test in finder.find(module, module.__name__):
        runner.run(test)
Exemple #12
0
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)
Exemple #13
0
        def runtest(self):
            if self.fspath.basename == 'conftest.py':
                module = self.config._conftest.importconftest(self.fspath)
            else:
                module = self.fspath.pyimport()

            finder = DocTestFinderPlus(exclude_empty=False)
            opts = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE
            runner = doctest.DebugRunner(verbose=False, optionflags=opts)

            for test in finder.find(module):
                runner.run(test)

            failed, tot = doctest.TestResults(runner.failures, runner.tries)
Exemple #14
0
        def collect(self):
            if self.fspath.basename == "conftest.py":
                module = self.config._conftest.importconftest(self.fspath)
            else:
                module = self.fspath.pyimport()

            # uses internal doctest module parsing mechanism
            finder = DocTestFinderPlus()
            opts = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE
            runner = doctest.DebugRunner(verbose=False, optionflags=opts)
            for test in finder.find(module):
                if test.examples:  # skip empty doctests
                    yield doctest_plugin.DoctestItem(test.name, self, runner,
                                                     test)
Exemple #15
0
def testmod_with_finder(
        m=None, name=None, globs=None, verbose=None, report=True, optionflags=0,
        extraglobs=None, raise_on_error=False, exclude_empty=False,
        finder=None):
    """
    Augment `testmod` with the ability to pass a custom `DocTestFinder`
    instance, that allows for selecting specific tests.

    Optional keyword arg "finder" specifies a finder instance to use, besides
    the default `DocTestFinder`.
    """
    # If no module was given, then use __main__.
    if m is None:
        # DWA - m will still be None if this wasn't invoked from the command
        # line, in which case the following TypeError is about as good an error
        # as we should expect
        m = sys.modules.get('__main__')

    # Check that we were actually given a module.
    import inspect
    if not inspect.ismodule(m):
        raise TypeError("testmod: module required; %r" % (m,))

    # If no name was given, then use the module's name.
    if name is None:
        name = m.__name__

    # Find, parse, and run all tests in the given module.
    if finder is None:
        finder = doctest.DocTestFinder(exclude_empty=exclude_empty)

    if raise_on_error:
        runner = doctest.DebugRunner(verbose=verbose, optionflags=optionflags)
    else:
        runner = doctest.DocTestRunner(verbose=verbose, optionflags=optionflags)

    for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
        runner.run(test)

    if report:
        runner.summarize()

    if doctest.master is None:
        doctest.master = runner
    else:
        doctest.master.merge(runner)

    return doctest.TestResults(runner.failures, runner.tries)
Exemple #16
0
def rundoctests(
    text,
    name='<text>',
    globs=None,
    verbose=None,
    report=True,
    optionflags=None,
    extraglobs=None,
    raise_on_error=False,
    quiet=False,
):
    # adapted from: http://www.mail-archive.com/[email protected]/msg404719.html
    # Assemble the globals.
    if optionflags is None:
        optionflags = doctest.NORMALIZE_WHITESPACE
    if globs is None:
        globs = globals()
    globs = globs.copy()
    if extraglobs is not None:
        globs.update(extraglobs)
    if '__name__' not in globs:
        globs['__name__'] = '__main__'
    # print(text)
    # Parse the text to find doc tests.
    parser = doctest.DocTestParser()
    test = parser.get_doctest(text, globs, name, name, 0)
    # Run the tests.
    if raise_on_error:
        runner = doctest.DebugRunner(verbose=verbose, optionflags=optionflags)
    else:
        runner = doctest.DocTestRunner(verbose=verbose,
                                       optionflags=optionflags)
    if quiet:
        runner.run(test, out=lambda s: None)
    else:
        runner.run(test)
    if report:
        runner.summarize()
    # Return a (named, if possible) tuple (failed, attempted).
    a, b = runner.failures, runner.tries
    try:
        TestResults = doctest.TestResults
    except AttributeError:
        return (a, b)
    return TestResults(a, b)
        def collect(self):
            if self.fspath.basename == "conftest.py":
                module = self.config._conftest.importconftest(self.fspath)
            else:
                module = self.fspath.pyimport()

            # uses internal doctest module parsing mechanism
            finder = DocTestFinderPlus()
            runner = doctest.DebugRunner(verbose=False, optionflags=opts)
            for test in finder.find(module):
                if test.examples:  # skip empty doctests
                    if not config.getvalue("remote_data"):
                        for example in test.examples:
                            if example.options.get(REMOTE_DATA):
                                example.options[doctest.SKIP] = True

                    yield doctest_plugin.DoctestItem(test.name, self, runner,
                                                     test)
Exemple #18
0
    def collect(self):
        import doctest

        # inspired by doctest.testfile; ideally we would use it directly,
        # but it doesn't support passing a custom checker
        text = self.fspath.read()
        filename = str(self.fspath)
        name = self.fspath.basename
        globs = {'__name__': '__main__'}

        optionflags = get_optionflags(self)
        runner = doctest.DebugRunner(verbose=0, optionflags=optionflags,
                                     checker=_get_checker())

        parser = doctest.DocTestParser()
        test = parser.get_doctest(text, globs, name, filename, 0)
        if test.examples:
            yield DoctestItem(test.name, self, runner, test)
Exemple #19
0
 def collect(self):
     import doctest
     if self.fspath.basename == "conftest.py":
         module = self.config._conftest.importconftest(self.fspath)
     else:
         module = self.fspath.pyimport()
     # satisfy `FixtureRequest` constructor...
     self.funcargs = {}
     self._fixtureinfo = FuncFixtureInfo((), [], {})
     fixture_request = FixtureRequest(self)
     doctest_globals = dict(getfixture=fixture_request.getfuncargvalue)
     # uses internal doctest module parsing mechanism
     finder = doctest.DocTestFinder()
     runner = doctest.DebugRunner(verbose=0, optionflags=doctest.ELLIPSIS)
     for test in finder.find(module,
                             module.__name__,
                             extraglobs=doctest_globals):
         if test.examples:  # skip empty doctests
             yield DoctestItem(test.name, self, runner, test)
Exemple #20
0
    def runtest(self):
        import doctest
        fixture_request = _setup_fixtures(self)

        # inspired by doctest.testfile; ideally we would use it directly,
        # but it doesn't support passing a custom checker
        text = self.fspath.read()
        filename = str(self.fspath)
        name = self.fspath.basename
        globs = dict(getfixture=fixture_request.getfuncargvalue)
        if '__name__' not in globs:
            globs['__name__'] = '__main__'

        optionflags = get_optionflags(self)
        runner = doctest.DebugRunner(verbose=0,
                                     optionflags=optionflags,
                                     checker=_get_unicode_checker())

        parser = doctest.DocTestParser()
        test = parser.get_doctest(text, globs, name, filename, 0)
        runner.run(test)
Exemple #21
0
def _run_functional_doctest(
    test_case,
    globs=None,
    verbose=None,
    optionflags=0,
    raise_on_error=True,
    module=flow,
):
    import doctest

    parser = doctest.DocTestParser()
    if raise_on_error:
        runner = doctest.DebugRunner(verbose=verbose, optionflags=optionflags)
    else:
        runner = doctest.DocTestRunner(verbose=verbose,
                                       optionflags=optionflags)
    r = inspect.getmembers(module)
    for (name, fun) in r:
        if fun.__doc__ is not None:
            test = parser.get_doctest(fun.__doc__, {}, __name__, __file__, 0)
            runner.run(test)
Exemple #22
0
def sympytestfile(filename,
                  module_relative=True,
                  name=None,
                  package=None,
                  globs=None,
                  verbose=None,
                  report=True,
                  optionflags=0,
                  extraglobs=None,
                  raise_on_error=False,
                  parser=pdoctest.DocTestParser(),
                  encoding=None):
    """
    Test examples in the given file.  Return (#failures, #tests).

    Optional keyword arg "module_relative" specifies how filenames
    should be interpreted:

      - If "module_relative" is True (the default), then "filename"
         specifies a module-relative path.  By default, this path is
         relative to the calling module's directory; but if the
         "package" argument is specified, then it is relative to that
         package.  To ensure os-independence, "filename" should use
         "/" characters to separate path segments, and should not
         be an absolute path (i.e., it may not begin with "/").

      - If "module_relative" is False, then "filename" specifies an
        os-specific path.  The path may be absolute or relative (to
        the current working directory).

    Optional keyword arg "name" gives the name of the test; by default
    use the file's basename.

    Optional keyword argument "package" is a Python package or the
    name of a Python package whose directory should be used as the
    base directory for a module relative filename.  If no package is
    specified, then the calling module's directory is used as the base
    directory for module relative filenames.  It is an error to
    specify "package" if "module_relative" is False.

    Optional keyword arg "globs" gives a dict to be used as the globals
    when executing examples; by default, use {}.  A copy of this dict
    is actually used for each docstring, so that each docstring's
    examples start with a clean slate.

    Optional keyword arg "extraglobs" gives a dictionary that should be
    merged into the globals that are used to execute examples.  By
    default, no extra globals are used.

    Optional keyword arg "verbose" prints lots of stuff if true, prints
    only failures if false; by default, it's true iff "-v" is in sys.argv.

    Optional keyword arg "report" prints a summary at the end when true,
    else prints nothing at the end.  In verbose mode, the summary is
    detailed, else very brief (in fact, empty if all tests passed).

    Optional keyword arg "optionflags" or's together module constants,
    and defaults to 0.  Possible values (see the docs for details):

        DONT_ACCEPT_TRUE_FOR_1
        DONT_ACCEPT_BLANKLINE
        NORMALIZE_WHITESPACE
        ELLIPSIS
        SKIP
        IGNORE_EXCEPTION_DETAIL
        REPORT_UDIFF
        REPORT_CDIFF
        REPORT_NDIFF
        REPORT_ONLY_FIRST_FAILURE

    Optional keyword arg "raise_on_error" raises an exception on the
    first unexpected exception or failure. This allows failures to be
    post-mortem debugged.

    Optional keyword arg "parser" specifies a DocTestParser (or
    subclass) that should be used to extract tests from the files.

    Optional keyword arg "encoding" specifies an encoding that should
    be used to convert the file to unicode.

    Advanced tomfoolery:  testmod runs methods of a local instance of
    class doctest.Tester, then merges the results into (or creates)
    global Tester instance doctest.master.  Methods of doctest.master
    can be called directly too, if you want to do something unusual.
    Passing report=0 to testmod is especially useful then, to delay
    displaying a summary.  Invoke doctest.master.summarize(verbose)
    when you're done fiddling.
    """
    if package and not module_relative:
        raise ValueError("Package may only be specified for module-"
                         "relative paths.")

    # Relativize the path
    text, filename = pdoctest._load_testfile(filename, package,
                                             module_relative)

    # If no name was given, then use the file's name.
    if name is None:
        name = os.path.basename(filename)

    # Assemble the globals.
    if globs is None:
        globs = {}
    else:
        globs = globs.copy()
    if extraglobs is not None:
        globs.update(extraglobs)
    if '__name__' not in globs:
        globs['__name__'] = '__main__'

    if raise_on_error:
        runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags)
    else:
        runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags)

    if encoding is not None:
        text = text.decode(encoding)

    # Read the file, convert it to a test, and run it.
    test = parser.get_doctest(text, globs, name, filename, 0)
    runner.run(test)

    if report:
        runner.summarize()

    if pdoctest.master is None:
        pdoctest.master = runner
    else:
        pdoctest.master.merge(runner)

    return SymPyTestResults(runner.failures, runner.tries)
Exemple #23
0
def testmod(m=None,
            name=None,
            globs=None,
            verbose=None,
            report=True,
            optionflags=0,
            extraglobs=None,
            raise_on_error=False,
            exclude_empty=False):
    """Test examples in the given module.  Return (#failures, #tests).
    
    Largely duplicated from :func:`doctest.testmod`, but using
    :class:`_SelectiveDocTestParser`.

    Test examples in docstrings in functions and classes reachable
    from module m (or the current module if m is not supplied), starting
    with m.__doc__.

    Also test examples reachable from dict m.__test__ if it exists and is
    not None.  m.__test__ maps names to functions, classes and strings;
    function and class docstrings are tested even if the name is private;
    strings are tested directly, as if they were docstrings.

    Return (#failures, #tests).

    See help(doctest) for an overview.

    Optional keyword arg "name" gives the name of the module; by default
    use m.__name__.

    Optional keyword arg "globs" gives a dict to be used as the globals
    when executing examples; by default, use m.__dict__.  A copy of this
    dict is actually used for each docstring, so that each docstring's
    examples start with a clean slate.

    Optional keyword arg "extraglobs" gives a dictionary that should be
    merged into the globals that are used to execute examples.  By
    default, no extra globals are used.  This is new in 2.4.

    Optional keyword arg "verbose" prints lots of stuff if true, prints
    only failures if false; by default, it's true iff "-v" is in sys.argv.

    Optional keyword arg "report" prints a summary at the end when true,
    else prints nothing at the end.  In verbose mode, the summary is
    detailed, else very brief (in fact, empty if all tests passed).

    Optional keyword arg "optionflags" or's together module constants,
    and defaults to 0.  This is new in 2.3.  Possible values (see the
    docs for details):

        DONT_ACCEPT_TRUE_FOR_1
        DONT_ACCEPT_BLANKLINE
        NORMALIZE_WHITESPACE
        ELLIPSIS
        SKIP
        IGNORE_EXCEPTION_DETAIL
        REPORT_UDIFF
        REPORT_CDIFF
        REPORT_NDIFF
        REPORT_ONLY_FIRST_FAILURE
        
    as well as FiPy's flags
    
        GMSH
        SCIPY
        TVTK
        SERIAL
        PARALLEL
        PROCESSOR_0
        PROCESSOR_0_OF_2
        PROCESSOR_1_OF_2
        PROCESSOR_0_OF_3
        PROCESSOR_1_OF_3
        PROCESSOR_2_OF_3

    Optional keyword arg "raise_on_error" raises an exception on the
    first unexpected exception or failure. This allows failures to be
    post-mortem debugged.
    """
    # If no module was given, then use __main__.
    if m is None:
        # DWA - m will still be None if this wasn't invoked from the command
        # line, in which case the following TypeError is about as good an error
        # as we should expect
        m = sys.modules.get('__main__')

    # Check that we were actually given a module.
    if not inspect.ismodule(m):
        raise TypeError("testmod: module required; %r" % (m, ))

    # If no name was given, then use the module's name.
    if name is None:
        name = m.__name__

    # Find, parse, and run all tests in the given module.
    finder = doctest.DocTestFinder(exclude_empty=exclude_empty,
                                   parser=_SelectiveDocTestParser())

    if raise_on_error:
        runner = doctest.DebugRunner(verbose=verbose, optionflags=optionflags)
    else:
        runner = doctest.DocTestRunner(verbose=verbose,
                                       optionflags=optionflags)

    for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
        runner.run(test)

    if report:
        runner.summarize()
        report_skips()

    return doctest.TestResults(runner.failures, runner.tries)
Exemple #24
0
        def collect(self):
            # When running directly from pytest we need to make sure that we
            # don't accidentally import setup.py!
            if PYTEST_GE_6_3:
                fspath = self.path
                filepath = self.path.name
            else:
                fspath = self.fspath
                filepath = self.fspath.basename

            if filepath == "setup.py":
                return
            elif filepath == "conftest.py":
                if PYTEST_GE_7_0:
                    module = self.config.pluginmanager._importconftest(
                        self.path,
                        self.config.getoption("importmode"),
                        rootpath=self.config.rootpath)
                elif PYTEST_GE_6_3:
                    module = self.config.pluginmanager._importconftest(
                        self.path, self.config.getoption("importmode"))
                elif PYTEST_GT_5:
                    module = self.config.pluginmanager._importconftest(
                        self.fspath, self.config.getoption("importmode"))
                else:
                    module = self.config.pluginmanager._importconftest(
                        self.fspath)
            else:
                try:
                    if PYTEST_GT_5:
                        from _pytest.pathlib import import_path

                    if PYTEST_GE_6_3:
                        module = import_path(fspath, root=self.config.rootpath)
                    elif PYTEST_GT_5:
                        module = import_path(fspath)
                    else:
                        module = fspath.pyimport()
                except ImportError:
                    if self.config.getvalue("doctest_ignore_import_errors"):
                        pytest.skip("unable to import module %r" % fspath)
                    else:
                        raise

            options = get_optionflags(self) | FIX

            # uses internal doctest module parsing mechanism
            finder = DocTestFinderPlus()
            runner = doctest.DebugRunner(verbose=False,
                                         optionflags=options,
                                         checker=OutputChecker())

            for test in finder.find(module):
                if test.examples:  # skip empty doctests
                    ignore_warnings_context_needed = False
                    show_warnings_context_needed = False

                    for example in test.examples:
                        if (config.getoption('remote_data', 'none') != 'any'
                                and example.options.get(REMOTE_DATA)):
                            example.options[doctest.SKIP] = True

                        # If warnings are to be ignored we need to catch them by
                        # wrapping the source in a context manager.
                        elif example.options.get(IGNORE_WARNINGS, False):
                            example.source = (
                                "with _doctestplus_ignore_all_warnings():\n" +
                                indent(example.source, '    '))
                            ignore_warnings_context_needed = True

                        # Same for SHOW_WARNINGS
                        elif example.options.get(SHOW_WARNINGS, False):
                            example.source = (
                                "with _doctestplus_show_all_warnings():\n" +
                                indent(example.source, '    '))
                            show_warnings_context_needed = True

                    # We insert the definition of the context manager to ignore
                    # warnings at the start of the file if needed.
                    if ignore_warnings_context_needed:
                        test.examples.insert(
                            0,
                            doctest.Example(source=IGNORE_WARNINGS_CONTEXT,
                                            want=''))

                    if show_warnings_context_needed:
                        test.examples.insert(
                            0,
                            doctest.Example(source=SHOW_WARNINGS_CONTEXT,
                                            want=''))

                    try:
                        yield doctest_plugin.DoctestItem.from_parent(
                            self, name=test.name, runner=runner, dtest=test)
                    except AttributeError:
                        # pytest < 5.4
                        yield doctest_plugin.DoctestItem(
                            test.name, self, runner, test)
Exemple #25
0
    >>> kak.evaluate('test b')
    >>> print(test(kak, 'c'))
    3
    >>> kak.execute("%")
    >>> print(kak.val.selection())
    <BLANKLINE>
    Test! a 1
    Test! b 2
    Test! c 3
    <BLANKLINE>
    >>> kak.quit()
    """


if __name__ == '__main__':
    import doctest
    import sys
    doctest.testmod(extraglobs={'libkak': sys.modules[__name__]})
    sys.exit()
    dt_runner = doctest.DebugRunner()
    tests = doctest.DocTestFinder().find(sys.modules[__name__])
    for t in tests:
        t.globs['libkak']=sys.modules[__name__]
        #dt_runner.run(t)
        try:
            dt_runner.run(t)
        except doctest.UnexpectedException as e:
            import pdb
            pdb.post_mortem(e.exc_info[2])