forked from reingart/exercism
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtest_utils.py
166 lines (138 loc) · 5.03 KB
/
test_utils.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
import errno
import inspect
import io
import os
ZEN = b"""Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
class MockException(Exception):
pass
class MockFile(io.BytesIO):
def __init__(self, *args, chunk=None, exception=None, **kwargs):
super(MockFile, self).__init__(*args, **kwargs)
self.__chunk = chunk
self.__exception = exception
def __exit__(self, exc_type, exc_val, exc_tb):
ret = super(MockFile, self).__exit__(exc_type, exc_val, exc_tb)
if exc_type is not None and "suppress" in exc_val.args[0]:
return True
return ret
def read(self, size=-1):
if self.__exception is not None:
raise self.__exception
if self.__chunk is None:
return super(MockFile, self).read(size)
if size is None:
return super(MockFile, self).read(self.__chunk)
if size < 0:
return super(MockFile, self).read(self.__chunk)
return super(MockFile, self).read(min(self.__chunk, size))
def write(self, data):
if self.__chunk is None:
return super(MockFile, self).write(data)
return super(MockFile, self).write(data[: self.__chunk])
class MockSock:
def __init__(self, *, chunk=None, exception=None):
self._recver = io.BytesIO(ZEN)
self._sender = io.BytesIO()
self.__closed = False
self.__chunk = chunk
self.__exception = exception
self.flags = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._recver.close()
self._sender.close()
self.__closed = True
if exc_type is not None and "suppress" in exc_val.args[0]:
return True
return False
def recv(self, bufsize, flags=0):
if self.__closed:
raise OSError(errno.EBADF, os.strerror(errno.EBADF))
if bufsize is None:
raise TypeError("'NoneType' object cannot be interpreted as an integer")
if not isinstance(flags, int):
raise TypeError(
"an integer is required (got type {})".format(type(flags).__name__)
)
self.flags = flags
if self.__exception is not None:
raise self.__exception
if self.__chunk is None:
return self._recver.read(bufsize)
else:
return self._recver.read(min(self.__chunk, bufsize))
def send(self, data, flags=0):
if self.__closed:
raise OSError(errno.EBADF, os.strerror(errno.EBADF))
if not isinstance(flags, int):
raise TypeError(
"an integer is required (got type {})".format(type(flags).__name__)
)
self.flags = flags
if self.__chunk is None:
return self._sender.write(data)
return self._sender.write(data[: self.__chunk])
class SuperMock:
"""Mock for super().__init__ calls only, as mock.MagicMock cannot."""
def __init__(self, *args, **kwargs):
if self.initialized:
self.init_called += 1
else:
self.initialized = True
def __call__(self, *args, **kwargs):
frame = inspect.currentframe()
if frame is None:
raise RuntimeError("Could not get current frame object")
stack = inspect.getouterframes(frame)
if any(frame[3] == "__init__" and "paasio" in frame[1] for frame in stack):
return self
else:
return self.mock_object
def __repr__(self):
return "<SuperMock at {} with mock object: {!r}>".format(
hex(id(self)), self.mock_object
)
mock_object = None
init_called = 0
initialized = False
class FileLike:
def __init__(self, fail_something=True):
self.is_open = False
self.was_open = False
self.did_something = False
self.fail_something = fail_something
def open(self):
self.was_open = False
self.is_open = True
def close(self):
self.is_open = False
self.was_open = True
def __enter__(self):
self.open()
return self
def __exit__(self, *args):
self.close()
def do_something(self):
self.did_something = True
if self.fail_something:
raise Exception("Failed while doing something")