Repository navigation
Expand file tree
/
Copy pathtest_txeffect.py
More file actions
227 lines (183 loc) · 7.09 KB
/
Copy pathtest_txeffect.py
File metadata and controls
227 lines (183 loc) · 7.09 KB
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
from __future__ import absolute_import
from functools import partial
from testtools import TestCase
from testtools.matchers import MatchesListwise, Equals
from twisted.trial.unittest import SynchronousTestCase
from twisted.internet.defer import Deferred
from twisted.internet.task import Clock
from twisted.python.failure import Failure
from effect import (
Constant,
Delay,
Effect,
base_dispatcher,
parallel,
ComposedDispatcher,
)
from effect._test_utils import MatchesException
from . import deferred_performer, make_twisted_dispatcher, perform
def func_dispatcher(intent):
"""
Simple effect dispatcher that takes callables taking a box,
and calls them with the given box.
"""
def performer(dispatcher, intent, box):
intent(box)
return performer
def _dispatcher(reactor):
return ComposedDispatcher([make_twisted_dispatcher(reactor), base_dispatcher])
class TestCase(TestCase, SynchronousTestCase):
skip = None # horrible hack to make trial cooperate with testtools
class ParallelTests(TestCase):
"""Tests for :func:`parallel`."""
def test_parallel(self):
"""
'parallel' results in a list of results of the given effects, in the
same order that they were passed to parallel.
"""
d = perform(
_dispatcher(None), parallel([Effect(Constant("a")), Effect(Constant("b"))])
)
self.assertEqual(self.successResultOf(d), ["a", "b"])
class DelayTests(TestCase):
"""Tests for :class:`Delay`."""
def test_delay(self):
"""
Delay intents will cause time to pass with reactor.callLater, and
result in None.
"""
clock = Clock()
called = []
eff = Effect(Delay(1)).on(called.append)
perform(make_twisted_dispatcher(clock), eff)
self.assertEqual(called, [])
clock.advance(1)
self.assertEqual(called, [None])
class TwistedPerformTests(TestCase):
def test_perform(self):
"""
effect.twisted.perform returns a Deferred which fires with the ultimate
result of the Effect.
"""
boxes = []
e = Effect(boxes.append)
d = perform(func_dispatcher, e)
self.assertNoResult(d)
boxes[0].succeed("foo")
self.assertEqual(self.successResultOf(d), "foo")
def test_perform_failure(self):
"""
effect.twisted.perform fails the Deferred it returns if the ultimate
result of the Effect is an exception.
"""
try:
raise ValueError("oh dear")
except Exception as e:
exc = e
boxes = []
e = Effect(boxes.append)
d = perform(func_dispatcher, e)
self.assertNoResult(d)
boxes[0].fail(exc)
f = self.failureResultOf(d)
self.assertEqual(f.type, ValueError)
self.assertEqual(str(f.value), "oh dear")
self.assertRegex(
f.getTraceback().splitlines()[-3],
r'^\s+File ".*?test_txeffect.py", line \d+, in test_perform_failure$',
)
class DeferredPerformerTests(TestCase):
"""Tests for :func:`deferred_performer`."""
def test_deferred_success(self):
"""
@deferred_performer wraps a function taking the dispatcher and intent
and hooks up its Deferred result to the box.
"""
deferred = Deferred()
eff = Effect("meaningless").on(success=lambda x: ("success", x))
dispatcher = lambda i: deferred_performer(lambda dispatcher, intent: deferred)
result = perform(dispatcher, eff)
self.assertNoResult(result)
deferred.callback("foo")
self.assertEqual(self.successResultOf(result), ("success", "foo"))
def test_deferred_failure(self):
"""
A failing Deferred causes error handlers to be called with an exception
tuple based on the failure.
"""
deferred = Deferred()
eff = Effect("meaningless").on(error=lambda e: ("error", e))
dispatcher = lambda i: deferred_performer(lambda dispatcher, intent: deferred)
result = perform(dispatcher, eff)
self.assertNoResult(result)
deferred.errback(Failure(ValueError("foo")))
self.assertThat(
self.successResultOf(result),
MatchesListwise([Equals("error"), MatchesException(ValueError("foo"))]),
)
def test_synchronous_success(self):
"""
If ``deferred_performer`` wraps a function that returns a non-deferred,
that result is the result of the effect.
"""
dispatcher = lambda i: deferred_performer(lambda dispatcher, intent: "foo")
result = perform(dispatcher, Effect("meaningless"))
self.assertEqual(self.successResultOf(result), "foo")
def test_synchronous_exception(self):
"""
If ``deferred_performer`` wraps a function that raises an exception,
the effect results in that exception.
"""
def raise_():
raise ValueError("foo")
dispatcher = lambda i: deferred_performer(lambda dispatcher, intent: raise_())
eff = Effect("meaningless").on(error=lambda e: ("error", e))
result = perform(dispatcher, eff)
self.assertThat(
self.successResultOf(result),
MatchesListwise([Equals("error"), MatchesException(ValueError("foo"))]),
)
def test_instance_method_performer(self):
"""The @deferred_performer decorator works on instance methods."""
eff = Effect("meaningless")
class PerformerContainer(object):
@deferred_performer
def performer(self, dispatcher, intent):
return (self, dispatcher, intent)
container = PerformerContainer()
dispatcher = lambda i: container.performer
result = self.successResultOf(perform(dispatcher, eff))
self.assertEqual(result, (container, dispatcher, "meaningless"))
def test_promote_metadata(self):
"""
The decorator copies metadata from the wrapped function onto the
wrapper.
"""
def original(dispatcher, intent):
"""Original!"""
pass
original.attr = 1
wrapped = deferred_performer(original)
self.assertEqual(wrapped.__name__, "original")
self.assertEqual(wrapped.attr, 1)
self.assertEqual(wrapped.__doc__, "Original!")
def test_ignore_lack_of_metadata(self):
"""
When the original callable is not a function, a new function is still
returned.
"""
def original(something, dispatcher, intent):
"""Original!"""
pass
new_func = partial(original, "something")
original.attr = 1
wrapped = deferred_performer(new_func)
self.assertEqual(wrapped.__name__, "deferred_wrapper")
def test_kwargs(self):
"""Additional kwargs are passed through."""
@deferred_performer
def p(dispatcher, intent, extra):
return extra
dispatcher = lambda _: partial(p, extra="extra val")
result = self.successResultOf(perform(dispatcher, Effect("foo")))
self.assertEqual(result, "extra val")