-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathtest_result.py
504 lines (356 loc) · 11.6 KB
/
test_result.py
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
from collections.abc import Callable, Generator
from typing import Any
import pytest
from hypothesis import given # type: ignore
from hypothesis import strategies as st
from pydantic import BaseModel, TypeAdapter
from expression import Error, Nothing, Ok, Option, Result, Some, effect, result
from expression.collections import Block
from expression.extra.result import pipeline, sequence
from .utils import CustomException
def test_pattern_match_with_alias():
xs: Result[int, str] = Ok(42)
match xs:
case Result(tag="ok", ok=x):
assert x == 42
case _:
assert False
def test_result_ok():
xs: Result[int, str] = Result.Ok(42)
assert isinstance(xs, Result)
assert xs.is_ok()
assert not xs.is_error()
assert str(xs) == "Ok 42"
match xs:
case Result(tag="ok", ok=x):
assert x == 42
case _:
assert False
def test_result_match_ok():
xs: Result[int, str] = Result.Ok(42)
match xs:
case Result(tag="ok", ok=x):
assert x == 42
case _:
assert False
def test_result_match_error():
xs: Result[int, str] = Error("err")
match xs:
case Result(tag="error", error=err):
assert err == "err"
case _: # type: ignore
assert False
def test_result_ok_iterate():
for x in Ok(42):
assert x == 42
def test_result_error():
error = CustomException("d'oh!")
xs: Result[str, Exception] = Error(error)
assert isinstance(xs, Result)
assert not xs.is_ok()
assert xs.is_error()
assert str(xs) == f"Error {error}"
match xs:
case Result(tag="ok"):
assert False
case Result(error=ex):
assert ex == error
# def test_result_error_iterate():
# with pytest.raises(Exception) as excinfo:
# error: Result[int, str] = Error("err")
# for _ in error:
# assert False
# assert excinfo.value.error == "err" # type: ignore
@given(st.integers(), st.integers())
def test_result_ok_equals_ok(x: int, y: int):
xs: Result[int, Exception] = Ok(x)
ys: Result[int, Exception] = Ok(y)
assert xs == ys if x == y else xs != ys
@given(st.integers()) # type: ignore
def test_result_ok_not_equals_error(x: int):
assert not Ok(x) == Error(x)
assert not Error(x) == Ok(x)
@given(st.text(), st.text())
def test_result_error_equals_error(x: int, y: int):
xs: Result[int, int] = Error(x)
ys: Result[int, int] = Error(y)
assert xs == ys if x == y else xs != ys
@given(st.integers(), st.integers())
def test_result_map_piped(x: int, y: int):
xs: Result[int, Exception] = Ok(x)
mapper: Callable[[int], int] = lambda x: x + y
ys = xs.pipe(result.map(mapper)) # NOTE: shows type error for mypy
match ys:
case Result(tag="ok", ok=value):
assert value == mapper(x)
case _:
assert False
@given(st.integers(), st.integers())
def test_result_map_ok_fluent(x: int, y: int):
xs: Result[int, Exception] = Ok(x)
mapper: Callable[[int], int] = lambda x: x + y
ys = xs.map(mapper)
match ys:
case Result(tag="ok", ok=value):
assert value == mapper(x)
case _:
assert False
@given(st.integers(), st.integers())
def test_result_ok_chained_map(x: int, y: int):
xs: Result[int, Exception] = Ok(x)
mapper1: Callable[[int], int] = lambda x: x + y
mapper2: Callable[[int], int] = lambda x: x * 10
ys = xs.map(mapper1).map(mapper2)
match ys:
case Result(tag="ok", ok=value):
assert value == mapper2(mapper1(x))
case _:
assert False
@given(st.text(), st.integers()) # type: ignore
def test_result_map_error_piped(msg: str, y: int):
xs: Result[int, str] = Error(msg)
mapper: Callable[[int], int] = lambda x: x + y
ys = xs.pipe(result.map(mapper))
match ys:
case Result(tag="error", error=err):
assert err == msg
case _:
assert False
@given(st.text(), st.integers()) # type: ignore
def test_result_map_error_fluent(msg: str, y: int):
xs: Result[int, str] = Error(msg)
mapper: Callable[[int], int] = lambda x: x + y
ys = xs.map(mapper)
match ys:
case Result(tag="error", error=err):
assert err == msg
case _:
assert False
@given(st.text(), st.integers()) # type: ignore
def test_result_error_chained_map(msg: str, y: int):
xs: Result[int, str] = Error(msg)
mapper1: Callable[[int], int] = lambda x: x + y
mapper2: Callable[[int], int] = lambda x: x * 10
ys = xs.map(mapper1).map(mapper2)
match ys:
case Result(tag="error", error=err):
assert err == msg
case _:
assert False
@given(st.integers(), st.integers()) # type: ignore
def test_result_bind_piped(x: int, y: int):
xs: Result[int, str] = Ok(x)
mapper: Callable[[int], Result[int, str]] = lambda x: Ok(x + y)
ys = xs.pipe(result.bind(mapper))
match ys:
case Result(tag="ok", ok=value):
assert Ok(value) == mapper(x)
case _:
assert False
@given(st.lists(st.integers())) # type: ignore
def test_result_traverse_ok(xs: list[int]):
ys: Block[Result[int, str]] = Block([Ok(x) for x in xs])
zs = sequence(ys)
match zs:
case Result(tag="ok", ok=value):
assert sum(value) == sum(xs)
case _:
assert False
@given(st.lists(st.integers(), min_size=5)) # type: ignore
def test_result_traverse_error(xs: list[int]):
error = "Do'h"
ys: Block[Result[int, str]] = Block([Ok(x) if i == 3 else Error(error) for x, i in enumerate(xs)])
zs = sequence(ys)
match zs:
case Result(tag="error", error=err):
assert err == error
case _:
assert False
def test_result_effect_zero():
@effect.result()
def fn():
while False:
yield
with pytest.raises(NotImplementedError):
fn()
def test_result_effect_yield_ok():
@effect.result[int, Exception]()
def fn():
yield 42
return None
xs = fn()
for x in xs:
assert x == 42
def test_result_effect_return_ok():
@effect.result[int, Exception]()
def fn() -> Generator[int, int, int]:
x: int = yield 42
return x
xs = fn()
match xs:
case Result(tag="ok", ok=x):
assert x == 42
case _:
assert False
def test_result_effect_yield_from_ok():
@effect.result[int, Exception]()
def fn() -> Generator[int, int, int]:
x = yield from Ok(42)
return x + 1
xs = fn()
match xs:
case Result(tag="ok", ok=x):
assert x == 43
case _:
assert False
def test_result_effect_yield_from_error():
error = "Do'h"
def mayfail() -> Result[int, str]:
return Error(error)
@effect.result[int, Exception]()
def fn() -> Generator[int, int, int]:
xs = mayfail()
x: int = yield from xs
return x + 1
xs = fn()
match xs:
case Result(tag="error", error=err):
assert err == error
case _:
assert False, "Should not happen"
def test_result_effect_multiple_ok():
@effect.result[int, Exception]()
def fn() -> Generator[int, int, int]:
x: int = yield 42
y = yield from Ok(43)
return x + y
xs = fn()
match xs:
case Result(tag="ok", ok=value):
assert value == 85
case _:
assert False
def test_result_effect_throws():
error = CustomException("this happend!")
@effect.result[int, Exception]()
def fn() -> Generator[int, int, int]:
_ = yield from Ok(42)
raise error
with pytest.raises(CustomException) as exc:
fn()
assert exc.value == error
def test_pipeline_none():
hn = pipeline()
assert hn(42) == Ok(42)
def test_pipeline_works():
fn: Callable[[int], Result[int, Exception]] = lambda x: Ok(x * 10)
gn: Callable[[int], Result[int, Exception]] = lambda x: Ok(x + 10)
hn = pipeline(
fn,
gn,
)
assert hn(42) == Ok(430)
def test_pipeline_error():
error: Result[int, str] = Error("failed")
fn: Callable[[int], Result[int, str]] = lambda x: Ok(x * 10)
gn: Callable[[int], Result[int, str]] = lambda x: error
hn = pipeline(
fn,
gn,
)
assert hn(42) == error
class MyError(BaseModel):
message: str
class Model(BaseModel):
one: Result[int, MyError]
two: Result[str, MyError] = Error(MyError(message="error"))
three: Result[float, MyError] = Error(MyError(message="error"))
def test_parse_block_works():
obj = dict(one=dict(ok=42))
model = Model.model_validate(obj)
assert isinstance(model.one, Result)
assert model.one == Ok(42)
assert model.two == Error(MyError(message="error"))
assert model.three == Error(MyError(message="error"))
def test_ok_to_dict_works():
result = Ok(10)
obj = result.dict()
assert obj == dict(tag="ok", ok=10)
def test_error_to_dict_works():
error = MyError(message="got error")
result = Error(error)
obj = result.dict()
assert obj == dict(tag="error", error=dict(message="got error"))
def test_ok_from_from_dict_works():
obj = dict(ok=10)
adapter = TypeAdapter(Result[int, MyError])
result = adapter.validate_python(obj)
assert result
assert isinstance(result, Result)
match result:
case Result(tag="ok", ok=x):
assert x == 10
case _:
assert False
def test_error_from_dict_works():
obj = dict(error=dict(message="got error"))
adapter = TypeAdapter(Result[int, MyError])
result = adapter.validate_python(obj)
assert result
assert isinstance(result, Result)
match result:
case Result(tag="error", error=error):
assert error.message == "got error"
case _:
assert False
def test_model_to_json_works():
model = Model(one=Ok(10))
obj = model.model_dump_json()
assert (
obj
== '{"one":{"tag":"ok","ok":10},"two":{"tag":"error","error":{"message":"error"}},"three":{"tag":"error","error":{"message":"error"}}}'
)
def test_error_default_value():
xs: Result[int, int] = Error(0)
zs = xs.default_value(42)
assert zs == 42
def test_ok_default_value():
xs: Result[int, int] = Ok(42)
zs = xs.default_value(0)
assert zs == 42
def test_error_default_with():
xs: Result[int, int] = Error(0)
zs = xs.default_with(lambda x: x + 42)
assert zs == 42
def test_ok_default_with():
xs: Result[int, int] = Ok(42)
zs = xs.default_with(lambda x: 0)
assert zs == 42
def test_result_to_option_ok():
Ok(42).to_option()
res: Result[int, Any] = Ok(42)
xs = result.to_option(res)
assert xs.is_some()
def test_result_to_option_error():
xs: Option[Any] = result.to_option(Error("oops"))
assert xs.is_none()
def test_result_of_option_ok():
xs = result.of_option(Some(42), "oops")
assert xs == Ok(42)
def test_result_of_option_error():
xs = result.of_option(Nothing, "oops")
assert xs == Error("oops")
def test_result_of_option_with_ok():
xs = result.of_option_with(Some(42), error=lambda: exec('raise(Exception("Should not be called"))'))
assert xs == Ok(42)
def test_result_of_option_with_error():
xs = result.of_option_with(Nothing, error=lambda: "oops")
assert xs == Error("oops")
def test_result_swap_with_ok():
ok: Result[int, str] = Ok(1)
xs = result.swap(ok)
assert xs == Error(1)
def test_result_swap_with_error():
error: Result[str, int] = Error(1)
xs = result.swap(error)
assert xs == Ok(1)