示例#1
0
 def test_add_tag_twice(self):
     # Calling change_tags twice to add tags adds both tags to the current
     # tags.
     tag_context = TagContext()
     tag_context.change_tags(set(['foo']), set())
     tag_context.change_tags(set(['bar']), set())
     self.assertEqual(set(['foo', 'bar']), tag_context.get_current_tags())
示例#2
0
 def test_add_to_child(self):
     # Adding a tag to the child context doesn't affect the parent.
     parent = TagContext()
     parent.change_tags({'foo'}, set())
     child = TagContext(parent)
     child.change_tags({'bar'}, set())
     self.assertEqual({'foo', 'bar'}, child.get_current_tags())
     self.assertEqual({'foo'}, parent.get_current_tags())
示例#3
0
 def test_add_tag_twice(self):
     # Calling change_tags twice to add tags adds both tags to the current
     # tags.
     tag_context = TagContext()
     tag_context.change_tags(set(['foo']), set())
     tag_context.change_tags(set(['bar']), set())
     self.assertEqual(
         set(['foo', 'bar']), tag_context.get_current_tags())
示例#4
0
 def test_remove_in_child(self):
     # A tag that was in the parent context can be removed from the child
     # context without affect the parent.
     parent = TagContext()
     parent.change_tags({'foo'}, set())
     child = TagContext(parent)
     child.change_tags(set(), {'foo'})
     self.assertEqual(set(), child.get_current_tags())
     self.assertEqual({'foo'}, parent.get_current_tags())
示例#5
0
 def test_child_context(self):
     # A TagContext can have a parent.  If so, its tags are the tags of the
     # parent at the moment of construction.
     parent = TagContext()
     parent.change_tags(set(['foo']), set())
     child = TagContext(parent)
     self.assertEqual(parent.get_current_tags(), child.get_current_tags())
示例#6
0
 def test_parent(self):
     # The parent can be retrieved from a child context.
     parent = TagContext()
     parent.change_tags({'foo'}, set())
     child = TagContext(parent)
     child.change_tags(set(), {'foo'})
     self.assertEqual(parent, child.parent)
示例#7
0
 def test_add_to_child(self):
     # Adding a tag to the child context doesn't affect the parent.
     parent = TagContext()
     parent.change_tags(set(['foo']), set())
     child = TagContext(parent)
     child.change_tags(set(['bar']), set())
     self.assertEqual(set(['foo', 'bar']), child.get_current_tags())
     self.assertEqual(set(['foo']), parent.get_current_tags())
示例#8
0
 def test_remove_in_child(self):
     # A tag that was in the parent context can be removed from the child
     # context without affect the parent.
     parent = TagContext()
     parent.change_tags(set(['foo']), set())
     child = TagContext(parent)
     child.change_tags(set(), set(['foo']))
     self.assertEqual(set(), child.get_current_tags())
     self.assertEqual(set(['foo']), parent.get_current_tags())
示例#9
0
文件: real.py 项目: LukeM12/samba
    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.
        """
        # failfast is reset by the super __init__, so stash it.
        failfast = self.failfast
        super(TestResult, self).__init__()
        self.skip_reasons = {}
        self.__now = None
        self._tags = TagContext()
        # -- Start: As per python 2.7 --
        self.expectedFailures = []
        self.unexpectedSuccesses = []
        self.failfast = failfast
示例#10
0
 def test_parent(self):
     # The parent can be retrieved from a child context.
     parent = TagContext()
     parent.change_tags(set(['foo']), set())
     child = TagContext(parent)
     child.change_tags(set(), set(['foo']))
     self.assertEqual(parent, child.parent)
示例#11
0
 def test_child_context(self):
     # A TagContext can have a parent.  If so, its tags are the tags of the
     # parent at the moment of construction.
     parent = TagContext()
     parent.change_tags(set(['foo']), set())
     child = TagContext(parent)
     self.assertEqual(
         parent.get_current_tags(), child.get_current_tags())
示例#12
0
文件: real.py 项目: AIdrifter/samba
    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.
        """
        # failfast is reset by the super __init__, so stash it.
        failfast = self.failfast
        super(TestResult, self).__init__()
        self.skip_reasons = {}
        self.__now = None
        self._tags = TagContext()
        # -- Start: As per python 2.7 --
        self.expectedFailures = []
        self.unexpectedSuccesses = []
        self.failfast = failfast
示例#13
0
 def __init__(self):
     super(ExtendedTestResult, self).__init__()
     self._tags = TagContext()
