Repository navigation
Expand file tree
/
Copy pathtesting.py
More file actions
308 lines (244 loc) · 10.1 KB
/
Copy pathtesting.py
File metadata and controls
308 lines (244 loc) · 10.1 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"""
Various functions for testing effects.
The main goal of this code is to allow you to safely tests your effects
in a way that makes it hard to *accidentally* perform real effects in your
tests.
"""
from __future__ import print_function
from contextlib import contextmanager
from functools import partial
import sys
from characteristic import attributes
from ._base import Effect, guard, _Box, NoPerformerFoundError
from ._sync import NotSynchronousError, sync_performer
from ._intents import Constant, Error, Func, ParallelEffects
import six
@attributes(['intent'], apply_with_init=False)
class Stub(object):
"""
An intent which wraps another intent, to flag that the intent should
be automatically resolved by :func:`resolve_stub`.
:class:`Stub` is intentionally not performable by any default
mechanism.
"""
def __init__(self, intent):
"""
:param intent: The intent to perform with :func:`resolve_stub`.
"""
self.intent = intent
def ESConstant(x):
"""Return Effect(Stub(Constant(x)))"""
return Effect(Stub(Constant(x)))
def ESError(x):
"""Return Effect(Stub(Error(x)))"""
return Effect(Stub(Error(x)))
def ESFunc(x):
"""Return Effect(Stub(Func(x)))"""
return Effect(Stub(Func(x)))
def resolve_effect(effect, result, is_error=False):
"""
Supply a result for an effect, allowing its callbacks to run.
The return value of the last callback is returned, unless any callback
returns another Effect, in which case an Effect representing that
operation plus the remaining callbacks will be returned.
This allows you to test your code in a somewhat "channel"-oriented
way:
eff = do_thing()
next_eff = resolve_effect(eff, first_result)
next_eff = resolve_effect(next_eff, second_result)
result = resolve_effect(next_eff, third_result)
Equivalently, if you don't care about intermediate results::
result = resolve_effect(
resolve_effect(
resolve_effect(
do_thing(),
first_result),
second_result),
third_result)
NOTE: parallel effects have no special support. They can be resolved with
a sequence, and if they're returned from another effect's callback they
will be returned just like any other effect.
:param bool is_error: Indicate whether the result should be treated as an
exception or a regular result.
:param result: If ``is_error`` is False, this can be any object and will be
treated as the result of the effect. If ``is_error`` is True, this must
be a three-tuple in the style of ``sys.exc_info``.
"""
for i, (callback, errback) in enumerate(effect.callbacks):
cb = errback if is_error else callback
if cb is None:
continue
is_error, result = guard(cb, result)
if type(result) is Effect:
return Effect(
result.intent,
callbacks=result.callbacks + effect.callbacks[i + 1:])
if is_error:
six.reraise(*result)
return result
def fail_effect(effect, exception):
"""
Resolve an effect with an exception, so its error handler will be run.
"""
try:
raise exception
except:
return resolve_effect(effect, sys.exc_info(), is_error=True)
def resolve_stub(dispatcher, effect):
"""
Automatically perform an effect, if its intent is a :obj:`Stub`.
Note that resolve_stubs is preferred to this function, since it handles
chains of stub effects.
"""
if type(effect.intent) is Stub:
performer = dispatcher(effect.intent.intent)
if performer is None:
raise NoPerformerFoundError(effect.intent.intent)
result_slot = []
box = _Box(result_slot.append)
performer(dispatcher, effect.intent.intent, box)
if len(result_slot) == 0:
raise NotSynchronousError(
"Performer %r was not synchronous during stub resolution for "
"effect %r"
% (performer, effect))
if len(result_slot) > 1:
raise RuntimeError(
"Pathological error (too many box results) while running "
"performer %r for effect %r"
% (performer, effect))
return resolve_effect(effect, result_slot[0][1],
is_error=result_slot[0][0])
else:
raise TypeError("resolve_stub can only resolve stubs, not %r"
% (effect,))
def resolve_stubs(dispatcher, effect):
"""
Successively performs effects with resolve_stub until a non-Effect value,
or an Effect with a non-stub intent is returned, and return that value.
Parallel effects are supported by recursively invoking resolve_stubs on
the child effects, if all of their children are stubs.
"""
if type(effect) is not Effect:
raise TypeError("effect must be Effect: %r" % (effect,))
while type(effect) is Effect:
if type(effect.intent) is Stub:
effect = resolve_stub(dispatcher, effect)
elif type(effect.intent) is ParallelEffects:
if not all(isinstance(x.intent, Stub)
for x in effect.intent.effects):
break
else:
effect = resolve_effect(
effect,
list(map(partial(resolve_stubs, dispatcher),
effect.intent.effects)))
else:
break
return effect
class EQDispatcher(object):
"""
An equality-based (constant) dispatcher.
This dispatcher looks up intents by equality and performs them by returning
an associated constant value.
Users provide a mapping of intents to results, where the intents are
matched against the intents being performed with a simple equality check
(not a type check!).
The mapping must be provided as a sequence of two-tuples. We don't use a
dict because we don't want to require that the intents be hashable (in
practice a lot of them aren't, and it's a pain to require it). If you want
to construct your mapping as a dict, you can, just pass in the result of
``d.items()``.
e.g.::
>>> sync_perform(EQDispatcher([(MyIntent(1, 2), 'the-result')]),
... Effect(MyIntent(1, 2)))
'the-result'
assuming MyIntent supports ``__eq__`` by value.
"""
def __init__(self, mapping):
"""
:param list mapping: A sequence of tuples of (intent, result).
"""
self.mapping = mapping
def __call__(self, intent):
# Avoid hashing, because a lot of intents aren't hashable.
for k, v in self.mapping:
if k == intent:
return sync_performer(lambda d, i: v)
class EQFDispatcher(object):
"""
An Equality-based function dispatcher.
This dispatcher looks up intents by equality and performs them by invoking
an associated function.
Users provide a mapping of intents to functions, where the intents are
matched against the intents being performed with a simple equality check
(not a type check!). The functions in the mapping will be passed only the
intent and are expected to return the result or raise an exception.
The mapping must be provided as a sequence of two-tuples. We don't use a
dict because we don't want to require that the intents be hashable (in
practice a lot of them aren't, and it's a pain to require it). If you want
to construct your mapping as a dict, you can, just pass in the result of
``d.items()``.
e.g.::
>>> sync_perform(
... EQFDispatcher([(
... MyIntent(1, 2), lambda i: 'the-result')]),
... Effect(MyIntent(1, 2)))
'the-result'
assuming MyIntent supports ``__eq__`` by value.
"""
def __init__(self, mapping):
"""
:param list mapping: A sequence of two-tuples of (intent, function).
"""
self.mapping = mapping
def __call__(self, intent):
# Avoid hashing, because a lot of intents aren't hashable.
for k, v in self.mapping:
if k == intent:
return sync_performer(lambda d, i: v(i))
class SequenceDispatcher(object):
"""
A dispatcher which steps through a sequence of (intent, func) tuples and
runs ``func`` to perform intents in strict sequence.
So, if you expect to first perform an intent like ``MyIntent('a')`` and
then an intent like ``OtherIntent('b')``, you can create and use a
dispatcher like this::
sequence = SequenceDispatcher([
(MyIntent('a'), lambda i: 'my-intent-result'),
(OtherIntent('b'), lambda i: 'other-intent-result')
])
with sequence.consume():
perform(sequence, eff)
It's important to use `with sequence.consume():` to ensure that all of the
intents are performed. Otherwise, if your code has a bug that causes it to
return before all effects are performed, your test may not fail.
:obj:`None` is returned if the next intent in the sequence is not equal to
the intent being performed, or if there are no more items left in the
sequence (this is standard behavior for dispatchers that don't handle an
intent).
"""
def __init__(self, sequence):
""":param list sequence: Sequence of (intent, fn)."""
self.sequence = sequence
def __call__(self, intent):
if len(self.sequence) == 0:
return
exp_intent, func = self.sequence[0]
if intent == exp_intent:
self.sequence = self.sequence[1:]
return sync_performer(lambda d, i: func(i))
def consumed(self):
"""Return True if all of the steps were performed."""
return len(self.sequence) == 0
@contextmanager
def consume(self):
"""
Return a context manager that can be used with the `with` syntax to
ensure that all steps are performed by the end.
"""
yield
if not self.consumed():
raise AssertionError(
"Not all intents were performed: {0}".format(
[x[0] for x in self.sequence]))