-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathtest_util.py
329 lines (256 loc) · 7.95 KB
/
test_util.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
import re
from array import array
from collections import OrderedDict
from collections import deque
from collections import namedtuple
from datetime import date
from datetime import datetime
from datetime import time
from datetime import timedelta
from datetime import tzinfo
from decimal import Decimal
from socket import _socket
from socket import socket
import py
import pytest
import six
from hunter.util import safe_repr
try:
from inspect import getattr_static
except ImportError:
from hunter.backports.inspect import getattr_static
MyTuple = namedtuple('MyTuple', 'a b')
class Dict(dict):
pass
class List(list):
pass
class Set(set):
pass
Stuff = namedtuple('Stuff', 'a b')
class Foobar:
__slots__ = ()
__repr__ = lambda _: 'Foo-bar'
class Bad1:
def __repr__(self):
raise Exception('Bad!')
def method(self):
pass
class String(str):
def __repr__(self):
raise Exception('Bad!')
__str__ = __repr__
class Int(int):
def __repr__(self):
raise Exception('Bad!')
__str__ = __repr__
class TzInfo(tzinfo):
def __repr__(self):
raise Exception('Bad!')
__str__ = __repr__
class Bad2:
def __repr__(self):
raise Exception('Bad!')
def method(self):
pass
def test_safe_repr():
s1 = _socket.socket()
s2 = socket()
data = {
'a': [set('b')],
('c',): deque(['d']),
'e': s1,
1: array('d', [1, 2]),
frozenset('f'): s2,
'g': Dict(
{
'a': List('123'),
'b': Set([Decimal('1.0')]),
'c': Stuff(1, 2),
'd': Exception(
1,
2,
{
'a': safe_repr,
'b': Foobar,
'c': Bad2(),
'ct': Bad2,
},
),
}
),
'od': OrderedDict({'a': 'b'}),
'nt': MyTuple(1, 2),
'bad1': Bad1().method,
'bad2': Bad2().method,
'regex': re.compile('123', 0),
'badregex': re.compile(String('123')),
'badregex2': re.compile(String('123'), Int(re.IGNORECASE)),
'date': date(Int(2000), Int(1), Int(2)),
'datetime': datetime(
Int(2000),
Int(1),
Int(2),
Int(3),
Int(4),
Int(5),
Int(600),
tzinfo=TzInfo(),
),
'time': time(Int(3), Int(4), Int(5), Int(600), tzinfo=TzInfo()),
'timedelta': timedelta(Int(1), Int(2), Int(3), Int(4), Int(5), Int(6), Int(7)),
}
print(re.compile(String('123'), Int(re.IGNORECASE)).match('123'))
print(safe_repr(data))
print(safe_repr([data]))
print(safe_repr([[data]]))
print(safe_repr([[[data]]]))
print(safe_repr([[[[data]]]]))
print(safe_repr([[[[[data]]]]]))
s1.close()
s2.close()
assert safe_repr(py.io).startswith('<py._vendored_packages.apipkg.ApiModule object at 0x')
def test_safe_repr_zoneinfo():
zoneinfo = pytest.importorskip("zoneinfo")
assert (
safe_repr(datetime(2000, 2, 2, tzinfo=zoneinfo.ZoneInfo('Europe/Bucharest')))
== f"datetime(2000, 2, 2, 0, 0, 0, 0, tzinfo={repr(zoneinfo.ZoneInfo('Europe/Bucharest'))}, fold=0)"
)
def test_safe_repr_decimal():
assert safe_repr(Decimal('1.23456')) == "Decimal('1.23456')"
def test_reliable_primitives():
# establish a baseline for primitives that cannot be messed with descriptors and metaclasses
side_effects = []
class MetaMeta(type):
@property
def __mro__(self):
side_effects.append('MetaMeta.__mro__')
return [Meta, type]
@property
def __class__(self):
side_effects.append('MetaMeta.__class__')
return MetaMeta
def __subclasscheck__(self, subclass):
side_effects.append('MetaMeta.__subclasscheck__')
return True
def __instancecheck__(self, instance):
side_effects.append('MetaMeta.__instancecheck__')
return True
class Meta(six.with_metaclass(MetaMeta, type)):
@property
def __mro__(self):
side_effects.append('Meta.__mro__')
return [Foobar, object]
@property
def __class__(self):
side_effects.append('Meta.__class__')
return Meta
def __subclasscheck__(self, subclass):
side_effects.append('Meta.__subclasscheck__')
return True
def __instancecheck__(self, instance):
side_effects.append('Meta.__instancecheck__')
return True
@property
def __dict__(self, _={}):
side_effects.append('Meta.__dict__')
return _
class Foobar(six.with_metaclass(Meta, object)):
@property
def __mro__(self):
side_effects.append('Foobar.__mro__')
return ['?']
@property
def __class__(self):
side_effects.append('Foobar.__class__')
return Foobar
def __subclasscheck__(self, subclass):
side_effects.append('Foobar.__subclasscheck__')
return True
def __instancecheck__(self, instance):
side_effects.append('Foobar.__instancecheck__')
return True
@property
def __dict__(self):
side_effects.append('Foobar.__dict__')
return {}
class SubFoobar(Foobar):
pass
class Plain:
pass
del side_effects[:]
foo = Foobar()
assert type(foo) is Foobar
assert type(Foobar) is Meta
assert type(foo) is Foobar
assert Foobar.__bases__
assert not side_effects
isinstance(type(foo), dict)
assert side_effects == ['Meta.__class__']
isinstance(foo, dict)
assert side_effects == ['Meta.__class__', 'Foobar.__class__']
isinstance(1, Foobar)
assert side_effects == [
'Meta.__class__',
'Foobar.__class__',
'Meta.__instancecheck__',
]
issubclass(type, Foobar)
assert side_effects == [
'Meta.__class__',
'Foobar.__class__',
'Meta.__instancecheck__',
'Meta.__subclasscheck__',
]
assert Foobar.__mro__
assert side_effects == [
'Meta.__class__',
'Foobar.__class__',
'Meta.__instancecheck__',
'Meta.__subclasscheck__',
'Meta.__mro__',
]
del side_effects[:]
assert Meta.__mro__
assert side_effects == ['MetaMeta.__mro__']
assert getattr_static(Plain, '__mro__') is type.__dict__['__mro__']
assert getattr_static(Foobar, '__mro__') is not type.__dict__['__mro__']
assert side_effects == ['MetaMeta.__mro__']
assert issubclass(SubFoobar, Foobar)
assert side_effects == ['MetaMeta.__mro__', 'Meta.__subclasscheck__']
subfoo = SubFoobar()
assert isinstance(SubFoobar, Foobar)
assert side_effects == [
'MetaMeta.__mro__',
'Meta.__subclasscheck__',
'Meta.__instancecheck__',
]
issubclass(type(SubFoobar()), Foobar)
assert side_effects == [
'MetaMeta.__mro__',
'Meta.__subclasscheck__',
'Meta.__instancecheck__',
'Meta.__subclasscheck__',
]
del side_effects[:]
isinstance(Foobar, dict)
isinstance(type(Foobar), dict)
isinstance(type(type(Foobar)), dict)
issubclass(Plain, Foobar)
issubclass(Plain, type(Foobar))
issubclass(Plain, type(type(Foobar)))
assert side_effects == [
'Meta.__class__',
'MetaMeta.__class__',
'Meta.__subclasscheck__',
'MetaMeta.__subclasscheck__',
]
del side_effects[:]
issubclass(getattr_static(SubFoobar(), '__class__'), Foobar)
assert side_effects[-1] == 'Meta.__subclasscheck__'
del side_effects[:]
getattr_static(type(SubFoobar()), '__instancecheck__')
getattr_static(type(SubFoobar()), '__subclasscheck__')
assert not side_effects
safe_repr(Foobar())
safe_repr(Foobar)
assert not side_effects