示例#14
0
文件: real.py 项目: LukeM12/samba
 def __init__(self, decorated):
     self.decorated = decorated
     self._tags = TagContext()
     # Only used for old TestResults that do not have failfast.
     self._failfast = False
示例#15
0
文件: real.py 项目: AIdrifter/samba
 def startTest(self, test):
     self._tags = TagContext(self._tags)
     return self.decorated.startTest(test)
示例#16
0
 def startTest(self, test):
     super().startTest(test)
     self._tags = TagContext(self._tags)
示例#17
0
文件: real.py 项目: AIdrifter/samba
 def startTest(self, test):
     super(TestResult, self).startTest(test)
     self._tags = TagContext(self._tags)
示例#18
0
文件: real.py 项目: AIdrifter/samba
class ExtendedToOriginalDecorator(object):
    """Permit new TestResult API code to degrade gracefully with old results.

    This decorates an existing TestResult and converts missing outcomes
    such as addSkip to older outcomes such as addSuccess. It also supports
    the extended details protocol. In all cases the most recent protocol
    is attempted first, and fallbacks only occur when the decorated result
    does not support the newer style of calling.
    """

    def __init__(self, decorated):
        self.decorated = decorated
        self._tags = TagContext()
        # Only used for old TestResults that do not have failfast.
        self._failfast = False

    def __repr__(self):
        return '<%s %r>' % (self.__class__.__name__, self.decorated)

    def __getattr__(self, name):
        return getattr(self.decorated, name)

    def addError(self, test, err=None, details=None):
        try:
            self._check_args(err, details)
            if details is not None:
                try:
                    return self.decorated.addError(test, details=details)
                except TypeError:
                    # have to convert
                    err = self._details_to_exc_info(details)
            return self.decorated.addError(test, err)
        finally:
            if self.failfast:
                self.stop()

    def addExpectedFailure(self, test, err=None, details=None):
        self._check_args(err, details)
        addExpectedFailure = getattr(
            self.decorated, 'addExpectedFailure', None)
        if addExpectedFailure is None:
            return self.addSuccess(test)
        if details is not None:
            try:
                return addExpectedFailure(test, details=details)
            except TypeError:
                # have to convert
                err = self._details_to_exc_info(details)
        return addExpectedFailure(test, err)

    def addFailure(self, test, err=None, details=None):
        try:
            self._check_args(err, details)
            if details is not None:
                try:
                    return self.decorated.addFailure(test, details=details)
                except TypeError:
                    # have to convert
                    err = self._details_to_exc_info(details)
            return self.decorated.addFailure(test, err)
        finally:
            if self.failfast:
                self.stop()

    def addSkip(self, test, reason=None, details=None):
        self._check_args(reason, details)
        addSkip = getattr(self.decorated, 'addSkip', None)
        if addSkip is None:
            return self.decorated.addSuccess(test)
        if details is not None:
            try:
                return addSkip(test, details=details)
            except TypeError:
                # extract the reason if it's available
                try:
                    reason = details['reason'].as_text()
                except KeyError:
                    reason = _details_to_str(details)
        return addSkip(test, reason)

    def addUnexpectedSuccess(self, test, details=None):
        try:
            outcome = getattr(self.decorated, 'addUnexpectedSuccess', None)
            if outcome is None:
                try:
                    test.fail("")
                except test.failureException:
                    return self.addFailure(test, sys.exc_info())
            if details is not None:
                try:
                    return outcome(test, details=details)
                except TypeError:
                    pass
            return outcome(test)
        finally:
            if self.failfast:
                self.stop()

    def addSuccess(self, test, details=None):
        if details is not None:
            try:
                return self.decorated.addSuccess(test, details=details)
            except TypeError:
                pass
        return self.decorated.addSuccess(test)

    def _check_args(self, err, details):
        param_count = 0
        if err is not None:
            param_count += 1
        if details is not None:
            param_count += 1
        if param_count != 1:
            raise ValueError("Must pass only one of err '%s' and details '%s"
                % (err, details))

    def _details_to_exc_info(self, details):
        """Convert a details dict to an exc_info tuple."""
        return (
            _StringException,
            _StringException(_details_to_str(details, special='traceback')),
            None)

    @property
    def current_tags(self):
        return getattr(
            self.decorated, 'current_tags', self._tags.get_current_tags())

    def done(self):
        try:
            return self.decorated.done()
        except AttributeError:
            return

    def _get_failfast(self):
        return getattr(self.decorated, 'failfast', self._failfast)
    def _set_failfast(self, value):
        if safe_hasattr(self.decorated, 'failfast'):
            self.decorated.failfast = value
        else:
            self._failfast = value
    failfast = property(_get_failfast, _set_failfast)

    def progress(self, offset, whence):
        method = getattr(self.decorated, 'progress', None)
        if method is None:
            return
        return method(offset, whence)

    @property
    def shouldStop(self):
        return self.decorated.shouldStop

    def startTest(self, test):
        self._tags = TagContext(self._tags)
        return self.decorated.startTest(test)

    def startTestRun(self):
        self._tags = TagContext()
        try:
            return self.decorated.startTestRun()
        except AttributeError:
            return

    def stop(self):
        return self.decorated.stop()

    def stopTest(self, test):
        self._tags = self._tags.parent
        return self.decorated.stopTest(test)

    def stopTestRun(self):
        try:
            return self.decorated.stopTestRun()
        except AttributeError:
            return

    def tags(self, new_tags, gone_tags):
        method = getattr(self.decorated, 'tags', None)
        if method is not None:
            return method(new_tags, gone_tags)
        else:
            self._tags.change_tags(new_tags, gone_tags)

    def time(self, a_datetime):
        method = getattr(self.decorated, 'time', None)
        if method is None:
            return
        return method(a_datetime)

    def wasSuccessful(self):
        return self.decorated.wasSuccessful()
