Python doctest.DocTestFailure() Examples

The following are 10 code examples of doctest.DocTestFailure(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module doctest , or try the search function .
Example #1
Source File: test_doctests.py    From zipline-chinese with Apache License 2.0 6 votes vote down vote up
def _check_docs(self, module):
        if self._skip:
            # Printing this directly to __stdout__ so that it doesn't get
            # captured by nose.
            print("Warning: Skipping doctests for %s because "
                  "pdbpp is installed." % module.__name__, file=sys.__stdout__)
            return
        try:
            doctest.testmod(
                module,
                verbose=True,
                raise_on_error=True,
                optionflags=self.flags,
            )
        except doctest.UnexpectedException as e:
            raise e.exc_info[1]
        except doctest.DocTestFailure as e:
            print("Got:")
            print(e.got)
            raise 
Example #2
Source File: doctest.py    From python-netsurv with MIT License 5 votes vote down vote up
def _init_runner_class():
    import doctest

    class PytestDoctestRunner(doctest.DebugRunner):
        """
        Runner to collect failures.  Note that the out variable in this case is
        a list instead of a stdout-like object
        """

        def __init__(
            self, checker=None, verbose=None, optionflags=0, continue_on_failure=True
        ):
            doctest.DebugRunner.__init__(
                self, checker=checker, verbose=verbose, optionflags=optionflags
            )
            self.continue_on_failure = continue_on_failure

        def report_failure(self, out, test, example, got):
            failure = doctest.DocTestFailure(test, example, got)
            if self.continue_on_failure:
                out.append(failure)
            else:
                raise failure

        def report_unexpected_exception(self, out, test, example, exc_info):
            if isinstance(exc_info[1], Skipped):
                raise exc_info[1]
            failure = doctest.UnexpectedException(test, example, exc_info)
            if self.continue_on_failure:
                out.append(failure)
            else:
                raise failure

    return PytestDoctestRunner 
Example #3
Source File: doctest.py    From python-netsurv with MIT License 5 votes vote down vote up
def _init_runner_class():
    import doctest

    class PytestDoctestRunner(doctest.DebugRunner):
        """
        Runner to collect failures.  Note that the out variable in this case is
        a list instead of a stdout-like object
        """

        def __init__(
            self, checker=None, verbose=None, optionflags=0, continue_on_failure=True
        ):
            doctest.DebugRunner.__init__(
                self, checker=checker, verbose=verbose, optionflags=optionflags
            )
            self.continue_on_failure = continue_on_failure

        def report_failure(self, out, test, example, got):
            failure = doctest.DocTestFailure(test, example, got)
            if self.continue_on_failure:
                out.append(failure)
            else:
                raise failure

        def report_unexpected_exception(self, out, test, example, exc_info):
            if isinstance(exc_info[1], Skipped):
                raise exc_info[1]
            failure = doctest.UnexpectedException(test, example, exc_info)
            if self.continue_on_failure:
                out.append(failure)
            else:
                raise failure

    return PytestDoctestRunner 
Example #4
Source File: doctest.py    From pytest with MIT License 5 votes vote down vote up
def __init__(self, failures: "Sequence[doctest.DocTestFailure]") -> None:
        super().__init__()
        self.failures = failures 
Example #5
Source File: doctest.py    From pytest with MIT License 5 votes vote down vote up
def runtest(self) -> None:
        assert self.dtest is not None
        assert self.runner is not None
        _check_all_skipped(self.dtest)
        self._disable_output_capturing_for_darwin()
        failures = []  # type: List[doctest.DocTestFailure]
        # Type ignored because we change the type of `out` from what
        # doctest expects.
        self.runner.run(self.dtest, out=failures)  # type: ignore[arg-type] # noqa: F821
        if failures:
            raise MultipleDoctestFailures(failures) 
Example #6
Source File: test_fileutils.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_docstrings(self, urlopen):
        pretend_html = b"<!DOCTYPE HTML ...blah blah blah"
        responses.add("GET", "http://www.salesforce.com/", body=pretend_html)
        fake_http_stream = BytesIO(pretend_html)
        fake_http_stream.url = "https://www.salesforce.com/"
        urlopen.return_value = fake_http_stream
        try:
            doctest.testmod(fileutils, raise_on_error=True, verbose=True)
        except doctest.DocTestFailure as e:
            print("Got")
            print(str(e.got))
            raise 
Example #7
Source File: test_doc.py    From portion with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readme():
    failure = None

    try:
        doctest.testfile('../README.md', raise_on_error=True, globs={'P': P})
    except doctest.DocTestFailure as e:
        failure = e.example.want, e.got, e.example.source

    if failure:
        # Make pytest display it outside the "except" block, to avoid a noisy traceback
        want, got, example = failure
        assert want.strip() == got.strip(), 'DocTest failure in "{}"'.format(example.strip())
        assert False  # In case .strip() removed something useful 
Example #8
Source File: doctest.py    From python-netsurv with MIT License 4 votes vote down vote up
def repr_failure(self, excinfo):
        import doctest

        failures = None
        if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):
            failures = [excinfo.value]
        elif excinfo.errisinstance(MultipleDoctestFailures):
            failures = excinfo.value.failures

        if failures is not None:
            reprlocation_lines = []
            for failure in failures:
                example = failure.example
                test = failure.test
                filename = test.filename
                if test.lineno is None:
                    lineno = None
                else:
                    lineno = test.lineno + example.lineno + 1
                message = type(failure).__name__
                reprlocation = ReprFileLocation(filename, lineno, message)
                checker = _get_checker()
                report_choice = _get_report_choice(
                    self.config.getoption("doctestreport")
                )
                if lineno is not None:
                    lines = failure.test.docstring.splitlines(False)
                    # add line numbers to the left of the error message
                    lines = [
                        "%03d %s" % (i + test.lineno + 1, x)
                        for (i, x) in enumerate(lines)
                    ]
                    # trim docstring error lines to 10
                    lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
                else:
                    lines = [
                        "EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
                    ]
                    indent = ">>>"
                    for line in example.source.splitlines():
                        lines.append("??? {} {}".format(indent, line))
                        indent = "..."
                if isinstance(failure, doctest.DocTestFailure):
                    lines += checker.output_difference(
                        example, failure.got, report_choice
                    ).split("\n")
                else:
                    inner_excinfo = ExceptionInfo(failure.exc_info)
                    lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
                    lines += traceback.format_exception(*failure.exc_info)
                reprlocation_lines.append((reprlocation, lines))
            return ReprFailDoctest(reprlocation_lines)
        else:
            return super().repr_failure(excinfo) 
