Esempio n. 1
0
def _format_final_exc_line(etype, value):
    valuestr = _some_str(value)
    if value == 'None' or value is None or not valuestr:
        line = u("%s\n") % etype
    else:
        line = u("%s: %s\n") % (etype, valuestr)
    return line
Esempio n. 2
0
def _format_final_exc_line(etype, value):
    valuestr = _some_str(value)
    if value == 'None' or value is None or not valuestr:
        line = u("%s\n") % etype
    else:
        line = u("%s: %s\n") % (etype, valuestr)
    return line
Esempio n. 3
0
    def format_exception_only(self):
        """Format the exception part of the traceback.

        The return value is a generator of strings, each ending in a newline.

        Normally, the generator emits a single string; however, for
        SyntaxError exceptions, it emites several lines that (when
        printed) display detailed information about where the syntax
        error occurred.

        The message indicating which exception occurred is always the last
        string in the output.
        """
        if self.exc_type is None:
            yield _format_final_exc_line(None, self._str)
            return

        stype = getattr(self.exc_type, '__qualname__', self.exc_type.__name__)
        smod = u(self.exc_type.__module__)
        if smod not in ("__main__", "builtins", "exceptions"):
            stype = smod + u('.') + stype

        if not issubclass(self.exc_type, SyntaxError):
            yield _format_final_exc_line(stype, self._str)
            return

        # It was a syntax error; show exactly where the problem was found.
        filename = _some_fs_str(self.filename) or u("<string>")
        lineno = str(self.lineno) or u('?')
        yield u('  File "{0}", line {1}\n').format(filename, lineno)

        badline = None
        if self.text is not None:
            if type(self.text) is bytes:
                # Not decoded - get the line via linecache which will decode
                # for us.
                if self.lineno:
                    badline = linecache.getline(filename, int(lineno))
                if not badline:
                    # But we can't for some reason, so fallback to attempting a
                    # u cast.
                    badline = u(self.text)
            else:
                badline = self.text
        offset = self.offset
        if badline is not None:
            yield u('    {0}\n').format(badline.strip())
            if offset is not None:
                caretspace = badline.rstrip('\n')
                offset = min(len(caretspace), offset) - 1
                caretspace = caretspace[:offset].lstrip()
                # non-space whitespace (likes tabs) must be kept for alignment
                caretspace = ((c.isspace() and c or ' ') for c in caretspace)
                yield u('    {0}^\n').format(''.join(caretspace))
        msg = self.msg or u("<no detail available>")
        yield u("{0}: {1}\n").format(stype, msg)
Esempio n. 4
0
    def format_exception_only(self):
        """Format the exception part of the traceback.

        The return value is a generator of strings, each ending in a newline.

        Normally, the generator emits a single string; however, for
        SyntaxError exceptions, it emites several lines that (when
        printed) display detailed information about where the syntax
        error occurred.

        The message indicating which exception occurred is always the last
        string in the output.
        """
        if self.exc_type is None:
            yield _format_final_exc_line(None, self._str)
            return

        stype = getattr(self.exc_type, '__qualname__', self.exc_type.__name__)
        smod = u(self.exc_type.__module__)
        if smod not in ("__main__", "builtins", "exceptions"):
            stype = smod + u('.') + stype

        if not issubclass(self.exc_type, SyntaxError):
            yield _format_final_exc_line(stype, self._str)
            return

        # It was a syntax error; show exactly where the problem was found.
        filename = _some_fs_str(self.filename) or u("<string>")
        lineno = str(self.lineno) or u('?')
        yield u('  File "{0}", line {1}\n').format(filename, lineno)

        badline = None
        if self.text is not None:
            if type(self.text) is bytes:
                # Not decoded - get the line via linecache which will decode
                # for us.
                if self.lineno:
                    badline = linecache.getline(filename, int(lineno))
                if not badline:
                    # But we can't for some reason, so fallback to attempting a
                    # u cast.
                    badline = u(self.text)
            else:
                badline = self.text
        offset = self.offset
        if badline is not None:
            yield u('    {0}\n').format(badline.strip())
            if offset is not None:
                caretspace = badline.rstrip('\n')
                offset = min(len(caretspace), offset) - 1
                caretspace = caretspace[:offset].lstrip()
                # non-space whitespace (likes tabs) must be kept for alignment
                caretspace = ((c.isspace() and c or ' ') for c in caretspace)
                yield u('    {0}^\n').format(''.join(caretspace))
        msg = self.msg or u("<no detail available>")
        yield u("{0}: {1}\n").format(stype, msg)