示例#19
0
 def startTestRun(self):
     super(ExtendedTestResult, self).startTestRun()
     self._was_successful = True
     self._tags = TagContext()
示例#20
0
 def test_no_tags(self):
     # A tag context has no tags initially.
     tag_context = TagContext()
     self.assertEqual(set(), tag_context.get_current_tags())
示例#21
0
 def startTestRun(self):
     super().startTestRun()
     self._was_successful = True
     self._tags = TagContext()
示例#22
0
文件: real.py 项目: LukeM12/samba
 def startTestRun(self):
     self._tags = TagContext()
     try:
         return self.decorated.startTestRun()
     except AttributeError:
         return
示例#23
0
 def test_remove_tag(self):
     # change_tags can remove tags from the context.
     tag_context = TagContext()
     tag_context.change_tags({'foo'}, set())
     tag_context.change_tags(set(), {'foo'})
     self.assertEqual(set(), tag_context.get_current_tags())
示例#24
0
 def test_change_tags_returns_tags(self):
     # change_tags returns the current tags.  This is a convenience.
     tag_context = TagContext()
     tags = tag_context.change_tags({'foo'}, set())
     self.assertEqual({'foo'}, tags)
示例#25
0
 def test_add_tag(self):
     # A tag added with change_tags appears in get_current_tags.
     tag_context = TagContext()
     tag_context.change_tags({'foo'}, set())
     self.assertEqual({'foo'}, tag_context.get_current_tags())
