summaryrefslogtreecommitdiff
path: root/testtools/twistedsupport/_matchers.py
blob: 99985e3814c725fe731ccdc1658a4881fdb8025e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# Copyright (c) testtools developers. See LICENSE for details.

"""Matchers that operate on synchronous Deferreds.

A "synchronous" Deferred is one that does not need the reactor or any other
asynchronous process in order to fire.

Normal application code can't know when a Deferred is going to fire, because
that is generally left up to the reactor. Unit tests can (and should!) provide
fake reactors, or don't use the reactor at all, so that Deferreds fire
synchronously.

These matchers allow you to make assertions about when and how Deferreds fire,
and about what values they fire with.
"""

from testtools.compat import _u
from testtools.matchers import Mismatch

from ._deferred import failure_content, on_deferred_result


class _NoResult(object):
    """Matches a Deferred that has not yet fired."""

    @staticmethod
    def _got_result(deferred, result):
        return Mismatch(
            _u('No result expected on %r, found %r instead'
               % (deferred, result)))

    def match(self, deferred):
        """Match ``deferred`` if it hasn't fired."""
        return on_deferred_result(
            deferred,
            on_success=self._got_result,
            on_failure=self._got_result,
            on_no_result=lambda _: None,
        )


_NO_RESULT = _NoResult()


def has_no_result():
    """Match a Deferred that has not yet fired.

    For example, this will pass::

        assert_that(defer.Deferred(), has_no_result())

    But this will fail:

    >>> assert_that(defer.succeed(None), has_no_result())
    Traceback (most recent call last):
      ...
      File "testtools/assertions.py", line 22, in assert_that
        raise MismatchError(matchee, matcher, mismatch, verbose)
    testtools.matchers._impl.MismatchError: No result expected on <Deferred at ... current result: None>, found None instead

    As will this:

    >>> assert_that(defer.fail(RuntimeError('foo')), has_no_result())
    Traceback (most recent call last):
      ...
      File "testtools/assertions.py", line 22, in assert_that
        raise MismatchError(matchee, matcher, mismatch, verbose)
    testtools.matchers._impl.MismatchError: No result expected on <Deferred at ... current result: <twisted.python.failure.Failure <type 'exceptions.RuntimeError'>>>, found <twisted.python.failure.Failure <type 'exceptions.RuntimeError'>> instead
    """
    return _NO_RESULT


class _Succeeded(object):
    """Matches a Deferred that has fired successfully."""

    def __init__(self, matcher):
        """Construct a ``_Succeeded`` matcher."""
        self._matcher = matcher

    @staticmethod
    def _got_failure(deferred, failure):
        deferred.addErrback(lambda _: None)
        return Mismatch(
            _u('Success result expected on %r, found failure result '
               'instead: %r' % (deferred, failure)),
            {'traceback': failure_content(failure)},
        )

    @staticmethod
    def _got_no_result(deferred):
        return Mismatch(
            _u('Success result expected on %r, found no result '
               'instead' % (deferred,)))

    def match(self, deferred):
        """Match against the successful result of ``deferred``."""
        return on_deferred_result(
            deferred,
            on_success=lambda _, value: self._matcher.match(value),
            on_failure=self._got_failure,
            on_no_result=self._got_no_result,
        )


def succeeded(matcher):
    """Match a Deferred that has fired successfully.

    For example::

        fires_with_the_answer = succeeded(Equals(42))
        deferred = defer.succeed(42)
        assert_that(deferred, fires_with_the_answer)

    This assertion will pass. However, if ``deferred`` had fired with a
    different value, or had failed, or had not fired at all, then it would
    fail.

    Use this instead of
    :py:meth:`twisted.trial.unittest.SynchronousTestCase.successResultOf`.

    :param matcher: A matcher to match against the result of a
        :class:`~twisted.internet.defer.Deferred`.
    :return: A matcher that can be applied to a synchronous
        :class:`~twisted.internet.defer.Deferred`.
    """
    return _Succeeded(matcher)


class _Failed(object):
    """Matches a Deferred that has failed."""

    def __init__(self, matcher):
        self._matcher = matcher

    def _got_failure(self, deferred, failure):
        # We have handled the failure, so suppress its output.
        deferred.addErrback(lambda _: None)
        return self._matcher.match(failure)

    @staticmethod
    def _got_success(deferred, success):
        return Mismatch(
            _u('Failure result expected on %r, found success '
               'result (%r) instead' % (deferred, success)))

    @staticmethod
    def _got_no_result(deferred):
        return Mismatch(
            _u('Failure result expected on %r, found no result instead'
               % (deferred,)))

    def match(self, deferred):
        return on_deferred_result(
            deferred,
            on_success=self._got_success,
            on_failure=self._got_failure,
            on_no_result=self._got_no_result,
        )


def failed(matcher):
    """Match a Deferred that has failed.

    For example::

        error = RuntimeError('foo')
        fails_at_runtime = failed(
            AfterPreprocessing(lambda f: f.value, Equals(error)))
        deferred = defer.fail(error)
        assert_that(deferred, fails_at_runtime)

    This assertion will pass. However, if ``deferred`` had fired successfully,
    had failed with a different error, or had not fired at all, then it would
    fail.

    Use this instead of
    :py:meth:`twisted.trial.unittest.SynchronousTestCase.failureResultOf`.

    :param matcher: A matcher to match against the result of a failing
        :class:`~twisted.internet.defer.Deferred`.
    :return: A matcher that can be applied to a synchronous
        :class:`~twisted.internet.defer.Deferred`.
    """
    return _Failed(matcher)