Esempio n. 5
0
    def format(self, chain=True):
        """Format the exception.

        If chain is not *True*, *__cause__* and *__context__* will not be formatted.

        The return value is a generator of strings, each ending in a newline and
        some containing internal newlines. `print_exception` is a wrapper around
        this method which just prints the lines to a file.

        The message indicating which exception occurred is always the last
        string in the output.
        """
        if chain:
            if self.__cause__ is not None:
                for line in self.__cause__.format(chain=chain):
                    yield line
                yield _cause_message
            elif (self.__context__ is not None
                  and not self.__suppress_context__):
                for line in self.__context__.format(chain=chain):
                    yield line
                yield _context_message
        yield u('Traceback (most recent call last):\n')
        for line in self.stack.format():
            yield line
        for line in self.format_exception_only():
            yield line
Esempio n. 6
0
    def format(self, chain=True):
        """Format the exception.

        If chain is not *True*, *__cause__* and *__context__* will not be formatted.

        The return value is a generator of strings, each ending in a newline and
        some containing internal newlines. `print_exception` is a wrapper around
        this method which just prints the lines to a file.

        The message indicating which exception occurred is always the last
        string in the output.
        """
        if chain:
            if self.__cause__ is not None:
                for line in self.__cause__.format(chain=chain):
                    yield line
                yield _cause_message
            elif (self.__context__ is not None and
                not self.__suppress_context__):
                for line in self.__context__.format(chain=chain):
                    yield line
                yield _context_message
        yield u('Traceback (most recent call last):\n')
        for line in self.stack.format():
            yield line
        for line in self.format_exception_only():
            yield line
Esempio n. 7
0
    def format(self):
        """Format the stack ready for printing.

        Returns a list of strings ready for printing.  Each string in the
        resulting list corresponds to a single frame from the stack.
        Each string ends in a newline; the strings may contain internal
        newlines as well, for those items with source text lines.
        """
        result = []
        for frame in self:
            row = []
            row.append(u('  File "{0}", line {1}, in {2}\n').format(
                _some_fs_str(frame.filename), frame.lineno, frame.name))
            if frame.line:
                row.append(u('    {0}\n').format(frame.line.strip()))
            if frame.locals:
                for name, value in sorted(frame.locals.items()):
                    row.append(u('    {name} = {value}\n').format(name=name, value=value))
            result.append(u('').join(row))
        return result
Esempio n. 8
0
    def format(self):
        """Format the stack ready for printing.

        Returns a list of strings ready for printing.  Each string in the
        resulting list corresponds to a single frame from the stack.
        Each string ends in a newline; the strings may contain internal
        newlines as well, for those items with source text lines.
        """
        result = []
        for frame in self:
            row = []
            row.append(
                u('  File "{0}", line {1}, in {2}\n').format(
                    _some_fs_str(frame.filename), frame.lineno, frame.name))
            if frame.line:
                row.append(u('    {0}\n').format(frame.line.strip()))
            if frame.locals:
                for name, value in sorted(frame.locals.items()):
                    row.append(
                        u('    {name} = {value}\n').format(name=name,
                                                           value=value))
            result.append(u('').join(row))
        return result