Example #9
Source File: doctest.py    From python-netsurv with MIT License 4 votes vote down vote up
def repr_failure(self, excinfo):
        import doctest

        failures = None
        if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):
            failures = [excinfo.value]
        elif excinfo.errisinstance(MultipleDoctestFailures):
            failures = excinfo.value.failures

        if failures is not None:
            reprlocation_lines = []
            for failure in failures:
                example = failure.example
                test = failure.test
                filename = test.filename
                if test.lineno is None:
                    lineno = None
                else:
                    lineno = test.lineno + example.lineno + 1
                message = type(failure).__name__
                reprlocation = ReprFileLocation(filename, lineno, message)
                checker = _get_checker()
                report_choice = _get_report_choice(
                    self.config.getoption("doctestreport")
                )
                if lineno is not None:
                    lines = failure.test.docstring.splitlines(False)
                    # add line numbers to the left of the error message
                    lines = [
                        "%03d %s" % (i + test.lineno + 1, x)
                        for (i, x) in enumerate(lines)
                    ]
                    # trim docstring error lines to 10
                    lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
                else:
                    lines = [
                        "EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
                    ]
                    indent = ">>>"
                    for line in example.source.splitlines():
                        lines.append("??? {} {}".format(indent, line))
                        indent = "..."
                if isinstance(failure, doctest.DocTestFailure):
                    lines += checker.output_difference(
                        example, failure.got, report_choice
                    ).split("\n")
                else:
                    inner_excinfo = ExceptionInfo(failure.exc_info)
                    lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
                    lines += traceback.format_exception(*failure.exc_info)
                reprlocation_lines.append((reprlocation, lines))
            return ReprFailDoctest(reprlocation_lines)
        else:
            return super().repr_failure(excinfo) 
Example #10
Source File: doctest.py    From pytest with MIT License 4 votes vote down vote up
def _init_runner_class() -> "Type[doctest.DocTestRunner]":
    import doctest

    class PytestDoctestRunner(doctest.DebugRunner):
        """
        Runner to collect failures.  Note that the out variable in this case is
        a list instead of a stdout-like object
        """

        def __init__(
            self,
            checker: Optional[doctest.OutputChecker] = None,
            verbose: Optional[bool] = None,
            optionflags: int = 0,
            continue_on_failure: bool = True,
        ) -> None:
            doctest.DebugRunner.__init__(
                self, checker=checker, verbose=verbose, optionflags=optionflags
            )
            self.continue_on_failure = continue_on_failure

        def report_failure(
            self, out, test: "doctest.DocTest", example: "doctest.Example", got: str,
        ) -> None:
            failure = doctest.DocTestFailure(test, example, got)
            if self.continue_on_failure:
                out.append(failure)
            else:
                raise failure

        def report_unexpected_exception(
            self,
            out,
            test: "doctest.DocTest",
            example: "doctest.Example",
            exc_info: "Tuple[Type[BaseException], BaseException, types.TracebackType]",
        ) -> None:
            if isinstance(exc_info[1], OutcomeException):
                raise exc_info[1]
            if isinstance(exc_info[1], bdb.BdbQuit):
                outcomes.exit("Quitting debugger")
            failure = doctest.UnexpectedException(test, example, exc_info)
            if self.continue_on_failure:
                out.append(failure)
            else:
                raise failure

    return PytestDoctestRunner