示例#26
0
文件: real.py 项目: LukeM12/samba
class ExtendedToOriginalDecorator(object):
    """Permit new TestResult API code to degrade gracefully with old results.

    This decorates an existing TestResult and converts missing outcomes
    such as addSkip to older outcomes such as addSuccess. It also supports
    the extended details protocol. In all cases the most recent protocol
    is attempted first, and fallbacks only occur when the decorated result
    does not support the newer style of calling.
    """
    def __init__(self, decorated):
        self.decorated = decorated
        self._tags = TagContext()
        # Only used for old TestResults that do not have failfast.
        self._failfast = False

    def __repr__(self):
        return '<%s %r>' % (self.__class__.__name__, self.decorated)

    def __getattr__(self, name):
        return getattr(self.decorated, name)

    def addError(self, test, err=None, details=None):
        try:
            self._check_args(err, details)
            if details is not None:
                try:
                    return self.decorated.addError(test, details=details)
                except TypeError:
                    # have to convert
                    err = self._details_to_exc_info(details)
            return self.decorated.addError(test, err)
        finally:
            if self.failfast:
                self.stop()

    def addExpectedFailure(self, test, err=None, details=None):
        self._check_args(err, details)
        addExpectedFailure = getattr(self.decorated, 'addExpectedFailure',
                                     None)
        if addExpectedFailure is None:
            return self.addSuccess(test)
        if details is not None:
            try:
                return addExpectedFailure(test, details=details)
            except TypeError:
                # have to convert
                err = self._details_to_exc_info(details)
        return addExpectedFailure(test, err)

    def addFailure(self, test, err=None, details=None):
        try:
            self._check_args(err, details)
            if details is not None:
                try:
                    return self.decorated.addFailure(test, details=details)
                except TypeError:
                    # have to convert
                    err = self._details_to_exc_info(details)
            return self.decorated.addFailure(test, err)
        finally:
            if self.failfast:
                self.stop()

    def addSkip(self, test, reason=None, details=None):
        self._check_args(reason, details)
        addSkip = getattr(self.decorated, 'addSkip', None)
        if addSkip is None:
            return self.decorated.addSuccess(test)
        if details is not None:
            try:
                return addSkip(test, details=details)
            except TypeError:
                # extract the reason if it's available
                try:
                    reason = details['reason'].as_text()
                except KeyError:
                    reason = _details_to_str(details)
        return addSkip(test, reason)

    def addUnexpectedSuccess(self, test, details=None):
        try:
            outcome = getattr(self.decorated, 'addUnexpectedSuccess', None)
            if outcome is None:
                try:
                    test.fail("")
                except test.failureException:
                    return self.addFailure(test, sys.exc_info())
            if details is not None:
                try:
                    return outcome(test, details=details)
                except TypeError:
                    pass
            return outcome(test)
        finally:
            if self.failfast:
                self.stop()

    def addSuccess(self, test, details=None):
        if details is not None:
            try:
                return self.decorated.addSuccess(test, details=details)
            except TypeError:
                pass
        return self.decorated.addSuccess(test)

    def _check_args(self, err, details):
        param_count = 0
        if err is not None:
            param_count += 1
        if details is not None:
            param_count += 1
        if param_count != 1:
            raise ValueError("Must pass only one of err '%s' and details '%s" %
                             (err, details))

    def _details_to_exc_info(self, details):
        """Convert a details dict to an exc_info tuple."""
        return (_StringException,
                _StringException(_details_to_str(details,
                                                 special='traceback')), None)

    @property
    def current_tags(self):
        return getattr(self.decorated, 'current_tags',
                       self._tags.get_current_tags())

    def done(self):
        try:
            return self.decorated.done()
        except AttributeError:
            return

    def _get_failfast(self):
        return getattr(self.decorated, 'failfast', self._failfast)

    def _set_failfast(self, value):
        if safe_hasattr(self.decorated, 'failfast'):
            self.decorated.failfast = value
        else:
            self._failfast = value

    failfast = property(_get_failfast, _set_failfast)

    def progress(self, offset, whence):
        method = getattr(self.decorated, 'progress', None)
        if method is None:
            return
        return method(offset, whence)

    @property
    def shouldStop(self):
        return self.decorated.shouldStop

    def startTest(self, test):
        self._tags = TagContext(self._tags)
        return self.decorated.startTest(test)

    def startTestRun(self):
        self._tags = TagContext()
        try:
            return self.decorated.startTestRun()
        except AttributeError:
            return

    def stop(self):
        return self.decorated.stop()

    def stopTest(self, test):
        self._tags = self._tags.parent
        return self.decorated.stopTest(test)

    def stopTestRun(self):
        try:
            return self.decorated.stopTestRun()
        except AttributeError:
            return

    def tags(self, new_tags, gone_tags):
        method = getattr(self.decorated, 'tags', None)
        if method is not None:
            return method(new_tags, gone_tags)
        else:
            self._tags.change_tags(new_tags, gone_tags)

    def time(self, a_datetime):
        method = getattr(self.decorated, 'time', None)
        if method is None:
            return
        return method(a_datetime)

    def wasSuccessful(self):
        return self.decorated.wasSuccessful()
示例#27
0
 def __init__(self):
     super(ExtendedTestResult, self).__init__()
     self._tags = TagContext()
示例#28
0
 def startTestRun(self):
     super(ExtendedTestResult, self).startTestRun()
     self._was_successful = True
     self._tags = TagContext()
示例#29
0
 def __init__(self, event_log=None):
     super(ExtendedTestResult, self).__init__(event_log)
     self._tags = TagContext()