Esempio n. 9
0
class TextTestResult(result.TestResult):
    """A test result class that can print formatted text results to a stream.

    Used by TextTestRunner.
    """
    separator1 = u('=' * 70)
    separator2 = u('-' * 70)

    def __init__(self, stream, descriptions, verbosity):
        super(TextTestResult, self).__init__(stream, descriptions, verbosity)
        self.stream = stream
        self.showAll = verbosity > 1
        self.dots = verbosity == 1
        self.descriptions = descriptions

    def getDescription(self, test):
        doc_first_line = test.shortDescription()
        if self.descriptions and doc_first_line:
            return '\n'.join((str(test), doc_first_line))
        else:
            return str(test)

    def startTest(self, test):
        super(TextTestResult, self).startTest(test)
        if self.showAll:
            self.stream.write(self.getDescription(test))
            self.stream.write(" ... ")
            self.stream.flush()

    def addSuccess(self, test):
        super(TextTestResult, self).addSuccess(test)
        if self.showAll:
            self.stream.writeln("ok")
        elif self.dots:
            self.stream.write('.')
            self.stream.flush()

    def addError(self, test, err):
        super(TextTestResult, self).addError(test, err)
        if self.showAll:
            self.stream.writeln("ERROR")
        elif self.dots:
            self.stream.write('E')
            self.stream.flush()

    def addFailure(self, test, err):
        super(TextTestResult, self).addFailure(test, err)
        if self.showAll:
            self.stream.writeln("FAIL")
        elif self.dots:
            self.stream.write('F')
            self.stream.flush()

    def addSkip(self, test, reason):
        super(TextTestResult, self).addSkip(test, reason)
        if self.showAll:
            self.stream.writeln("skipped %r" % (reason,))
        elif self.dots:
            self.stream.write("s")
            self.stream.flush()

    def addExpectedFailure(self, test, err):
        super(TextTestResult, self).addExpectedFailure(test, err)
        if self.showAll:
            self.stream.writeln("expected failure")
        elif self.dots:
            self.stream.write("x")
            self.stream.flush()

    def addUnexpectedSuccess(self, test):
        super(TextTestResult, self).addUnexpectedSuccess(test)
        if self.showAll:
            self.stream.writeln("unexpected success")
        elif self.dots:
            self.stream.write("u")
            self.stream.flush()

    def printErrors(self):
        if self.dots or self.showAll:
            self.stream.writeln()
        self.printErrorList('ERROR', self.errors)
        self.printErrorList('FAIL', self.failures)

    def printErrorList(self, flavour, errors):
        for test, err in errors:
            self.stream.writeln(self.separator1)
            self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
            self.stream.writeln(self.separator2)
            self.stream.writeln("%s" % err)

    def stopTestRun(self):
        super(TextTestResult, self).stopTestRun()
        self.printErrors()
Esempio n. 10
0
 def writeln(self, arg=None):
     if arg:
         self.write(arg)
     self.write(u('\n')) # text-mode streams translate to \r\n if needed
Esempio n. 11
0
    def run(self, test):
        "Run the given test case or test suite."
        result = self._makeResult()
        result.failfast = self.failfast
        result.buffer = self.buffer
        result.tb_locals = self.tb_locals
        registerResult(result)

        startTime = time.time()
        startTestRun = getattr(result, 'startTestRun', None)
        if startTestRun is not None:
            startTestRun()
        try:
            test(result)
        finally:
            stopTestRun = getattr(result, 'stopTestRun', None)
            if stopTestRun is not None:
                stopTestRun()
            else:
                result.printErrors()
        stopTime = time.time()
        timeTaken = stopTime - startTime
        if hasattr(result, 'separator2'):
            self.stream.writeln(result.separator2)
        run = result.testsRun
        self.stream.writeln(u("Ran %d test%s in %.3fs") %
                            (run, run != 1 and "s" or "", timeTaken))
        self.stream.writeln()

        expectedFails = unexpectedSuccesses = skipped = 0
        try:
            results = map(len, (result.expectedFailures,
                                result.unexpectedSuccesses,
                                result.skipped))
        except AttributeError:
            pass
        else:
            expectedFails, unexpectedSuccesses, skipped = results
        infos = []
        if not result.wasSuccessful():
            self.stream.write(u("FAILED"))
            failed, errored = map(len, (result.failures, result.errors))
            if failed:
                infos.append(u("failures=%d") % failed)
            if errored:
                infos.append(u("errors=%d") % errored)
        else:
            self.stream.write(u("OK"))
        if skipped:
            infos.append(u("skipped=%d") % skipped)
        if expectedFails:
            infos.append(u("expected failures=%d") % expectedFails)
        if unexpectedSuccesses:
            infos.append(u("unexpected successes=%d") % unexpectedSuccesses)
        if infos:
            self.stream.writeln(u(" (%s)") % (u(", ").join(infos),))
        else:
            self.stream.write(u("\n"))
        return result