File: future_test.py

package info (click to toggle)
pyhamcrest 2.1.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 844 kB
  • sloc: python: 4,081; makefile: 114; sh: 15
file content (185 lines) | stat: -rw-r--r-- 7,216 bytes parent folder | download
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
185
import sys

import pytest
import asyncio
from hamcrest import has_properties
from hamcrest.core.core.future import resolved, future_raising
from hamcrest_unit_test.matcher_test import MatcherTest

if __name__ == "__main__":
    sys.path.insert(0, "..")
    sys.path.insert(0, "../..")


__author__ = "David Keijser"
__copyright__ = "Copyright 2023 hamcrest.org"
__license__ = "BSD, see License.txt"


async def no_exception(*args, **kwargs):
    return


async def raise_exception(*args, **kwargs):
    raise AssertionError(str(args) + str(kwargs))


async def raise_exception_with_properties(**kwargs):
    err = AssertionError("boom")
    for k, v in kwargs.items():
        setattr(err, k, v)
    raise err


# From python 3.8 this could be simplified by using unittest.IsolatedAsyncioTestCase
class FutureExceptionTest(MatcherTest):
    def testMatchesIfFutureHasTheExactExceptionExpected(self):
        async def test():
            self.assert_matches(
                "Right exception",
                future_raising(AssertionError),
                await resolved(raise_exception()),
            )

        asyncio.new_event_loop().run_until_complete(test())

    def testDoesNotMatchIfActualIsNotAFuture(self):
        async def test():
            self.assert_does_not_match("Not a future", future_raising(TypeError), 23)

        asyncio.new_event_loop().run_until_complete(test())

    def testDoesNotMatchIfFutureIsNotDone(self):
        future = asyncio.Future(loop=asyncio.new_event_loop())
        self.assert_does_not_match("Unresolved future", future_raising(TypeError), future)

    def testDoesNotMatchIfFutureIsCancelled(self):
        future = asyncio.Future(loop=asyncio.new_event_loop())
        future.cancel()
        self.assert_does_not_match("Cancelled future", future_raising(TypeError), future)

    @pytest.mark.skipif(
        not (3, 0) <= sys.version_info < (3, 7), reason="Message differs between Python versions"
    )
    def testDoesNotMatchIfFutureHasTheWrongExceptionTypePy3(self):
        return
        async def test():
            self.assert_does_not_match(
                "Wrong exception", future_raising(IOError), await resolved(raise_exception())
            )
            expected_message = (
                "AssertionError('(){}',) of type <class 'AssertionError'> was raised instead"
            )
            self.assert_mismatch_description(
                expected_message, future_raising(TypeError), await resolved(raise_exception())
            )

        asyncio.get_event_loop().run_until_complete(test())

    @pytest.mark.skipif(sys.version_info < (3, 7), reason="Message differs between Python versions")
    def testDoesNotMatchIfFutureHasTheWrongExceptionTypePy37(self):
        async def test():
            self.assert_does_not_match(
                "Wrong exception", future_raising(IOError), await resolved(raise_exception())
            )
            expected_message = (
                "AssertionError('(){}') of type <class 'AssertionError'> was raised instead"
            )
            self.assert_mismatch_description(
                expected_message, future_raising(TypeError), await resolved(raise_exception())
            )

        asyncio.new_event_loop().run_until_complete(test())

    def testMatchesIfFutureHasASubclassOfTheExpectedException(self):
        async def test():
            self.assert_matches(
                "Subclassed Exception",
                future_raising(Exception),
                await resolved(raise_exception()),
            )

        asyncio.new_event_loop().run_until_complete(test())

    def testDoesNotMatchIfFutureDoesNotHaveException(self):
        async def test():
            self.assert_does_not_match(
                "No exception", future_raising(ValueError), await resolved(no_exception())
            )

        asyncio.new_event_loop().run_until_complete(test())

    def testDoesNotMatchExceptionIfRegularExpressionDoesNotMatch(self):
        async def test():
            self.assert_does_not_match(
                "Bad regex",
                future_raising(AssertionError, "Phrase not found"),
                await resolved(raise_exception()),
            )
            self.assert_mismatch_description(
                '''Correct assertion type raised, but the expected pattern ("Phrase not found") not found. Exception message was: "(){}"''',
                future_raising(AssertionError, "Phrase not found"),
                await resolved(raise_exception()),
            )

        asyncio.new_event_loop().run_until_complete(test())

    def testMatchesRegularExpressionToStringifiedException(self):
        async def test():
            self.assert_matches(
                "Regex",
                future_raising(AssertionError, "(3, 1, 4)"),
                await resolved(raise_exception(3, 1, 4)),
            )

            self.assert_matches(
                "Regex",
                future_raising(AssertionError, r"([\d, ]+)"),
                await resolved(raise_exception(3, 1, 4)),
            )

        asyncio.new_event_loop().run_until_complete(test())

    def testMachesIfExceptionMatchesAdditionalMatchers(self):
        async def test():
            self.assert_matches(
                "Properties",
                future_raising(AssertionError, matching=has_properties(prip="prop")),
                await resolved(raise_exception_with_properties(prip="prop")),
            )

        asyncio.new_event_loop().run_until_complete(test())

    def testDoesNotMatchIfAdditionalMatchersDoesNotMatch(self):
        async def test():
            self.assert_does_not_match(
                "Bad properties",
                future_raising(AssertionError, matching=has_properties(prop="prip")),
                await resolved(raise_exception_with_properties(prip="prop")),
            )
            self.assert_mismatch_description(
                '''Correct assertion type raised, but an object with a property 'prop' matching 'prip' not found. Exception message was: "boom"''',
                future_raising(AssertionError, matching=has_properties(prop="prip")),
                await resolved(raise_exception_with_properties(prip="prop")),
            )

        asyncio.new_event_loop().run_until_complete(test())

    def testDoesNotMatchIfNeitherPatternOrMatcherMatch(self):
        async def test():
            self.assert_does_not_match(
                "Bad pattern and properties",
                future_raising(
                    AssertionError, pattern="asdf", matching=has_properties(prop="prip")
                ),
                await resolved(raise_exception_with_properties(prip="prop")),
            )
            self.assert_mismatch_description(
                '''Correct assertion type raised, but the expected pattern ("asdf") and an object with a property 'prop' matching 'prip' not found. Exception message was: "boom"''',
                future_raising(
                    AssertionError, pattern="asdf", matching=has_properties(prop="prip")
                ),
                await resolved(raise_exception_with_properties(prip="prop")),
            )

        asyncio.new_event_loop().run_until_complete(test())