示例#30
0
class ExtendedTestResult(Python27TestResult):
    """A test result like the proposed extended unittest result API."""

    def __init__(self):
        super(ExtendedTestResult, self).__init__()
        self._tags = TagContext()

    def addError(self, test, err=None, details=None):
        self._was_successful = False
        self._events.append(('addError', test, err or details))

    def addFailure(self, test, err=None, details=None):
        self._was_successful = False
        self._events.append(('addFailure', test, err or details))

    def addExpectedFailure(self, test, err=None, details=None):
        self._events.append(('addExpectedFailure', test, err or details))

    def addSkip(self, test, reason=None, details=None):
        self._events.append(('addSkip', test, reason or details))

    def addSuccess(self, test, details=None):
        if details:
            self._events.append(('addSuccess', test, details))
        else:
            self._events.append(('addSuccess', test))

    def addUnexpectedSuccess(self, test, details=None):
        self._was_successful = False
        if details is not None:
            self._events.append(('addUnexpectedSuccess', test, details))
        else:
            self._events.append(('addUnexpectedSuccess', test))

    def progress(self, offset, whence):
        self._events.append(('progress', offset, whence))

    def startTestRun(self):
        super(ExtendedTestResult, self).startTestRun()
        self._was_successful = True
        self._tags = TagContext()

    def startTest(self, test):
        super(ExtendedTestResult, self).startTest(test)
        self._tags = TagContext(self._tags)

    def stopTest(self, test):
        self._tags = self._tags.parent
        super(ExtendedTestResult, self).stopTest(test)

    @property
    def current_tags(self):
        return self._tags.get_current_tags()

    def tags(self, new_tags, gone_tags):
        self._tags.change_tags(new_tags, gone_tags)
        self._events.append(('tags', new_tags, gone_tags))

    def time(self, time):
        self._events.append(('time', time))

    def wasSuccessful(self):
        return self._was_successful
示例#31
0
class ExtendedTestResult(Python27TestResult):
    """A test result like the proposed extended unittest result API."""
    def __init__(self, event_log=None):
        super(ExtendedTestResult, self).__init__(event_log)
        self._tags = TagContext()

    def addError(self, test, err=None, details=None):
        self._was_successful = False
        self._events.append(('addError', test, err or details))

    def addFailure(self, test, err=None, details=None):
        self._was_successful = False
        self._events.append(('addFailure', test, err or details))

    def addExpectedFailure(self, test, err=None, details=None):
        self._events.append(('addExpectedFailure', test, err or details))

    def addSkip(self, test, reason=None, details=None):
        self._events.append(('addSkip', test, reason or details))

    def addSuccess(self, test, details=None):
        if details:
            self._events.append(('addSuccess', test, details))
        else:
            self._events.append(('addSuccess', test))

    def addUnexpectedSuccess(self, test, details=None):
        self._was_successful = False
        if details is not None:
            self._events.append(('addUnexpectedSuccess', test, details))
        else:
            self._events.append(('addUnexpectedSuccess', test))

    def progress(self, offset, whence):
        self._events.append(('progress', offset, whence))

    def startTestRun(self):
        super(ExtendedTestResult, self).startTestRun()
        self._was_successful = True
        self._tags = TagContext()

    def startTest(self, test):
        super(ExtendedTestResult, self).startTest(test)
        self._tags = TagContext(self._tags)

    def stopTest(self, test):
        self._tags = self._tags.parent
        super(ExtendedTestResult, self).stopTest(test)

    @property
    def current_tags(self):
        return self._tags.get_current_tags()

    def tags(self, new_tags, gone_tags):
        self._tags.change_tags(new_tags, gone_tags)
        self._events.append(('tags', new_tags, gone_tags))

    def time(self, time):
        self._events.append(('time', time))

    def wasSuccessful(self):
        return self._was_successful
示例#32
0
文件: real.py 项目: LukeM12/samba
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, failfast=False):
        # 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.
        self.failfast = failfast
        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)))
        if self.failfast:
            self.stop()

    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)))
        if self.failfast:
            self.stop()

    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 = reason.as_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)
        if self.failfast:
            self.stop()

    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)

    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 TracebackContent(err, test).as_text()
        return _details_to_str(details, special='traceback')

    def _exc_info_to_unicode(self, err, test):
        # Deprecated.  Only present because subunit upcalls to it.  See
        # <https://bugs.launchpad.net/testtools/+bug/929063>.
        return TracebackContent(err, test).as_text()

    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.
        """
        # failfast is reset by the super __init__, so stash it.
        failfast = self.failfast
        super(TestResult, self).__init__()
        self.skip_reasons = {}
        self.__now = None
        self._tags = TagContext()
        # -- Start: As per python 2.7 --
        self.expectedFailures = []
        self.unexpectedSuccesses = []
        self.failfast = failfast
        # -- End:   As per python 2.7 --

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

        New in python 2.7
        """

    def startTest(self, test):
        super(TestResult, self).startTest(test)
        self._tags = TagContext(self._tags)

    def stopTest(self, test):
        self._tags = self._tags.parent
        super(TestResult, self).stopTest(test)

    @property
    def current_tags(self):
        """The currently set tags."""
        return self._tags.get_current_tags()

    def tags(self, new_tags, gone_tags):
        """Add and remove tags from the test.

        :param new_tags: A set of tags to be added to the stream.
        :param gone_tags: A set of tags to be removed from the stream.
        """
        self._tags.change_tags(new_tags, gone_tags)

    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.
