Ejemplo n.º 1
0
class _NonManglingOutputChecker(doctest.OutputChecker):
    """Doctest checker that works with unicode rather than mangling strings

    This is needed because current Python versions have tried to fix string
    encoding related problems, but regressed the default behaviour with
    unicode inputs in the process.

    In Python 2.6 and 2.7 ``OutputChecker.output_difference`` is was changed
    to return a bytestring encoded as per ``sys.stdout.encoding``, or utf-8 if
    that can't be determined. Worse, that encoding process happens in the
    innocent looking `_indent` global function. Because the
    `DocTestMismatch.describe` result may well not be destined for printing to
    stdout, this is no good for us. To get a unicode return as before, the
    method is monkey patched if ``doctest._encoding`` exists.

    Python 3 has a different problem. For some reason both inputs are encoded
    to ascii with 'backslashreplace', making an escaped string matches its
    unescaped form. Overriding the offending ``OutputChecker._toAscii`` method
    is sufficient to revert this.
    """
    def _toAscii(self, s):
        """Return ``s`` unchanged rather than mangling it to ascii"""
        return s

    # Only do this overriding hackery if doctest has a broken _input function
    if getattr(doctest, "_encoding", None) is not None:
        from types import FunctionType as __F
        __f = doctest.OutputChecker.output_difference.im_func
        __g = dict(__f.func_globals)

        def _indent(s, indent=4, _pattern=re.compile("^(?!$)", re.MULTILINE)):
            """Prepend non-empty lines in ``s`` with ``indent`` number of spaces"""
            return _pattern.sub(indent * " ", s)

        __g["_indent"] = _indent
        output_difference = __F(__f.func_code, __g, "output_difference")
        del __F, __f, __g, _indent
Ejemplo n.º 2
0
class TestResult(unittest.TestResult):
    """Subclass of unittest.TestResult extending the protocol for flexability.

    This test result supports an experimental protocol for providing additional
    data to in test outcomes. All the outcome methods take an optional dict
    'details'. If supplied any other detail parameters like 'err' or 'reason'
    should not be provided. The details dict is a mapping from names to
    MIME content objects (see testtools.content). This permits attaching
    tracebacks, log files, or even large objects like databases that were
    part of the test fixture. Until this API is accepted into upstream
    Python it is considered experimental: it may be replaced at any point
    by a newer version more in line with upstream Python. Compatibility would
    be aimed for in this case, but may not be possible.

    :ivar skip_reasons: A dict of skip-reasons -> list of tests. See addSkip.
    """
    def __init__(self):
        # startTestRun resets all attributes, and older clients don't know to
        # call startTestRun, so it is called once here.
        # Because subclasses may reasonably not expect this, we call the
        # specific version we want to run.
        TestResult.startTestRun(self)

    def addExpectedFailure(self, test, err=None, details=None):
        """Called when a test has failed in an expected manner.

        Like with addSuccess and addError, testStopped should still be called.

        :param test: The test that has been skipped.
        :param err: The exc_info of the error that was raised.
        :return: None
        """
        # This is the python 2.7 implementation
        self.expectedFailures.append(
            (test, self._err_details_to_string(test, err, details)))

    def addError(self, test, err=None, details=None):
        """Called when an error has occurred. 'err' is a tuple of values as
        returned by sys.exc_info().

        :param details: Alternative way to supply details about the outcome.
            see the class docstring for more information.
        """
        self.errors.append(
            (test, self._err_details_to_string(test, err, details)))

    def addFailure(self, test, err=None, details=None):
        """Called when an error has occurred. 'err' is a tuple of values as
        returned by sys.exc_info().

        :param details: Alternative way to supply details about the outcome.
            see the class docstring for more information.
        """
        self.failures.append(
            (test, self._err_details_to_string(test, err, details)))

    def addSkip(self, test, reason=None, details=None):
        """Called when a test has been skipped rather than running.

        Like with addSuccess and addError, testStopped should still be called.

        This must be called by the TestCase. 'addError' and 'addFailure' will
        not call addSkip, since they have no assumptions about the kind of
        errors that a test can raise.

        :param test: The test that has been skipped.
        :param reason: The reason for the test being skipped. For instance,
            u"pyGL is not available".
        :param details: Alternative way to supply details about the outcome.
            see the class docstring for more information.
        :return: None
        """
        if reason is None:
            reason = details.get('reason')
            if reason is None:
                reason = 'No reason given'
            else:
                reason = ''.join(reason.iter_text())
        skip_list = self.skip_reasons.setdefault(reason, [])
        skip_list.append(test)

    def addSuccess(self, test, details=None):
        """Called when a test succeeded."""

    def addUnexpectedSuccess(self, test, details=None):
        """Called when a test was expected to fail, but succeed."""
        self.unexpectedSuccesses.append(test)

    def wasSuccessful(self):
        """Has this result been successful so far?

        If there have been any errors, failures or unexpected successes,
        return False.  Otherwise, return True.

        Note: This differs from standard unittest in that we consider
        unexpected successes to be equivalent to failures, rather than
        successes.
        """
        return not (self.errors or self.failures or self.unexpectedSuccesses)

    if str_is_unicode:
        # Python 3 and IronPython strings are unicode, use parent class method
        _exc_info_to_unicode = unittest.TestResult._exc_info_to_string
    else:
        # For Python 2, need to decode components of traceback according to
        # their source, so can't use traceback.format_exception
        # Here follows a little deep magic to copy the existing method and
        # replace the formatter with one that returns unicode instead
        from types import FunctionType as __F, ModuleType as __M
        __f = unittest.TestResult._exc_info_to_string.im_func
        __g = dict(__f.func_globals)
        __m = __M("__fake_traceback")
        __m.format_exception = _format_exc_info
        __g["traceback"] = __m
        _exc_info_to_unicode = __F(__f.func_code, __g, "_exc_info_to_unicode")
        del __F, __M, __f, __g, __m

    def _err_details_to_string(self, test, err=None, details=None):
        """Convert an error in exc_info form or a contents dict to a string."""
        if err is not None:
            return self._exc_info_to_unicode(err, test)
        return _details_to_str(details)

    def _now(self):
        """Return the current 'test time'.

        If the time() method has not been called, this is equivalent to
        datetime.now(), otherwise its the last supplied datestamp given to the
        time() method.
        """
        if self.__now is None:
            return datetime.datetime.now(utc)
        else:
            return self.__now

    def startTestRun(self):
        """Called before a test run starts.

        New in Python 2.7. The testtools version resets the result to a
        pristine condition ready for use in another test run.  Note that this
        is different from Python 2.7's startTestRun, which does nothing.
        """
        super(TestResult, self).__init__()
        self.skip_reasons = {}
        self.__now = None
        # -- Start: As per python 2.7 --
        self.expectedFailures = []
        self.unexpectedSuccesses = []
        # -- End:   As per python 2.7 --

    def stopTestRun(self):
        """Called after a test run completes

        New in python 2.7
        """

    def time(self, a_datetime):
        """Provide a timestamp to represent the current time.

        This is useful when test activity is time delayed, or happening
        concurrently and getting the system time between API calls will not
        accurately represent the duration of tests (or the whole run).

        Calling time() sets the datetime used by the TestResult object.
        Time is permitted to go backwards when using this call.

        :param a_datetime: A datetime.datetime object with TZ information or
            None to reset the TestResult to gathering time from the system.
        """
        self.__now = a_datetime

    def done(self):
        """Called when the test runner is done.