-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtest_option.py
294 lines (252 loc) · 10.1 KB
/
test_option.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
"""Test the Option type."""
import typing as t
import pytest
from safetywrap import Option, Some, Nothing, Result, Ok, Err
def _sq(val: int) -> Option[int]:
"""Square the result and return an option."""
return Some(val ** 2)
def _nothing(_: int) -> Option[int]:
"""Just return nothing."""
return Nothing()
class TestOptionConstructors:
"""Test option constructors."""
@pytest.mark.parametrize(
"val, exp",
(
(5, Some(5)),
(None, Nothing()),
("", Some("")),
(False, Some(False)),
({}, Some({})),
([], Some([])),
),
)
def test_of(self, val: t.Any, exp: Option) -> None:
"""Option.of() returns an Option from an Optional."""
assert Option.of(val) == exp
@pytest.mark.parametrize(
"predicate, val, exp",
(
(lambda x: x is True, True, Some(True)),
(lambda x: x is True, False, Nothing()),
(lambda x: x > 0, 1, Some(1)),
(lambda x: x > 0, -2, Nothing()),
),
)
def test_some_if(
self, predicate: t.Callable, val: t.Any, exp: Option
) -> None:
"""Test constructing based on some predicate."""
assert Option.some_if(predicate, val) == exp
@pytest.mark.parametrize(
"predicate, val, exp",
(
(lambda x: x is True, True, Nothing()),
(lambda x: x is True, False, Some(False)),
(lambda x: x > 0, 1, Nothing()),
(lambda x: x > 0, -2, Some(-2)),
),
)
def test_nothing_if(
self, predicate: t.Callable, val: t.Any, exp: Option
) -> None:
"""Test constructing based on some predicate."""
assert Option.nothing_if(predicate, val) == exp
@pytest.mark.parametrize(
"options, exp",
(
([Some(1), Some(2), Some(3)], Some((1, 2, 3))),
([Some(1), Nothing(), Some(3)], Nothing()),
([Nothing()], Nothing()),
([Some(1)], Some((1,))),
((Some(1), Some(2), Some(3)), Some((1, 2, 3))),
),
)
def test_collect(self, options: t.Iterable[Option], exp: Option) -> None:
"""Test constructing from an iterable of options."""
assert Option.collect(options) == exp
class TestOption:
"""Test the option type."""
@pytest.mark.parametrize(
"left, right, exp",
(
(Some(2), Nothing(), Nothing()),
(Nothing(), Some(2), Nothing()),
(Some(1), Some(2), Some(2)),
(Nothing(), Nothing(), Nothing()),
),
)
def test_and(
self, left: Option[int], right: Option[int], exp: Option[int]
) -> None:
"""Returns Some() if both options are Some()."""
assert left.and_(right) == exp
@pytest.mark.parametrize(
"left, right, exp",
(
(Some(2), Nothing(), Some(2)),
(Nothing(), Some(2), Some(2)),
(Some(1), Some(2), Some(1)),
(Nothing(), Nothing(), Nothing()),
),
)
def test_or(
self, left: Option[int], right: Option[int], exp: Option[int]
) -> None:
"""Returns Some() if either or both is Some()."""
assert left.or_(right) == exp
@pytest.mark.parametrize(
"left, right, exp",
(
(Some(2), Nothing(), Some(2)),
(Nothing(), Some(2), Some(2)),
(Some(1), Some(2), Nothing()),
(Nothing(), Nothing(), Nothing()),
),
)
def test_xor(
self, left: Option[int], right: Option[int], exp: Option[int]
) -> None:
"""Returns Some() IFF only one option is Some()."""
assert left.xor(right) == exp
@pytest.mark.parametrize(
"start, first, second, exp",
(
(Some(2), _sq, _sq, Some(16)),
(Some(2), _sq, _nothing, Nothing()),
(Some(2), _nothing, _sq, Nothing()),
(Nothing(), _sq, _sq, Nothing()),
),
)
def test_and_then(
self,
start: Option[int],
first: t.Callable[[int], Option[int]],
second: t.Callable[[int], Option[int]],
exp: Option[int],
) -> None:
"""Chains option-generating functions if results are `Some`."""
assert start.and_then(first).and_then(second) == exp
@pytest.mark.parametrize(
"start, fn, exp",
(
(Some("one"), lambda: Some("one else"), Some("one")),
(Nothing(), lambda: Some("one else"), Some("one else")),
(Nothing(), lambda: Nothing(), Nothing()),
),
)
def test_or_else(
self,
start: Option[str],
fn: t.Callable[[], Option[str]],
exp: Option[str],
) -> None:
"""Chains option-generating functions if results are `None`."""
assert start.or_else(fn) == exp
@pytest.mark.parametrize("method", ("expect", "raise_if_nothing"))
@pytest.mark.parametrize("exc_cls", (None, IOError))
def test_expect_and_aliases_raising(
self, method: str, exc_cls: t.Type[Exception]
) -> None:
"""Can specify exception msg/cls if value is not Some()."""
exp_exc: t.Type[Exception] = exc_cls if exc_cls else RuntimeError
kwargs = {"exc_cls": exc_cls} if exc_cls else {}
msg = "not what I expected"
with pytest.raises(exp_exc) as exc_info:
getattr(Nothing(), method)(msg, **kwargs)
assert msg in str(exc_info.value)
@pytest.mark.parametrize("method", ("expect", "raise_if_nothing"))
def test_expect_and_aliases_not_raising(self, method: str) -> None:
"""Expecting on a Some() returns the value."""
assert getattr(Some("hello"), method)("not what I expected") == "hello"
def test_raise_if_err(self) -> None:
"""This method is deprecated."""
with pytest.deprecated_call():
assert Some("hello").raise_if_err("error") == "hello"
with pytest.deprecated_call():
with pytest.raises(RuntimeError):
Nothing().raise_if_err("error")
@pytest.mark.parametrize(
"start, exp",
((Nothing(), Nothing()), (Some(3), Nothing()), (Some(4), Some(4))),
)
def test_filter(self, start: Option[int], exp: Option[int]) -> None:
"""A satisfied predicate returns `Some()`, otherwise `None()`."""
def is_even(val: int) -> bool:
return val % 2 == 0
assert start.filter(is_even) == exp
@pytest.mark.parametrize("opt, exp", ((Nothing(), True), (Some(1), False)))
def test_is_nothing(self, opt: Option[int], exp: bool) -> None:
""""Nothings() are nothing, Some()s are not."""
assert opt.is_nothing() is exp
@pytest.mark.parametrize("opt, exp", ((Nothing(), False), (Some(1), True)))
def test_is_some(self, opt: Option[int], exp: bool) -> None:
""""Nothings() are nothing, Some()s are not."""
assert opt.is_some() is exp
@pytest.mark.parametrize("opt, exp", ((Nothing(), ()), (Some(5), (5,))))
def test_iter(self, opt: Option[int], exp: t.Tuple[int, ...]) -> None:
"""Iterating on a Some() yields the Some(); on a None() nothing."""
assert tuple(opt.iter()) == tuple(iter(opt)) == exp
@pytest.mark.parametrize(
"opt, exp", ((Some("hello"), Some(5)), (Nothing(), Nothing()))
)
def test_map(self, opt: Option[str], exp: Option[int]) -> None:
"""Maps fn() onto `Some()` to make a new option, or ignores None()."""
assert opt.map(len) == exp
@pytest.mark.parametrize("opt, exp", ((Some("hello"), 5), (Nothing(), -1)))
def test_map_or(self, opt: Option[str], exp: Option[int]) -> None:
"""Maps fn() onto `Some()` & return the value, or return a default."""
assert opt.map_or(-1, lambda s: len(s)) == exp
@pytest.mark.parametrize("opt, exp", ((Some("hello"), 5), (Nothing(), -1)))
def test_map_or_else(self, opt: Option[str], exp: Option[int]) -> None:
"""Maps fn() onto `Some()` & return the value, or return a default."""
assert opt.map_or_else(lambda: -1, lambda s: len(s)) == exp
@pytest.mark.parametrize(
"opt, exp", ((Some(2), Ok(2)), (Nothing(), Err("oh no")))
)
def test_ok_or(self, opt: Option[str], exp: Result[str, int]) -> None:
"""Map `Some(t)` to `Ok(t)`, or `Nothing()` to an `Err()`."""
assert opt.ok_or("oh no") == exp
@pytest.mark.parametrize(
"opt, exp", ((Some(2), Ok(2)), (Nothing(), Err("oh no")))
)
def test_ok_or_else(self, opt: Option[str], exp: Result[str, int]) -> None:
"""Map `Some(t)` to `Ok(t)`, or `Nothing()` to an `Err()`."""
assert opt.ok_or_else(lambda: "oh no") == exp
def test_unwrap_raising(self) -> None:
"""Unwraping a Nothing() raises an error."""
with pytest.raises(RuntimeError):
Nothing().unwrap()
def test_unwrap_success(self) -> None:
"""Unwrapping a Some() returns the wrapped value."""
assert Some("thing").unwrap() == "thing"
@pytest.mark.parametrize("opt, exp", ((Some(2), 2), (Nothing(), 42)))
def test_unwrap_or(self, opt: Option[int], exp: int) -> None:
"""Unwraps a `Some()` or returns a default."""
assert opt.unwrap_or(42) == exp
@pytest.mark.parametrize("opt, exp", ((Some(2), 2), (Nothing(), 42)))
def test_unwrap_or_else(self, opt: Option[int], exp: int) -> None:
"""Unwraps a `Some()` or returns a default."""
assert opt.unwrap_or_else(lambda: 42) == exp
@pytest.mark.parametrize(
"inst, other, eq",
(
(Some(1), Some(1), True),
(Some(1), Some(2), False),
(Some(1), Nothing(), False),
(Some(1), 1, False),
(Nothing(), Nothing(), True),
(Nothing(), Some(1), False),
(Nothing(), None, False),
),
)
def test_equality_inequality(
self, inst: t.Any, other: t.Any, eq: bool
) -> None:
"""Test equality and inequality of results."""
assert (inst == other) is eq
assert (inst != other) is not eq
def test_stringify(self) -> None:
"""Repr and str representations are equivalent."""
assert repr(Some(1)) == str(Some(1)) == "Some(1)"
assert repr(Nothing()) == str(Nothing()) == "Nothing()"