示例#33
0
文件: real.py 项目: LukeM12/samba
 def startTest(self, test):
     self._tags = TagContext(self._tags)
     return self.decorated.startTest(test)
示例#34
0
文件: real.py 项目: AIdrifter/samba
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, failfast=False):
        # 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.
        self.failfast = failfast
        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)))
        if self.failfast:
            self.stop()

    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)))
        if self.failfast:
            self.stop()

    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 = reason.as_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)
        if self.failfast:
            self.stop()

    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)

    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 TracebackContent(err, test).as_text()
        return _details_to_str(details, special='traceback')

    def _exc_info_to_unicode(self, err, test):
        # Deprecated.  Only present because subunit upcalls to it.  See
        # <https://bugs.launchpad.net/testtools/+bug/929063>.
        return TracebackContent(err, test).as_text()

    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.
        """
        # failfast is reset by the super __init__, so stash it.
        failfast = self.failfast
        super(TestResult, self).__init__()
        self.skip_reasons = {}
        self.__now = None
        self._tags = TagContext()
        # -- Start: As per python 2.7 --
        self.expectedFailures = []
        self.unexpectedSuccesses = []
        self.failfast = failfast
        # -- End:   As per python 2.7 --

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

        New in python 2.7
        """

    def startTest(self, test):
        super(TestResult, self).startTest(test)
        self._tags = TagContext(self._tags)

    def stopTest(self, test):
        self._tags = self._tags.parent
        super(TestResult, self).stopTest(test)

    @property
    def current_tags(self):
        """The currently set tags."""
        return self._tags.get_current_tags()

    def tags(self, new_tags, gone_tags):
        """Add and remove tags from the test.

        :param new_tags: A set of tags to be added to the stream.
        :param gone_tags: A set of tags to be removed from the stream.
        """
        self._tags.change_tags(new_tags, gone_tags)

    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.
示例#35
0
 def test_change_tags_returns_tags(self):
     # change_tags returns the current tags.  This is a convenience.
     tag_context = TagContext()
     tags = tag_context.change_tags(set(['foo']), set())
     self.assertEqual(set(['foo']), tags)
示例#36
0
文件: real.py 项目: AIdrifter/samba
 def __init__(self, decorated):
     self.decorated = decorated
     self._tags = TagContext()
     # Only used for old TestResults that do not have failfast.
     self._failfast = False
示例#37
0
 def test_remove_tag(self):
     # change_tags can remove tags from the context.
     tag_context = TagContext()
     tag_context.change_tags(set(['foo']), set())
     tag_context.change_tags(set(), set(['foo']))
     self.assertEqual(set(), tag_context.get_current_tags())
示例#38
0
文件: real.py 项目: AIdrifter/samba
 def startTestRun(self):
     self._tags = TagContext()
     try:
         return self.decorated.startTestRun()
     except AttributeError:
         return
示例#39
0
 def __init__(self, event_log=None):
     super().__init__(event_log)
     self._tags = TagContext()
示例#40
0
 def startTest(self, test):
     super(ExtendedTestResult, self).startTest(test)
     self._tags = TagContext(self._tags)
示例#41
0
 def test_no_tags(self):
     # A tag context has no tags initially.
     tag_context = TagContext()
     self.assertEqual(set(), tag_context.get_current_tags())
示例#42
0
 def __init__(self, event_log=None):
     super(ExtendedTestResult, self).__init__(event_log)
     self._tags = TagContext()
示例#43
0
 def test_add_tag(self):
     # A tag added with change_tags appears in get_current_tags.
     tag_context = TagContext()
     tag_context.change_tags(set(['foo']), set())
     self.assertEqual(set(['foo']), tag_context.get_current_tags())