1 | n/a | import abc |
---|
2 | n/a | import builtins |
---|
3 | n/a | import collections |
---|
4 | n/a | import copy |
---|
5 | n/a | from itertools import permutations |
---|
6 | n/a | import pickle |
---|
7 | n/a | from random import choice |
---|
8 | n/a | import sys |
---|
9 | n/a | from test import support |
---|
10 | n/a | import time |
---|
11 | n/a | import unittest |
---|
12 | n/a | import unittest.mock |
---|
13 | n/a | from weakref import proxy |
---|
14 | n/a | import contextlib |
---|
15 | n/a | try: |
---|
16 | n/a | import threading |
---|
17 | n/a | except ImportError: |
---|
18 | n/a | threading = None |
---|
19 | n/a | |
---|
20 | n/a | import functools |
---|
21 | n/a | |
---|
22 | n/a | py_functools = support.import_fresh_module('functools', blocked=['_functools']) |
---|
23 | n/a | c_functools = support.import_fresh_module('functools', fresh=['_functools']) |
---|
24 | n/a | |
---|
25 | n/a | decimal = support.import_fresh_module('decimal', fresh=['_decimal']) |
---|
26 | n/a | |
---|
27 | n/a | @contextlib.contextmanager |
---|
28 | n/a | def replaced_module(name, replacement): |
---|
29 | n/a | original_module = sys.modules[name] |
---|
30 | n/a | sys.modules[name] = replacement |
---|
31 | n/a | try: |
---|
32 | n/a | yield |
---|
33 | n/a | finally: |
---|
34 | n/a | sys.modules[name] = original_module |
---|
35 | n/a | |
---|
36 | n/a | def capture(*args, **kw): |
---|
37 | n/a | """capture all positional and keyword arguments""" |
---|
38 | n/a | return args, kw |
---|
39 | n/a | |
---|
40 | n/a | |
---|
41 | n/a | def signature(part): |
---|
42 | n/a | """ return the signature of a partial object """ |
---|
43 | n/a | return (part.func, part.args, part.keywords, part.__dict__) |
---|
44 | n/a | |
---|
45 | n/a | class MyTuple(tuple): |
---|
46 | n/a | pass |
---|
47 | n/a | |
---|
48 | n/a | class BadTuple(tuple): |
---|
49 | n/a | def __add__(self, other): |
---|
50 | n/a | return list(self) + list(other) |
---|
51 | n/a | |
---|
52 | n/a | class MyDict(dict): |
---|
53 | n/a | pass |
---|
54 | n/a | |
---|
55 | n/a | |
---|
56 | n/a | class TestPartial: |
---|
57 | n/a | |
---|
58 | n/a | def test_basic_examples(self): |
---|
59 | n/a | p = self.partial(capture, 1, 2, a=10, b=20) |
---|
60 | n/a | self.assertTrue(callable(p)) |
---|
61 | n/a | self.assertEqual(p(3, 4, b=30, c=40), |
---|
62 | n/a | ((1, 2, 3, 4), dict(a=10, b=30, c=40))) |
---|
63 | n/a | p = self.partial(map, lambda x: x*10) |
---|
64 | n/a | self.assertEqual(list(p([1,2,3,4])), [10, 20, 30, 40]) |
---|
65 | n/a | |
---|
66 | n/a | def test_attributes(self): |
---|
67 | n/a | p = self.partial(capture, 1, 2, a=10, b=20) |
---|
68 | n/a | # attributes should be readable |
---|
69 | n/a | self.assertEqual(p.func, capture) |
---|
70 | n/a | self.assertEqual(p.args, (1, 2)) |
---|
71 | n/a | self.assertEqual(p.keywords, dict(a=10, b=20)) |
---|
72 | n/a | |
---|
73 | n/a | def test_argument_checking(self): |
---|
74 | n/a | self.assertRaises(TypeError, self.partial) # need at least a func arg |
---|
75 | n/a | try: |
---|
76 | n/a | self.partial(2)() |
---|
77 | n/a | except TypeError: |
---|
78 | n/a | pass |
---|
79 | n/a | else: |
---|
80 | n/a | self.fail('First arg not checked for callability') |
---|
81 | n/a | |
---|
82 | n/a | def test_protection_of_callers_dict_argument(self): |
---|
83 | n/a | # a caller's dictionary should not be altered by partial |
---|
84 | n/a | def func(a=10, b=20): |
---|
85 | n/a | return a |
---|
86 | n/a | d = {'a':3} |
---|
87 | n/a | p = self.partial(func, a=5) |
---|
88 | n/a | self.assertEqual(p(**d), 3) |
---|
89 | n/a | self.assertEqual(d, {'a':3}) |
---|
90 | n/a | p(b=7) |
---|
91 | n/a | self.assertEqual(d, {'a':3}) |
---|
92 | n/a | |
---|
93 | n/a | def test_arg_combinations(self): |
---|
94 | n/a | # exercise special code paths for zero args in either partial |
---|
95 | n/a | # object or the caller |
---|
96 | n/a | p = self.partial(capture) |
---|
97 | n/a | self.assertEqual(p(), ((), {})) |
---|
98 | n/a | self.assertEqual(p(1,2), ((1,2), {})) |
---|
99 | n/a | p = self.partial(capture, 1, 2) |
---|
100 | n/a | self.assertEqual(p(), ((1,2), {})) |
---|
101 | n/a | self.assertEqual(p(3,4), ((1,2,3,4), {})) |
---|
102 | n/a | |
---|
103 | n/a | def test_kw_combinations(self): |
---|
104 | n/a | # exercise special code paths for no keyword args in |
---|
105 | n/a | # either the partial object or the caller |
---|
106 | n/a | p = self.partial(capture) |
---|
107 | n/a | self.assertEqual(p.keywords, {}) |
---|
108 | n/a | self.assertEqual(p(), ((), {})) |
---|
109 | n/a | self.assertEqual(p(a=1), ((), {'a':1})) |
---|
110 | n/a | p = self.partial(capture, a=1) |
---|
111 | n/a | self.assertEqual(p.keywords, {'a':1}) |
---|
112 | n/a | self.assertEqual(p(), ((), {'a':1})) |
---|
113 | n/a | self.assertEqual(p(b=2), ((), {'a':1, 'b':2})) |
---|
114 | n/a | # keyword args in the call override those in the partial object |
---|
115 | n/a | self.assertEqual(p(a=3, b=2), ((), {'a':3, 'b':2})) |
---|
116 | n/a | |
---|
117 | n/a | def test_positional(self): |
---|
118 | n/a | # make sure positional arguments are captured correctly |
---|
119 | n/a | for args in [(), (0,), (0,1), (0,1,2), (0,1,2,3)]: |
---|
120 | n/a | p = self.partial(capture, *args) |
---|
121 | n/a | expected = args + ('x',) |
---|
122 | n/a | got, empty = p('x') |
---|
123 | n/a | self.assertTrue(expected == got and empty == {}) |
---|
124 | n/a | |
---|
125 | n/a | def test_keyword(self): |
---|
126 | n/a | # make sure keyword arguments are captured correctly |
---|
127 | n/a | for a in ['a', 0, None, 3.5]: |
---|
128 | n/a | p = self.partial(capture, a=a) |
---|
129 | n/a | expected = {'a':a,'x':None} |
---|
130 | n/a | empty, got = p(x=None) |
---|
131 | n/a | self.assertTrue(expected == got and empty == ()) |
---|
132 | n/a | |
---|
133 | n/a | def test_no_side_effects(self): |
---|
134 | n/a | # make sure there are no side effects that affect subsequent calls |
---|
135 | n/a | p = self.partial(capture, 0, a=1) |
---|
136 | n/a | args1, kw1 = p(1, b=2) |
---|
137 | n/a | self.assertTrue(args1 == (0,1) and kw1 == {'a':1,'b':2}) |
---|
138 | n/a | args2, kw2 = p() |
---|
139 | n/a | self.assertTrue(args2 == (0,) and kw2 == {'a':1}) |
---|
140 | n/a | |
---|
141 | n/a | def test_error_propagation(self): |
---|
142 | n/a | def f(x, y): |
---|
143 | n/a | x / y |
---|
144 | n/a | self.assertRaises(ZeroDivisionError, self.partial(f, 1, 0)) |
---|
145 | n/a | self.assertRaises(ZeroDivisionError, self.partial(f, 1), 0) |
---|
146 | n/a | self.assertRaises(ZeroDivisionError, self.partial(f), 1, 0) |
---|
147 | n/a | self.assertRaises(ZeroDivisionError, self.partial(f, y=0), 1) |
---|
148 | n/a | |
---|
149 | n/a | def test_weakref(self): |
---|
150 | n/a | f = self.partial(int, base=16) |
---|
151 | n/a | p = proxy(f) |
---|
152 | n/a | self.assertEqual(f.func, p.func) |
---|
153 | n/a | f = None |
---|
154 | n/a | self.assertRaises(ReferenceError, getattr, p, 'func') |
---|
155 | n/a | |
---|
156 | n/a | def test_with_bound_and_unbound_methods(self): |
---|
157 | n/a | data = list(map(str, range(10))) |
---|
158 | n/a | join = self.partial(str.join, '') |
---|
159 | n/a | self.assertEqual(join(data), '0123456789') |
---|
160 | n/a | join = self.partial(''.join) |
---|
161 | n/a | self.assertEqual(join(data), '0123456789') |
---|
162 | n/a | |
---|
163 | n/a | def test_nested_optimization(self): |
---|
164 | n/a | partial = self.partial |
---|
165 | n/a | inner = partial(signature, 'asdf') |
---|
166 | n/a | nested = partial(inner, bar=True) |
---|
167 | n/a | flat = partial(signature, 'asdf', bar=True) |
---|
168 | n/a | self.assertEqual(signature(nested), signature(flat)) |
---|
169 | n/a | |
---|
170 | n/a | def test_nested_partial_with_attribute(self): |
---|
171 | n/a | # see issue 25137 |
---|
172 | n/a | partial = self.partial |
---|
173 | n/a | |
---|
174 | n/a | def foo(bar): |
---|
175 | n/a | return bar |
---|
176 | n/a | |
---|
177 | n/a | p = partial(foo, 'first') |
---|
178 | n/a | p2 = partial(p, 'second') |
---|
179 | n/a | p2.new_attr = 'spam' |
---|
180 | n/a | self.assertEqual(p2.new_attr, 'spam') |
---|
181 | n/a | |
---|
182 | n/a | def test_repr(self): |
---|
183 | n/a | args = (object(), object()) |
---|
184 | n/a | args_repr = ', '.join(repr(a) for a in args) |
---|
185 | n/a | kwargs = {'a': object(), 'b': object()} |
---|
186 | n/a | kwargs_reprs = ['a={a!r}, b={b!r}'.format_map(kwargs), |
---|
187 | n/a | 'b={b!r}, a={a!r}'.format_map(kwargs)] |
---|
188 | n/a | if self.partial in (c_functools.partial, py_functools.partial): |
---|
189 | n/a | name = 'functools.partial' |
---|
190 | n/a | else: |
---|
191 | n/a | name = self.partial.__name__ |
---|
192 | n/a | |
---|
193 | n/a | f = self.partial(capture) |
---|
194 | n/a | self.assertEqual(f'{name}({capture!r})', repr(f)) |
---|
195 | n/a | |
---|
196 | n/a | f = self.partial(capture, *args) |
---|
197 | n/a | self.assertEqual(f'{name}({capture!r}, {args_repr})', repr(f)) |
---|
198 | n/a | |
---|
199 | n/a | f = self.partial(capture, **kwargs) |
---|
200 | n/a | self.assertIn(repr(f), |
---|
201 | n/a | [f'{name}({capture!r}, {kwargs_repr})' |
---|
202 | n/a | for kwargs_repr in kwargs_reprs]) |
---|
203 | n/a | |
---|
204 | n/a | f = self.partial(capture, *args, **kwargs) |
---|
205 | n/a | self.assertIn(repr(f), |
---|
206 | n/a | [f'{name}({capture!r}, {args_repr}, {kwargs_repr})' |
---|
207 | n/a | for kwargs_repr in kwargs_reprs]) |
---|
208 | n/a | |
---|
209 | n/a | def test_recursive_repr(self): |
---|
210 | n/a | if self.partial in (c_functools.partial, py_functools.partial): |
---|
211 | n/a | name = 'functools.partial' |
---|
212 | n/a | else: |
---|
213 | n/a | name = self.partial.__name__ |
---|
214 | n/a | |
---|
215 | n/a | f = self.partial(capture) |
---|
216 | n/a | f.__setstate__((f, (), {}, {})) |
---|
217 | n/a | try: |
---|
218 | n/a | self.assertEqual(repr(f), '%s(...)' % (name,)) |
---|
219 | n/a | finally: |
---|
220 | n/a | f.__setstate__((capture, (), {}, {})) |
---|
221 | n/a | |
---|
222 | n/a | f = self.partial(capture) |
---|
223 | n/a | f.__setstate__((capture, (f,), {}, {})) |
---|
224 | n/a | try: |
---|
225 | n/a | self.assertEqual(repr(f), '%s(%r, ...)' % (name, capture,)) |
---|
226 | n/a | finally: |
---|
227 | n/a | f.__setstate__((capture, (), {}, {})) |
---|
228 | n/a | |
---|
229 | n/a | f = self.partial(capture) |
---|
230 | n/a | f.__setstate__((capture, (), {'a': f}, {})) |
---|
231 | n/a | try: |
---|
232 | n/a | self.assertEqual(repr(f), '%s(%r, a=...)' % (name, capture,)) |
---|
233 | n/a | finally: |
---|
234 | n/a | f.__setstate__((capture, (), {}, {})) |
---|
235 | n/a | |
---|
236 | n/a | def test_pickle(self): |
---|
237 | n/a | with self.AllowPickle(): |
---|
238 | n/a | f = self.partial(signature, ['asdf'], bar=[True]) |
---|
239 | n/a | f.attr = [] |
---|
240 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
241 | n/a | f_copy = pickle.loads(pickle.dumps(f, proto)) |
---|
242 | n/a | self.assertEqual(signature(f_copy), signature(f)) |
---|
243 | n/a | |
---|
244 | n/a | def test_copy(self): |
---|
245 | n/a | f = self.partial(signature, ['asdf'], bar=[True]) |
---|
246 | n/a | f.attr = [] |
---|
247 | n/a | f_copy = copy.copy(f) |
---|
248 | n/a | self.assertEqual(signature(f_copy), signature(f)) |
---|
249 | n/a | self.assertIs(f_copy.attr, f.attr) |
---|
250 | n/a | self.assertIs(f_copy.args, f.args) |
---|
251 | n/a | self.assertIs(f_copy.keywords, f.keywords) |
---|
252 | n/a | |
---|
253 | n/a | def test_deepcopy(self): |
---|
254 | n/a | f = self.partial(signature, ['asdf'], bar=[True]) |
---|
255 | n/a | f.attr = [] |
---|
256 | n/a | f_copy = copy.deepcopy(f) |
---|
257 | n/a | self.assertEqual(signature(f_copy), signature(f)) |
---|
258 | n/a | self.assertIsNot(f_copy.attr, f.attr) |
---|
259 | n/a | self.assertIsNot(f_copy.args, f.args) |
---|
260 | n/a | self.assertIsNot(f_copy.args[0], f.args[0]) |
---|
261 | n/a | self.assertIsNot(f_copy.keywords, f.keywords) |
---|
262 | n/a | self.assertIsNot(f_copy.keywords['bar'], f.keywords['bar']) |
---|
263 | n/a | |
---|
264 | n/a | def test_setstate(self): |
---|
265 | n/a | f = self.partial(signature) |
---|
266 | n/a | f.__setstate__((capture, (1,), dict(a=10), dict(attr=[]))) |
---|
267 | n/a | |
---|
268 | n/a | self.assertEqual(signature(f), |
---|
269 | n/a | (capture, (1,), dict(a=10), dict(attr=[]))) |
---|
270 | n/a | self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20})) |
---|
271 | n/a | |
---|
272 | n/a | f.__setstate__((capture, (1,), dict(a=10), None)) |
---|
273 | n/a | |
---|
274 | n/a | self.assertEqual(signature(f), (capture, (1,), dict(a=10), {})) |
---|
275 | n/a | self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20})) |
---|
276 | n/a | |
---|
277 | n/a | f.__setstate__((capture, (1,), None, None)) |
---|
278 | n/a | #self.assertEqual(signature(f), (capture, (1,), {}, {})) |
---|
279 | n/a | self.assertEqual(f(2, b=20), ((1, 2), {'b': 20})) |
---|
280 | n/a | self.assertEqual(f(2), ((1, 2), {})) |
---|
281 | n/a | self.assertEqual(f(), ((1,), {})) |
---|
282 | n/a | |
---|
283 | n/a | f.__setstate__((capture, (), {}, None)) |
---|
284 | n/a | self.assertEqual(signature(f), (capture, (), {}, {})) |
---|
285 | n/a | self.assertEqual(f(2, b=20), ((2,), {'b': 20})) |
---|
286 | n/a | self.assertEqual(f(2), ((2,), {})) |
---|
287 | n/a | self.assertEqual(f(), ((), {})) |
---|
288 | n/a | |
---|
289 | n/a | def test_setstate_errors(self): |
---|
290 | n/a | f = self.partial(signature) |
---|
291 | n/a | self.assertRaises(TypeError, f.__setstate__, (capture, (), {})) |
---|
292 | n/a | self.assertRaises(TypeError, f.__setstate__, (capture, (), {}, {}, None)) |
---|
293 | n/a | self.assertRaises(TypeError, f.__setstate__, [capture, (), {}, None]) |
---|
294 | n/a | self.assertRaises(TypeError, f.__setstate__, (None, (), {}, None)) |
---|
295 | n/a | self.assertRaises(TypeError, f.__setstate__, (capture, None, {}, None)) |
---|
296 | n/a | self.assertRaises(TypeError, f.__setstate__, (capture, [], {}, None)) |
---|
297 | n/a | self.assertRaises(TypeError, f.__setstate__, (capture, (), [], None)) |
---|
298 | n/a | |
---|
299 | n/a | def test_setstate_subclasses(self): |
---|
300 | n/a | f = self.partial(signature) |
---|
301 | n/a | f.__setstate__((capture, MyTuple((1,)), MyDict(a=10), None)) |
---|
302 | n/a | s = signature(f) |
---|
303 | n/a | self.assertEqual(s, (capture, (1,), dict(a=10), {})) |
---|
304 | n/a | self.assertIs(type(s[1]), tuple) |
---|
305 | n/a | self.assertIs(type(s[2]), dict) |
---|
306 | n/a | r = f() |
---|
307 | n/a | self.assertEqual(r, ((1,), {'a': 10})) |
---|
308 | n/a | self.assertIs(type(r[0]), tuple) |
---|
309 | n/a | self.assertIs(type(r[1]), dict) |
---|
310 | n/a | |
---|
311 | n/a | f.__setstate__((capture, BadTuple((1,)), {}, None)) |
---|
312 | n/a | s = signature(f) |
---|
313 | n/a | self.assertEqual(s, (capture, (1,), {}, {})) |
---|
314 | n/a | self.assertIs(type(s[1]), tuple) |
---|
315 | n/a | r = f(2) |
---|
316 | n/a | self.assertEqual(r, ((1, 2), {})) |
---|
317 | n/a | self.assertIs(type(r[0]), tuple) |
---|
318 | n/a | |
---|
319 | n/a | def test_recursive_pickle(self): |
---|
320 | n/a | with self.AllowPickle(): |
---|
321 | n/a | f = self.partial(capture) |
---|
322 | n/a | f.__setstate__((f, (), {}, {})) |
---|
323 | n/a | try: |
---|
324 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
325 | n/a | with self.assertRaises(RecursionError): |
---|
326 | n/a | pickle.dumps(f, proto) |
---|
327 | n/a | finally: |
---|
328 | n/a | f.__setstate__((capture, (), {}, {})) |
---|
329 | n/a | |
---|
330 | n/a | f = self.partial(capture) |
---|
331 | n/a | f.__setstate__((capture, (f,), {}, {})) |
---|
332 | n/a | try: |
---|
333 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
334 | n/a | f_copy = pickle.loads(pickle.dumps(f, proto)) |
---|
335 | n/a | try: |
---|
336 | n/a | self.assertIs(f_copy.args[0], f_copy) |
---|
337 | n/a | finally: |
---|
338 | n/a | f_copy.__setstate__((capture, (), {}, {})) |
---|
339 | n/a | finally: |
---|
340 | n/a | f.__setstate__((capture, (), {}, {})) |
---|
341 | n/a | |
---|
342 | n/a | f = self.partial(capture) |
---|
343 | n/a | f.__setstate__((capture, (), {'a': f}, {})) |
---|
344 | n/a | try: |
---|
345 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
346 | n/a | f_copy = pickle.loads(pickle.dumps(f, proto)) |
---|
347 | n/a | try: |
---|
348 | n/a | self.assertIs(f_copy.keywords['a'], f_copy) |
---|
349 | n/a | finally: |
---|
350 | n/a | f_copy.__setstate__((capture, (), {}, {})) |
---|
351 | n/a | finally: |
---|
352 | n/a | f.__setstate__((capture, (), {}, {})) |
---|
353 | n/a | |
---|
354 | n/a | # Issue 6083: Reference counting bug |
---|
355 | n/a | def test_setstate_refcount(self): |
---|
356 | n/a | class BadSequence: |
---|
357 | n/a | def __len__(self): |
---|
358 | n/a | return 4 |
---|
359 | n/a | def __getitem__(self, key): |
---|
360 | n/a | if key == 0: |
---|
361 | n/a | return max |
---|
362 | n/a | elif key == 1: |
---|
363 | n/a | return tuple(range(1000000)) |
---|
364 | n/a | elif key in (2, 3): |
---|
365 | n/a | return {} |
---|
366 | n/a | raise IndexError |
---|
367 | n/a | |
---|
368 | n/a | f = self.partial(object) |
---|
369 | n/a | self.assertRaises(TypeError, f.__setstate__, BadSequence()) |
---|
370 | n/a | |
---|
371 | n/a | @unittest.skipUnless(c_functools, 'requires the C _functools module') |
---|
372 | n/a | class TestPartialC(TestPartial, unittest.TestCase): |
---|
373 | n/a | if c_functools: |
---|
374 | n/a | partial = c_functools.partial |
---|
375 | n/a | |
---|
376 | n/a | class AllowPickle: |
---|
377 | n/a | def __enter__(self): |
---|
378 | n/a | return self |
---|
379 | n/a | def __exit__(self, type, value, tb): |
---|
380 | n/a | return False |
---|
381 | n/a | |
---|
382 | n/a | def test_attributes_unwritable(self): |
---|
383 | n/a | # attributes should not be writable |
---|
384 | n/a | p = self.partial(capture, 1, 2, a=10, b=20) |
---|
385 | n/a | self.assertRaises(AttributeError, setattr, p, 'func', map) |
---|
386 | n/a | self.assertRaises(AttributeError, setattr, p, 'args', (1, 2)) |
---|
387 | n/a | self.assertRaises(AttributeError, setattr, p, 'keywords', dict(a=1, b=2)) |
---|
388 | n/a | |
---|
389 | n/a | p = self.partial(hex) |
---|
390 | n/a | try: |
---|
391 | n/a | del p.__dict__ |
---|
392 | n/a | except TypeError: |
---|
393 | n/a | pass |
---|
394 | n/a | else: |
---|
395 | n/a | self.fail('partial object allowed __dict__ to be deleted') |
---|
396 | n/a | |
---|
397 | n/a | class TestPartialPy(TestPartial, unittest.TestCase): |
---|
398 | n/a | partial = py_functools.partial |
---|
399 | n/a | |
---|
400 | n/a | class AllowPickle: |
---|
401 | n/a | def __init__(self): |
---|
402 | n/a | self._cm = replaced_module("functools", py_functools) |
---|
403 | n/a | def __enter__(self): |
---|
404 | n/a | return self._cm.__enter__() |
---|
405 | n/a | def __exit__(self, type, value, tb): |
---|
406 | n/a | return self._cm.__exit__(type, value, tb) |
---|
407 | n/a | |
---|
408 | n/a | if c_functools: |
---|
409 | n/a | class CPartialSubclass(c_functools.partial): |
---|
410 | n/a | pass |
---|
411 | n/a | |
---|
412 | n/a | class PyPartialSubclass(py_functools.partial): |
---|
413 | n/a | pass |
---|
414 | n/a | |
---|
415 | n/a | @unittest.skipUnless(c_functools, 'requires the C _functools module') |
---|
416 | n/a | class TestPartialCSubclass(TestPartialC): |
---|
417 | n/a | if c_functools: |
---|
418 | n/a | partial = CPartialSubclass |
---|
419 | n/a | |
---|
420 | n/a | # partial subclasses are not optimized for nested calls |
---|
421 | n/a | test_nested_optimization = None |
---|
422 | n/a | |
---|
423 | n/a | class TestPartialPySubclass(TestPartialPy): |
---|
424 | n/a | partial = PyPartialSubclass |
---|
425 | n/a | |
---|
426 | n/a | class TestPartialMethod(unittest.TestCase): |
---|
427 | n/a | |
---|
428 | n/a | class A(object): |
---|
429 | n/a | nothing = functools.partialmethod(capture) |
---|
430 | n/a | positional = functools.partialmethod(capture, 1) |
---|
431 | n/a | keywords = functools.partialmethod(capture, a=2) |
---|
432 | n/a | both = functools.partialmethod(capture, 3, b=4) |
---|
433 | n/a | |
---|
434 | n/a | nested = functools.partialmethod(positional, 5) |
---|
435 | n/a | |
---|
436 | n/a | over_partial = functools.partialmethod(functools.partial(capture, c=6), 7) |
---|
437 | n/a | |
---|
438 | n/a | static = functools.partialmethod(staticmethod(capture), 8) |
---|
439 | n/a | cls = functools.partialmethod(classmethod(capture), d=9) |
---|
440 | n/a | |
---|
441 | n/a | a = A() |
---|
442 | n/a | |
---|
443 | n/a | def test_arg_combinations(self): |
---|
444 | n/a | self.assertEqual(self.a.nothing(), ((self.a,), {})) |
---|
445 | n/a | self.assertEqual(self.a.nothing(5), ((self.a, 5), {})) |
---|
446 | n/a | self.assertEqual(self.a.nothing(c=6), ((self.a,), {'c': 6})) |
---|
447 | n/a | self.assertEqual(self.a.nothing(5, c=6), ((self.a, 5), {'c': 6})) |
---|
448 | n/a | |
---|
449 | n/a | self.assertEqual(self.a.positional(), ((self.a, 1), {})) |
---|
450 | n/a | self.assertEqual(self.a.positional(5), ((self.a, 1, 5), {})) |
---|
451 | n/a | self.assertEqual(self.a.positional(c=6), ((self.a, 1), {'c': 6})) |
---|
452 | n/a | self.assertEqual(self.a.positional(5, c=6), ((self.a, 1, 5), {'c': 6})) |
---|
453 | n/a | |
---|
454 | n/a | self.assertEqual(self.a.keywords(), ((self.a,), {'a': 2})) |
---|
455 | n/a | self.assertEqual(self.a.keywords(5), ((self.a, 5), {'a': 2})) |
---|
456 | n/a | self.assertEqual(self.a.keywords(c=6), ((self.a,), {'a': 2, 'c': 6})) |
---|
457 | n/a | self.assertEqual(self.a.keywords(5, c=6), ((self.a, 5), {'a': 2, 'c': 6})) |
---|
458 | n/a | |
---|
459 | n/a | self.assertEqual(self.a.both(), ((self.a, 3), {'b': 4})) |
---|
460 | n/a | self.assertEqual(self.a.both(5), ((self.a, 3, 5), {'b': 4})) |
---|
461 | n/a | self.assertEqual(self.a.both(c=6), ((self.a, 3), {'b': 4, 'c': 6})) |
---|
462 | n/a | self.assertEqual(self.a.both(5, c=6), ((self.a, 3, 5), {'b': 4, 'c': 6})) |
---|
463 | n/a | |
---|
464 | n/a | self.assertEqual(self.A.both(self.a, 5, c=6), ((self.a, 3, 5), {'b': 4, 'c': 6})) |
---|
465 | n/a | |
---|
466 | n/a | def test_nested(self): |
---|
467 | n/a | self.assertEqual(self.a.nested(), ((self.a, 1, 5), {})) |
---|
468 | n/a | self.assertEqual(self.a.nested(6), ((self.a, 1, 5, 6), {})) |
---|
469 | n/a | self.assertEqual(self.a.nested(d=7), ((self.a, 1, 5), {'d': 7})) |
---|
470 | n/a | self.assertEqual(self.a.nested(6, d=7), ((self.a, 1, 5, 6), {'d': 7})) |
---|
471 | n/a | |
---|
472 | n/a | self.assertEqual(self.A.nested(self.a, 6, d=7), ((self.a, 1, 5, 6), {'d': 7})) |
---|
473 | n/a | |
---|
474 | n/a | def test_over_partial(self): |
---|
475 | n/a | self.assertEqual(self.a.over_partial(), ((self.a, 7), {'c': 6})) |
---|
476 | n/a | self.assertEqual(self.a.over_partial(5), ((self.a, 7, 5), {'c': 6})) |
---|
477 | n/a | self.assertEqual(self.a.over_partial(d=8), ((self.a, 7), {'c': 6, 'd': 8})) |
---|
478 | n/a | self.assertEqual(self.a.over_partial(5, d=8), ((self.a, 7, 5), {'c': 6, 'd': 8})) |
---|
479 | n/a | |
---|
480 | n/a | self.assertEqual(self.A.over_partial(self.a, 5, d=8), ((self.a, 7, 5), {'c': 6, 'd': 8})) |
---|
481 | n/a | |
---|
482 | n/a | def test_bound_method_introspection(self): |
---|
483 | n/a | obj = self.a |
---|
484 | n/a | self.assertIs(obj.both.__self__, obj) |
---|
485 | n/a | self.assertIs(obj.nested.__self__, obj) |
---|
486 | n/a | self.assertIs(obj.over_partial.__self__, obj) |
---|
487 | n/a | self.assertIs(obj.cls.__self__, self.A) |
---|
488 | n/a | self.assertIs(self.A.cls.__self__, self.A) |
---|
489 | n/a | |
---|
490 | n/a | def test_unbound_method_retrieval(self): |
---|
491 | n/a | obj = self.A |
---|
492 | n/a | self.assertFalse(hasattr(obj.both, "__self__")) |
---|
493 | n/a | self.assertFalse(hasattr(obj.nested, "__self__")) |
---|
494 | n/a | self.assertFalse(hasattr(obj.over_partial, "__self__")) |
---|
495 | n/a | self.assertFalse(hasattr(obj.static, "__self__")) |
---|
496 | n/a | self.assertFalse(hasattr(self.a.static, "__self__")) |
---|
497 | n/a | |
---|
498 | n/a | def test_descriptors(self): |
---|
499 | n/a | for obj in [self.A, self.a]: |
---|
500 | n/a | with self.subTest(obj=obj): |
---|
501 | n/a | self.assertEqual(obj.static(), ((8,), {})) |
---|
502 | n/a | self.assertEqual(obj.static(5), ((8, 5), {})) |
---|
503 | n/a | self.assertEqual(obj.static(d=8), ((8,), {'d': 8})) |
---|
504 | n/a | self.assertEqual(obj.static(5, d=8), ((8, 5), {'d': 8})) |
---|
505 | n/a | |
---|
506 | n/a | self.assertEqual(obj.cls(), ((self.A,), {'d': 9})) |
---|
507 | n/a | self.assertEqual(obj.cls(5), ((self.A, 5), {'d': 9})) |
---|
508 | n/a | self.assertEqual(obj.cls(c=8), ((self.A,), {'c': 8, 'd': 9})) |
---|
509 | n/a | self.assertEqual(obj.cls(5, c=8), ((self.A, 5), {'c': 8, 'd': 9})) |
---|
510 | n/a | |
---|
511 | n/a | def test_overriding_keywords(self): |
---|
512 | n/a | self.assertEqual(self.a.keywords(a=3), ((self.a,), {'a': 3})) |
---|
513 | n/a | self.assertEqual(self.A.keywords(self.a, a=3), ((self.a,), {'a': 3})) |
---|
514 | n/a | |
---|
515 | n/a | def test_invalid_args(self): |
---|
516 | n/a | with self.assertRaises(TypeError): |
---|
517 | n/a | class B(object): |
---|
518 | n/a | method = functools.partialmethod(None, 1) |
---|
519 | n/a | |
---|
520 | n/a | def test_repr(self): |
---|
521 | n/a | self.assertEqual(repr(vars(self.A)['both']), |
---|
522 | n/a | 'functools.partialmethod({}, 3, b=4)'.format(capture)) |
---|
523 | n/a | |
---|
524 | n/a | def test_abstract(self): |
---|
525 | n/a | class Abstract(abc.ABCMeta): |
---|
526 | n/a | |
---|
527 | n/a | @abc.abstractmethod |
---|
528 | n/a | def add(self, x, y): |
---|
529 | n/a | pass |
---|
530 | n/a | |
---|
531 | n/a | add5 = functools.partialmethod(add, 5) |
---|
532 | n/a | |
---|
533 | n/a | self.assertTrue(Abstract.add.__isabstractmethod__) |
---|
534 | n/a | self.assertTrue(Abstract.add5.__isabstractmethod__) |
---|
535 | n/a | |
---|
536 | n/a | for func in [self.A.static, self.A.cls, self.A.over_partial, self.A.nested, self.A.both]: |
---|
537 | n/a | self.assertFalse(getattr(func, '__isabstractmethod__', False)) |
---|
538 | n/a | |
---|
539 | n/a | |
---|
540 | n/a | class TestUpdateWrapper(unittest.TestCase): |
---|
541 | n/a | |
---|
542 | n/a | def check_wrapper(self, wrapper, wrapped, |
---|
543 | n/a | assigned=functools.WRAPPER_ASSIGNMENTS, |
---|
544 | n/a | updated=functools.WRAPPER_UPDATES): |
---|
545 | n/a | # Check attributes were assigned |
---|
546 | n/a | for name in assigned: |
---|
547 | n/a | self.assertIs(getattr(wrapper, name), getattr(wrapped, name)) |
---|
548 | n/a | # Check attributes were updated |
---|
549 | n/a | for name in updated: |
---|
550 | n/a | wrapper_attr = getattr(wrapper, name) |
---|
551 | n/a | wrapped_attr = getattr(wrapped, name) |
---|
552 | n/a | for key in wrapped_attr: |
---|
553 | n/a | if name == "__dict__" and key == "__wrapped__": |
---|
554 | n/a | # __wrapped__ is overwritten by the update code |
---|
555 | n/a | continue |
---|
556 | n/a | self.assertIs(wrapped_attr[key], wrapper_attr[key]) |
---|
557 | n/a | # Check __wrapped__ |
---|
558 | n/a | self.assertIs(wrapper.__wrapped__, wrapped) |
---|
559 | n/a | |
---|
560 | n/a | |
---|
561 | n/a | def _default_update(self): |
---|
562 | n/a | def f(a:'This is a new annotation'): |
---|
563 | n/a | """This is a test""" |
---|
564 | n/a | pass |
---|
565 | n/a | f.attr = 'This is also a test' |
---|
566 | n/a | f.__wrapped__ = "This is a bald faced lie" |
---|
567 | n/a | def wrapper(b:'This is the prior annotation'): |
---|
568 | n/a | pass |
---|
569 | n/a | functools.update_wrapper(wrapper, f) |
---|
570 | n/a | return wrapper, f |
---|
571 | n/a | |
---|
572 | n/a | def test_default_update(self): |
---|
573 | n/a | wrapper, f = self._default_update() |
---|
574 | n/a | self.check_wrapper(wrapper, f) |
---|
575 | n/a | self.assertIs(wrapper.__wrapped__, f) |
---|
576 | n/a | self.assertEqual(wrapper.__name__, 'f') |
---|
577 | n/a | self.assertEqual(wrapper.__qualname__, f.__qualname__) |
---|
578 | n/a | self.assertEqual(wrapper.attr, 'This is also a test') |
---|
579 | n/a | self.assertEqual(wrapper.__annotations__['a'], 'This is a new annotation') |
---|
580 | n/a | self.assertNotIn('b', wrapper.__annotations__) |
---|
581 | n/a | |
---|
582 | n/a | @unittest.skipIf(sys.flags.optimize >= 2, |
---|
583 | n/a | "Docstrings are omitted with -O2 and above") |
---|
584 | n/a | def test_default_update_doc(self): |
---|
585 | n/a | wrapper, f = self._default_update() |
---|
586 | n/a | self.assertEqual(wrapper.__doc__, 'This is a test') |
---|
587 | n/a | |
---|
588 | n/a | def test_no_update(self): |
---|
589 | n/a | def f(): |
---|
590 | n/a | """This is a test""" |
---|
591 | n/a | pass |
---|
592 | n/a | f.attr = 'This is also a test' |
---|
593 | n/a | def wrapper(): |
---|
594 | n/a | pass |
---|
595 | n/a | functools.update_wrapper(wrapper, f, (), ()) |
---|
596 | n/a | self.check_wrapper(wrapper, f, (), ()) |
---|
597 | n/a | self.assertEqual(wrapper.__name__, 'wrapper') |
---|
598 | n/a | self.assertNotEqual(wrapper.__qualname__, f.__qualname__) |
---|
599 | n/a | self.assertEqual(wrapper.__doc__, None) |
---|
600 | n/a | self.assertEqual(wrapper.__annotations__, {}) |
---|
601 | n/a | self.assertFalse(hasattr(wrapper, 'attr')) |
---|
602 | n/a | |
---|
603 | n/a | def test_selective_update(self): |
---|
604 | n/a | def f(): |
---|
605 | n/a | pass |
---|
606 | n/a | f.attr = 'This is a different test' |
---|
607 | n/a | f.dict_attr = dict(a=1, b=2, c=3) |
---|
608 | n/a | def wrapper(): |
---|
609 | n/a | pass |
---|
610 | n/a | wrapper.dict_attr = {} |
---|
611 | n/a | assign = ('attr',) |
---|
612 | n/a | update = ('dict_attr',) |
---|
613 | n/a | functools.update_wrapper(wrapper, f, assign, update) |
---|
614 | n/a | self.check_wrapper(wrapper, f, assign, update) |
---|
615 | n/a | self.assertEqual(wrapper.__name__, 'wrapper') |
---|
616 | n/a | self.assertNotEqual(wrapper.__qualname__, f.__qualname__) |
---|
617 | n/a | self.assertEqual(wrapper.__doc__, None) |
---|
618 | n/a | self.assertEqual(wrapper.attr, 'This is a different test') |
---|
619 | n/a | self.assertEqual(wrapper.dict_attr, f.dict_attr) |
---|
620 | n/a | |
---|
621 | n/a | def test_missing_attributes(self): |
---|
622 | n/a | def f(): |
---|
623 | n/a | pass |
---|
624 | n/a | def wrapper(): |
---|
625 | n/a | pass |
---|
626 | n/a | wrapper.dict_attr = {} |
---|
627 | n/a | assign = ('attr',) |
---|
628 | n/a | update = ('dict_attr',) |
---|
629 | n/a | # Missing attributes on wrapped object are ignored |
---|
630 | n/a | functools.update_wrapper(wrapper, f, assign, update) |
---|
631 | n/a | self.assertNotIn('attr', wrapper.__dict__) |
---|
632 | n/a | self.assertEqual(wrapper.dict_attr, {}) |
---|
633 | n/a | # Wrapper must have expected attributes for updating |
---|
634 | n/a | del wrapper.dict_attr |
---|
635 | n/a | with self.assertRaises(AttributeError): |
---|
636 | n/a | functools.update_wrapper(wrapper, f, assign, update) |
---|
637 | n/a | wrapper.dict_attr = 1 |
---|
638 | n/a | with self.assertRaises(AttributeError): |
---|
639 | n/a | functools.update_wrapper(wrapper, f, assign, update) |
---|
640 | n/a | |
---|
641 | n/a | @support.requires_docstrings |
---|
642 | n/a | @unittest.skipIf(sys.flags.optimize >= 2, |
---|
643 | n/a | "Docstrings are omitted with -O2 and above") |
---|
644 | n/a | def test_builtin_update(self): |
---|
645 | n/a | # Test for bug #1576241 |
---|
646 | n/a | def wrapper(): |
---|
647 | n/a | pass |
---|
648 | n/a | functools.update_wrapper(wrapper, max) |
---|
649 | n/a | self.assertEqual(wrapper.__name__, 'max') |
---|
650 | n/a | self.assertTrue(wrapper.__doc__.startswith('max(')) |
---|
651 | n/a | self.assertEqual(wrapper.__annotations__, {}) |
---|
652 | n/a | |
---|
653 | n/a | |
---|
654 | n/a | class TestWraps(TestUpdateWrapper): |
---|
655 | n/a | |
---|
656 | n/a | def _default_update(self): |
---|
657 | n/a | def f(): |
---|
658 | n/a | """This is a test""" |
---|
659 | n/a | pass |
---|
660 | n/a | f.attr = 'This is also a test' |
---|
661 | n/a | f.__wrapped__ = "This is still a bald faced lie" |
---|
662 | n/a | @functools.wraps(f) |
---|
663 | n/a | def wrapper(): |
---|
664 | n/a | pass |
---|
665 | n/a | return wrapper, f |
---|
666 | n/a | |
---|
667 | n/a | def test_default_update(self): |
---|
668 | n/a | wrapper, f = self._default_update() |
---|
669 | n/a | self.check_wrapper(wrapper, f) |
---|
670 | n/a | self.assertEqual(wrapper.__name__, 'f') |
---|
671 | n/a | self.assertEqual(wrapper.__qualname__, f.__qualname__) |
---|
672 | n/a | self.assertEqual(wrapper.attr, 'This is also a test') |
---|
673 | n/a | |
---|
674 | n/a | @unittest.skipIf(sys.flags.optimize >= 2, |
---|
675 | n/a | "Docstrings are omitted with -O2 and above") |
---|
676 | n/a | def test_default_update_doc(self): |
---|
677 | n/a | wrapper, _ = self._default_update() |
---|
678 | n/a | self.assertEqual(wrapper.__doc__, 'This is a test') |
---|
679 | n/a | |
---|
680 | n/a | def test_no_update(self): |
---|
681 | n/a | def f(): |
---|
682 | n/a | """This is a test""" |
---|
683 | n/a | pass |
---|
684 | n/a | f.attr = 'This is also a test' |
---|
685 | n/a | @functools.wraps(f, (), ()) |
---|
686 | n/a | def wrapper(): |
---|
687 | n/a | pass |
---|
688 | n/a | self.check_wrapper(wrapper, f, (), ()) |
---|
689 | n/a | self.assertEqual(wrapper.__name__, 'wrapper') |
---|
690 | n/a | self.assertNotEqual(wrapper.__qualname__, f.__qualname__) |
---|
691 | n/a | self.assertEqual(wrapper.__doc__, None) |
---|
692 | n/a | self.assertFalse(hasattr(wrapper, 'attr')) |
---|
693 | n/a | |
---|
694 | n/a | def test_selective_update(self): |
---|
695 | n/a | def f(): |
---|
696 | n/a | pass |
---|
697 | n/a | f.attr = 'This is a different test' |
---|
698 | n/a | f.dict_attr = dict(a=1, b=2, c=3) |
---|
699 | n/a | def add_dict_attr(f): |
---|
700 | n/a | f.dict_attr = {} |
---|
701 | n/a | return f |
---|
702 | n/a | assign = ('attr',) |
---|
703 | n/a | update = ('dict_attr',) |
---|
704 | n/a | @functools.wraps(f, assign, update) |
---|
705 | n/a | @add_dict_attr |
---|
706 | n/a | def wrapper(): |
---|
707 | n/a | pass |
---|
708 | n/a | self.check_wrapper(wrapper, f, assign, update) |
---|
709 | n/a | self.assertEqual(wrapper.__name__, 'wrapper') |
---|
710 | n/a | self.assertNotEqual(wrapper.__qualname__, f.__qualname__) |
---|
711 | n/a | self.assertEqual(wrapper.__doc__, None) |
---|
712 | n/a | self.assertEqual(wrapper.attr, 'This is a different test') |
---|
713 | n/a | self.assertEqual(wrapper.dict_attr, f.dict_attr) |
---|
714 | n/a | |
---|
715 | n/a | @unittest.skipUnless(c_functools, 'requires the C _functools module') |
---|
716 | n/a | class TestReduce(unittest.TestCase): |
---|
717 | n/a | if c_functools: |
---|
718 | n/a | func = c_functools.reduce |
---|
719 | n/a | |
---|
720 | n/a | def test_reduce(self): |
---|
721 | n/a | class Squares: |
---|
722 | n/a | def __init__(self, max): |
---|
723 | n/a | self.max = max |
---|
724 | n/a | self.sofar = [] |
---|
725 | n/a | |
---|
726 | n/a | def __len__(self): |
---|
727 | n/a | return len(self.sofar) |
---|
728 | n/a | |
---|
729 | n/a | def __getitem__(self, i): |
---|
730 | n/a | if not 0 <= i < self.max: raise IndexError |
---|
731 | n/a | n = len(self.sofar) |
---|
732 | n/a | while n <= i: |
---|
733 | n/a | self.sofar.append(n*n) |
---|
734 | n/a | n += 1 |
---|
735 | n/a | return self.sofar[i] |
---|
736 | n/a | def add(x, y): |
---|
737 | n/a | return x + y |
---|
738 | n/a | self.assertEqual(self.func(add, ['a', 'b', 'c'], ''), 'abc') |
---|
739 | n/a | self.assertEqual( |
---|
740 | n/a | self.func(add, [['a', 'c'], [], ['d', 'w']], []), |
---|
741 | n/a | ['a','c','d','w'] |
---|
742 | n/a | ) |
---|
743 | n/a | self.assertEqual(self.func(lambda x, y: x*y, range(2,8), 1), 5040) |
---|
744 | n/a | self.assertEqual( |
---|
745 | n/a | self.func(lambda x, y: x*y, range(2,21), 1), |
---|
746 | n/a | 2432902008176640000 |
---|
747 | n/a | ) |
---|
748 | n/a | self.assertEqual(self.func(add, Squares(10)), 285) |
---|
749 | n/a | self.assertEqual(self.func(add, Squares(10), 0), 285) |
---|
750 | n/a | self.assertEqual(self.func(add, Squares(0), 0), 0) |
---|
751 | n/a | self.assertRaises(TypeError, self.func) |
---|
752 | n/a | self.assertRaises(TypeError, self.func, 42, 42) |
---|
753 | n/a | self.assertRaises(TypeError, self.func, 42, 42, 42) |
---|
754 | n/a | self.assertEqual(self.func(42, "1"), "1") # func is never called with one item |
---|
755 | n/a | self.assertEqual(self.func(42, "", "1"), "1") # func is never called with one item |
---|
756 | n/a | self.assertRaises(TypeError, self.func, 42, (42, 42)) |
---|
757 | n/a | self.assertRaises(TypeError, self.func, add, []) # arg 2 must not be empty sequence with no initial value |
---|
758 | n/a | self.assertRaises(TypeError, self.func, add, "") |
---|
759 | n/a | self.assertRaises(TypeError, self.func, add, ()) |
---|
760 | n/a | self.assertRaises(TypeError, self.func, add, object()) |
---|
761 | n/a | |
---|
762 | n/a | class TestFailingIter: |
---|
763 | n/a | def __iter__(self): |
---|
764 | n/a | raise RuntimeError |
---|
765 | n/a | self.assertRaises(RuntimeError, self.func, add, TestFailingIter()) |
---|
766 | n/a | |
---|
767 | n/a | self.assertEqual(self.func(add, [], None), None) |
---|
768 | n/a | self.assertEqual(self.func(add, [], 42), 42) |
---|
769 | n/a | |
---|
770 | n/a | class BadSeq: |
---|
771 | n/a | def __getitem__(self, index): |
---|
772 | n/a | raise ValueError |
---|
773 | n/a | self.assertRaises(ValueError, self.func, 42, BadSeq()) |
---|
774 | n/a | |
---|
775 | n/a | # Test reduce()'s use of iterators. |
---|
776 | n/a | def test_iterator_usage(self): |
---|
777 | n/a | class SequenceClass: |
---|
778 | n/a | def __init__(self, n): |
---|
779 | n/a | self.n = n |
---|
780 | n/a | def __getitem__(self, i): |
---|
781 | n/a | if 0 <= i < self.n: |
---|
782 | n/a | return i |
---|
783 | n/a | else: |
---|
784 | n/a | raise IndexError |
---|
785 | n/a | |
---|
786 | n/a | from operator import add |
---|
787 | n/a | self.assertEqual(self.func(add, SequenceClass(5)), 10) |
---|
788 | n/a | self.assertEqual(self.func(add, SequenceClass(5), 42), 52) |
---|
789 | n/a | self.assertRaises(TypeError, self.func, add, SequenceClass(0)) |
---|
790 | n/a | self.assertEqual(self.func(add, SequenceClass(0), 42), 42) |
---|
791 | n/a | self.assertEqual(self.func(add, SequenceClass(1)), 0) |
---|
792 | n/a | self.assertEqual(self.func(add, SequenceClass(1), 42), 42) |
---|
793 | n/a | |
---|
794 | n/a | d = {"one": 1, "two": 2, "three": 3} |
---|
795 | n/a | self.assertEqual(self.func(add, d), "".join(d.keys())) |
---|
796 | n/a | |
---|
797 | n/a | |
---|
798 | n/a | class TestCmpToKey: |
---|
799 | n/a | |
---|
800 | n/a | def test_cmp_to_key(self): |
---|
801 | n/a | def cmp1(x, y): |
---|
802 | n/a | return (x > y) - (x < y) |
---|
803 | n/a | key = self.cmp_to_key(cmp1) |
---|
804 | n/a | self.assertEqual(key(3), key(3)) |
---|
805 | n/a | self.assertGreater(key(3), key(1)) |
---|
806 | n/a | self.assertGreaterEqual(key(3), key(3)) |
---|
807 | n/a | |
---|
808 | n/a | def cmp2(x, y): |
---|
809 | n/a | return int(x) - int(y) |
---|
810 | n/a | key = self.cmp_to_key(cmp2) |
---|
811 | n/a | self.assertEqual(key(4.0), key('4')) |
---|
812 | n/a | self.assertLess(key(2), key('35')) |
---|
813 | n/a | self.assertLessEqual(key(2), key('35')) |
---|
814 | n/a | self.assertNotEqual(key(2), key('35')) |
---|
815 | n/a | |
---|
816 | n/a | def test_cmp_to_key_arguments(self): |
---|
817 | n/a | def cmp1(x, y): |
---|
818 | n/a | return (x > y) - (x < y) |
---|
819 | n/a | key = self.cmp_to_key(mycmp=cmp1) |
---|
820 | n/a | self.assertEqual(key(obj=3), key(obj=3)) |
---|
821 | n/a | self.assertGreater(key(obj=3), key(obj=1)) |
---|
822 | n/a | with self.assertRaises((TypeError, AttributeError)): |
---|
823 | n/a | key(3) > 1 # rhs is not a K object |
---|
824 | n/a | with self.assertRaises((TypeError, AttributeError)): |
---|
825 | n/a | 1 < key(3) # lhs is not a K object |
---|
826 | n/a | with self.assertRaises(TypeError): |
---|
827 | n/a | key = self.cmp_to_key() # too few args |
---|
828 | n/a | with self.assertRaises(TypeError): |
---|
829 | n/a | key = self.cmp_to_key(cmp1, None) # too many args |
---|
830 | n/a | key = self.cmp_to_key(cmp1) |
---|
831 | n/a | with self.assertRaises(TypeError): |
---|
832 | n/a | key() # too few args |
---|
833 | n/a | with self.assertRaises(TypeError): |
---|
834 | n/a | key(None, None) # too many args |
---|
835 | n/a | |
---|
836 | n/a | def test_bad_cmp(self): |
---|
837 | n/a | def cmp1(x, y): |
---|
838 | n/a | raise ZeroDivisionError |
---|
839 | n/a | key = self.cmp_to_key(cmp1) |
---|
840 | n/a | with self.assertRaises(ZeroDivisionError): |
---|
841 | n/a | key(3) > key(1) |
---|
842 | n/a | |
---|
843 | n/a | class BadCmp: |
---|
844 | n/a | def __lt__(self, other): |
---|
845 | n/a | raise ZeroDivisionError |
---|
846 | n/a | def cmp1(x, y): |
---|
847 | n/a | return BadCmp() |
---|
848 | n/a | with self.assertRaises(ZeroDivisionError): |
---|
849 | n/a | key(3) > key(1) |
---|
850 | n/a | |
---|
851 | n/a | def test_obj_field(self): |
---|
852 | n/a | def cmp1(x, y): |
---|
853 | n/a | return (x > y) - (x < y) |
---|
854 | n/a | key = self.cmp_to_key(mycmp=cmp1) |
---|
855 | n/a | self.assertEqual(key(50).obj, 50) |
---|
856 | n/a | |
---|
857 | n/a | def test_sort_int(self): |
---|
858 | n/a | def mycmp(x, y): |
---|
859 | n/a | return y - x |
---|
860 | n/a | self.assertEqual(sorted(range(5), key=self.cmp_to_key(mycmp)), |
---|
861 | n/a | [4, 3, 2, 1, 0]) |
---|
862 | n/a | |
---|
863 | n/a | def test_sort_int_str(self): |
---|
864 | n/a | def mycmp(x, y): |
---|
865 | n/a | x, y = int(x), int(y) |
---|
866 | n/a | return (x > y) - (x < y) |
---|
867 | n/a | values = [5, '3', 7, 2, '0', '1', 4, '10', 1] |
---|
868 | n/a | values = sorted(values, key=self.cmp_to_key(mycmp)) |
---|
869 | n/a | self.assertEqual([int(value) for value in values], |
---|
870 | n/a | [0, 1, 1, 2, 3, 4, 5, 7, 10]) |
---|
871 | n/a | |
---|
872 | n/a | def test_hash(self): |
---|
873 | n/a | def mycmp(x, y): |
---|
874 | n/a | return y - x |
---|
875 | n/a | key = self.cmp_to_key(mycmp) |
---|
876 | n/a | k = key(10) |
---|
877 | n/a | self.assertRaises(TypeError, hash, k) |
---|
878 | n/a | self.assertNotIsInstance(k, collections.Hashable) |
---|
879 | n/a | |
---|
880 | n/a | |
---|
881 | n/a | @unittest.skipUnless(c_functools, 'requires the C _functools module') |
---|
882 | n/a | class TestCmpToKeyC(TestCmpToKey, unittest.TestCase): |
---|
883 | n/a | if c_functools: |
---|
884 | n/a | cmp_to_key = c_functools.cmp_to_key |
---|
885 | n/a | |
---|
886 | n/a | |
---|
887 | n/a | class TestCmpToKeyPy(TestCmpToKey, unittest.TestCase): |
---|
888 | n/a | cmp_to_key = staticmethod(py_functools.cmp_to_key) |
---|
889 | n/a | |
---|
890 | n/a | |
---|
891 | n/a | class TestTotalOrdering(unittest.TestCase): |
---|
892 | n/a | |
---|
893 | n/a | def test_total_ordering_lt(self): |
---|
894 | n/a | @functools.total_ordering |
---|
895 | n/a | class A: |
---|
896 | n/a | def __init__(self, value): |
---|
897 | n/a | self.value = value |
---|
898 | n/a | def __lt__(self, other): |
---|
899 | n/a | return self.value < other.value |
---|
900 | n/a | def __eq__(self, other): |
---|
901 | n/a | return self.value == other.value |
---|
902 | n/a | self.assertTrue(A(1) < A(2)) |
---|
903 | n/a | self.assertTrue(A(2) > A(1)) |
---|
904 | n/a | self.assertTrue(A(1) <= A(2)) |
---|
905 | n/a | self.assertTrue(A(2) >= A(1)) |
---|
906 | n/a | self.assertTrue(A(2) <= A(2)) |
---|
907 | n/a | self.assertTrue(A(2) >= A(2)) |
---|
908 | n/a | self.assertFalse(A(1) > A(2)) |
---|
909 | n/a | |
---|
910 | n/a | def test_total_ordering_le(self): |
---|
911 | n/a | @functools.total_ordering |
---|
912 | n/a | class A: |
---|
913 | n/a | def __init__(self, value): |
---|
914 | n/a | self.value = value |
---|
915 | n/a | def __le__(self, other): |
---|
916 | n/a | return self.value <= other.value |
---|
917 | n/a | def __eq__(self, other): |
---|
918 | n/a | return self.value == other.value |
---|
919 | n/a | self.assertTrue(A(1) < A(2)) |
---|
920 | n/a | self.assertTrue(A(2) > A(1)) |
---|
921 | n/a | self.assertTrue(A(1) <= A(2)) |
---|
922 | n/a | self.assertTrue(A(2) >= A(1)) |
---|
923 | n/a | self.assertTrue(A(2) <= A(2)) |
---|
924 | n/a | self.assertTrue(A(2) >= A(2)) |
---|
925 | n/a | self.assertFalse(A(1) >= A(2)) |
---|
926 | n/a | |
---|
927 | n/a | def test_total_ordering_gt(self): |
---|
928 | n/a | @functools.total_ordering |
---|
929 | n/a | class A: |
---|
930 | n/a | def __init__(self, value): |
---|
931 | n/a | self.value = value |
---|
932 | n/a | def __gt__(self, other): |
---|
933 | n/a | return self.value > other.value |
---|
934 | n/a | def __eq__(self, other): |
---|
935 | n/a | return self.value == other.value |
---|
936 | n/a | self.assertTrue(A(1) < A(2)) |
---|
937 | n/a | self.assertTrue(A(2) > A(1)) |
---|
938 | n/a | self.assertTrue(A(1) <= A(2)) |
---|
939 | n/a | self.assertTrue(A(2) >= A(1)) |
---|
940 | n/a | self.assertTrue(A(2) <= A(2)) |
---|
941 | n/a | self.assertTrue(A(2) >= A(2)) |
---|
942 | n/a | self.assertFalse(A(2) < A(1)) |
---|
943 | n/a | |
---|
944 | n/a | def test_total_ordering_ge(self): |
---|
945 | n/a | @functools.total_ordering |
---|
946 | n/a | class A: |
---|
947 | n/a | def __init__(self, value): |
---|
948 | n/a | self.value = value |
---|
949 | n/a | def __ge__(self, other): |
---|
950 | n/a | return self.value >= other.value |
---|
951 | n/a | def __eq__(self, other): |
---|
952 | n/a | return self.value == other.value |
---|
953 | n/a | self.assertTrue(A(1) < A(2)) |
---|
954 | n/a | self.assertTrue(A(2) > A(1)) |
---|
955 | n/a | self.assertTrue(A(1) <= A(2)) |
---|
956 | n/a | self.assertTrue(A(2) >= A(1)) |
---|
957 | n/a | self.assertTrue(A(2) <= A(2)) |
---|
958 | n/a | self.assertTrue(A(2) >= A(2)) |
---|
959 | n/a | self.assertFalse(A(2) <= A(1)) |
---|
960 | n/a | |
---|
961 | n/a | def test_total_ordering_no_overwrite(self): |
---|
962 | n/a | # new methods should not overwrite existing |
---|
963 | n/a | @functools.total_ordering |
---|
964 | n/a | class A(int): |
---|
965 | n/a | pass |
---|
966 | n/a | self.assertTrue(A(1) < A(2)) |
---|
967 | n/a | self.assertTrue(A(2) > A(1)) |
---|
968 | n/a | self.assertTrue(A(1) <= A(2)) |
---|
969 | n/a | self.assertTrue(A(2) >= A(1)) |
---|
970 | n/a | self.assertTrue(A(2) <= A(2)) |
---|
971 | n/a | self.assertTrue(A(2) >= A(2)) |
---|
972 | n/a | |
---|
973 | n/a | def test_no_operations_defined(self): |
---|
974 | n/a | with self.assertRaises(ValueError): |
---|
975 | n/a | @functools.total_ordering |
---|
976 | n/a | class A: |
---|
977 | n/a | pass |
---|
978 | n/a | |
---|
979 | n/a | def test_type_error_when_not_implemented(self): |
---|
980 | n/a | # bug 10042; ensure stack overflow does not occur |
---|
981 | n/a | # when decorated types return NotImplemented |
---|
982 | n/a | @functools.total_ordering |
---|
983 | n/a | class ImplementsLessThan: |
---|
984 | n/a | def __init__(self, value): |
---|
985 | n/a | self.value = value |
---|
986 | n/a | def __eq__(self, other): |
---|
987 | n/a | if isinstance(other, ImplementsLessThan): |
---|
988 | n/a | return self.value == other.value |
---|
989 | n/a | return False |
---|
990 | n/a | def __lt__(self, other): |
---|
991 | n/a | if isinstance(other, ImplementsLessThan): |
---|
992 | n/a | return self.value < other.value |
---|
993 | n/a | return NotImplemented |
---|
994 | n/a | |
---|
995 | n/a | @functools.total_ordering |
---|
996 | n/a | class ImplementsGreaterThan: |
---|
997 | n/a | def __init__(self, value): |
---|
998 | n/a | self.value = value |
---|
999 | n/a | def __eq__(self, other): |
---|
1000 | n/a | if isinstance(other, ImplementsGreaterThan): |
---|
1001 | n/a | return self.value == other.value |
---|
1002 | n/a | return False |
---|
1003 | n/a | def __gt__(self, other): |
---|
1004 | n/a | if isinstance(other, ImplementsGreaterThan): |
---|
1005 | n/a | return self.value > other.value |
---|
1006 | n/a | return NotImplemented |
---|
1007 | n/a | |
---|
1008 | n/a | @functools.total_ordering |
---|
1009 | n/a | class ImplementsLessThanEqualTo: |
---|
1010 | n/a | def __init__(self, value): |
---|
1011 | n/a | self.value = value |
---|
1012 | n/a | def __eq__(self, other): |
---|
1013 | n/a | if isinstance(other, ImplementsLessThanEqualTo): |
---|
1014 | n/a | return self.value == other.value |
---|
1015 | n/a | return False |
---|
1016 | n/a | def __le__(self, other): |
---|
1017 | n/a | if isinstance(other, ImplementsLessThanEqualTo): |
---|
1018 | n/a | return self.value <= other.value |
---|
1019 | n/a | return NotImplemented |
---|
1020 | n/a | |
---|
1021 | n/a | @functools.total_ordering |
---|
1022 | n/a | class ImplementsGreaterThanEqualTo: |
---|
1023 | n/a | def __init__(self, value): |
---|
1024 | n/a | self.value = value |
---|
1025 | n/a | def __eq__(self, other): |
---|
1026 | n/a | if isinstance(other, ImplementsGreaterThanEqualTo): |
---|
1027 | n/a | return self.value == other.value |
---|
1028 | n/a | return False |
---|
1029 | n/a | def __ge__(self, other): |
---|
1030 | n/a | if isinstance(other, ImplementsGreaterThanEqualTo): |
---|
1031 | n/a | return self.value >= other.value |
---|
1032 | n/a | return NotImplemented |
---|
1033 | n/a | |
---|
1034 | n/a | @functools.total_ordering |
---|
1035 | n/a | class ComparatorNotImplemented: |
---|
1036 | n/a | def __init__(self, value): |
---|
1037 | n/a | self.value = value |
---|
1038 | n/a | def __eq__(self, other): |
---|
1039 | n/a | if isinstance(other, ComparatorNotImplemented): |
---|
1040 | n/a | return self.value == other.value |
---|
1041 | n/a | return False |
---|
1042 | n/a | def __lt__(self, other): |
---|
1043 | n/a | return NotImplemented |
---|
1044 | n/a | |
---|
1045 | n/a | with self.subTest("LT < 1"), self.assertRaises(TypeError): |
---|
1046 | n/a | ImplementsLessThan(-1) < 1 |
---|
1047 | n/a | |
---|
1048 | n/a | with self.subTest("LT < LE"), self.assertRaises(TypeError): |
---|
1049 | n/a | ImplementsLessThan(0) < ImplementsLessThanEqualTo(0) |
---|
1050 | n/a | |
---|
1051 | n/a | with self.subTest("LT < GT"), self.assertRaises(TypeError): |
---|
1052 | n/a | ImplementsLessThan(1) < ImplementsGreaterThan(1) |
---|
1053 | n/a | |
---|
1054 | n/a | with self.subTest("LE <= LT"), self.assertRaises(TypeError): |
---|
1055 | n/a | ImplementsLessThanEqualTo(2) <= ImplementsLessThan(2) |
---|
1056 | n/a | |
---|
1057 | n/a | with self.subTest("LE <= GE"), self.assertRaises(TypeError): |
---|
1058 | n/a | ImplementsLessThanEqualTo(3) <= ImplementsGreaterThanEqualTo(3) |
---|
1059 | n/a | |
---|
1060 | n/a | with self.subTest("GT > GE"), self.assertRaises(TypeError): |
---|
1061 | n/a | ImplementsGreaterThan(4) > ImplementsGreaterThanEqualTo(4) |
---|
1062 | n/a | |
---|
1063 | n/a | with self.subTest("GT > LT"), self.assertRaises(TypeError): |
---|
1064 | n/a | ImplementsGreaterThan(5) > ImplementsLessThan(5) |
---|
1065 | n/a | |
---|
1066 | n/a | with self.subTest("GE >= GT"), self.assertRaises(TypeError): |
---|
1067 | n/a | ImplementsGreaterThanEqualTo(6) >= ImplementsGreaterThan(6) |
---|
1068 | n/a | |
---|
1069 | n/a | with self.subTest("GE >= LE"), self.assertRaises(TypeError): |
---|
1070 | n/a | ImplementsGreaterThanEqualTo(7) >= ImplementsLessThanEqualTo(7) |
---|
1071 | n/a | |
---|
1072 | n/a | with self.subTest("GE when equal"): |
---|
1073 | n/a | a = ComparatorNotImplemented(8) |
---|
1074 | n/a | b = ComparatorNotImplemented(8) |
---|
1075 | n/a | self.assertEqual(a, b) |
---|
1076 | n/a | with self.assertRaises(TypeError): |
---|
1077 | n/a | a >= b |
---|
1078 | n/a | |
---|
1079 | n/a | with self.subTest("LE when equal"): |
---|
1080 | n/a | a = ComparatorNotImplemented(9) |
---|
1081 | n/a | b = ComparatorNotImplemented(9) |
---|
1082 | n/a | self.assertEqual(a, b) |
---|
1083 | n/a | with self.assertRaises(TypeError): |
---|
1084 | n/a | a <= b |
---|
1085 | n/a | |
---|
1086 | n/a | def test_pickle(self): |
---|
1087 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
1088 | n/a | for name in '__lt__', '__gt__', '__le__', '__ge__': |
---|
1089 | n/a | with self.subTest(method=name, proto=proto): |
---|
1090 | n/a | method = getattr(Orderable_LT, name) |
---|
1091 | n/a | method_copy = pickle.loads(pickle.dumps(method, proto)) |
---|
1092 | n/a | self.assertIs(method_copy, method) |
---|
1093 | n/a | |
---|
1094 | n/a | @functools.total_ordering |
---|
1095 | n/a | class Orderable_LT: |
---|
1096 | n/a | def __init__(self, value): |
---|
1097 | n/a | self.value = value |
---|
1098 | n/a | def __lt__(self, other): |
---|
1099 | n/a | return self.value < other.value |
---|
1100 | n/a | def __eq__(self, other): |
---|
1101 | n/a | return self.value == other.value |
---|
1102 | n/a | |
---|
1103 | n/a | |
---|
1104 | n/a | class TestLRU: |
---|
1105 | n/a | |
---|
1106 | n/a | def test_lru(self): |
---|
1107 | n/a | def orig(x, y): |
---|
1108 | n/a | return 3 * x + y |
---|
1109 | n/a | f = self.module.lru_cache(maxsize=20)(orig) |
---|
1110 | n/a | hits, misses, maxsize, currsize = f.cache_info() |
---|
1111 | n/a | self.assertEqual(maxsize, 20) |
---|
1112 | n/a | self.assertEqual(currsize, 0) |
---|
1113 | n/a | self.assertEqual(hits, 0) |
---|
1114 | n/a | self.assertEqual(misses, 0) |
---|
1115 | n/a | |
---|
1116 | n/a | domain = range(5) |
---|
1117 | n/a | for i in range(1000): |
---|
1118 | n/a | x, y = choice(domain), choice(domain) |
---|
1119 | n/a | actual = f(x, y) |
---|
1120 | n/a | expected = orig(x, y) |
---|
1121 | n/a | self.assertEqual(actual, expected) |
---|
1122 | n/a | hits, misses, maxsize, currsize = f.cache_info() |
---|
1123 | n/a | self.assertTrue(hits > misses) |
---|
1124 | n/a | self.assertEqual(hits + misses, 1000) |
---|
1125 | n/a | self.assertEqual(currsize, 20) |
---|
1126 | n/a | |
---|
1127 | n/a | f.cache_clear() # test clearing |
---|
1128 | n/a | hits, misses, maxsize, currsize = f.cache_info() |
---|
1129 | n/a | self.assertEqual(hits, 0) |
---|
1130 | n/a | self.assertEqual(misses, 0) |
---|
1131 | n/a | self.assertEqual(currsize, 0) |
---|
1132 | n/a | f(x, y) |
---|
1133 | n/a | hits, misses, maxsize, currsize = f.cache_info() |
---|
1134 | n/a | self.assertEqual(hits, 0) |
---|
1135 | n/a | self.assertEqual(misses, 1) |
---|
1136 | n/a | self.assertEqual(currsize, 1) |
---|
1137 | n/a | |
---|
1138 | n/a | # Test bypassing the cache |
---|
1139 | n/a | self.assertIs(f.__wrapped__, orig) |
---|
1140 | n/a | f.__wrapped__(x, y) |
---|
1141 | n/a | hits, misses, maxsize, currsize = f.cache_info() |
---|
1142 | n/a | self.assertEqual(hits, 0) |
---|
1143 | n/a | self.assertEqual(misses, 1) |
---|
1144 | n/a | self.assertEqual(currsize, 1) |
---|
1145 | n/a | |
---|
1146 | n/a | # test size zero (which means "never-cache") |
---|
1147 | n/a | @self.module.lru_cache(0) |
---|
1148 | n/a | def f(): |
---|
1149 | n/a | nonlocal f_cnt |
---|
1150 | n/a | f_cnt += 1 |
---|
1151 | n/a | return 20 |
---|
1152 | n/a | self.assertEqual(f.cache_info().maxsize, 0) |
---|
1153 | n/a | f_cnt = 0 |
---|
1154 | n/a | for i in range(5): |
---|
1155 | n/a | self.assertEqual(f(), 20) |
---|
1156 | n/a | self.assertEqual(f_cnt, 5) |
---|
1157 | n/a | hits, misses, maxsize, currsize = f.cache_info() |
---|
1158 | n/a | self.assertEqual(hits, 0) |
---|
1159 | n/a | self.assertEqual(misses, 5) |
---|
1160 | n/a | self.assertEqual(currsize, 0) |
---|
1161 | n/a | |
---|
1162 | n/a | # test size one |
---|
1163 | n/a | @self.module.lru_cache(1) |
---|
1164 | n/a | def f(): |
---|
1165 | n/a | nonlocal f_cnt |
---|
1166 | n/a | f_cnt += 1 |
---|
1167 | n/a | return 20 |
---|
1168 | n/a | self.assertEqual(f.cache_info().maxsize, 1) |
---|
1169 | n/a | f_cnt = 0 |
---|
1170 | n/a | for i in range(5): |
---|
1171 | n/a | self.assertEqual(f(), 20) |
---|
1172 | n/a | self.assertEqual(f_cnt, 1) |
---|
1173 | n/a | hits, misses, maxsize, currsize = f.cache_info() |
---|
1174 | n/a | self.assertEqual(hits, 4) |
---|
1175 | n/a | self.assertEqual(misses, 1) |
---|
1176 | n/a | self.assertEqual(currsize, 1) |
---|
1177 | n/a | |
---|
1178 | n/a | # test size two |
---|
1179 | n/a | @self.module.lru_cache(2) |
---|
1180 | n/a | def f(x): |
---|
1181 | n/a | nonlocal f_cnt |
---|
1182 | n/a | f_cnt += 1 |
---|
1183 | n/a | return x*10 |
---|
1184 | n/a | self.assertEqual(f.cache_info().maxsize, 2) |
---|
1185 | n/a | f_cnt = 0 |
---|
1186 | n/a | for x in 7, 9, 7, 9, 7, 9, 8, 8, 8, 9, 9, 9, 8, 8, 8, 7: |
---|
1187 | n/a | # * * * * |
---|
1188 | n/a | self.assertEqual(f(x), x*10) |
---|
1189 | n/a | self.assertEqual(f_cnt, 4) |
---|
1190 | n/a | hits, misses, maxsize, currsize = f.cache_info() |
---|
1191 | n/a | self.assertEqual(hits, 12) |
---|
1192 | n/a | self.assertEqual(misses, 4) |
---|
1193 | n/a | self.assertEqual(currsize, 2) |
---|
1194 | n/a | |
---|
1195 | n/a | def test_lru_hash_only_once(self): |
---|
1196 | n/a | # To protect against weird reentrancy bugs and to improve |
---|
1197 | n/a | # efficiency when faced with slow __hash__ methods, the |
---|
1198 | n/a | # LRU cache guarantees that it will only call __hash__ |
---|
1199 | n/a | # only once per use as an argument to the cached function. |
---|
1200 | n/a | |
---|
1201 | n/a | @self.module.lru_cache(maxsize=1) |
---|
1202 | n/a | def f(x, y): |
---|
1203 | n/a | return x * 3 + y |
---|
1204 | n/a | |
---|
1205 | n/a | # Simulate the integer 5 |
---|
1206 | n/a | mock_int = unittest.mock.Mock() |
---|
1207 | n/a | mock_int.__mul__ = unittest.mock.Mock(return_value=15) |
---|
1208 | n/a | mock_int.__hash__ = unittest.mock.Mock(return_value=999) |
---|
1209 | n/a | |
---|
1210 | n/a | # Add to cache: One use as an argument gives one call |
---|
1211 | n/a | self.assertEqual(f(mock_int, 1), 16) |
---|
1212 | n/a | self.assertEqual(mock_int.__hash__.call_count, 1) |
---|
1213 | n/a | self.assertEqual(f.cache_info(), (0, 1, 1, 1)) |
---|
1214 | n/a | |
---|
1215 | n/a | # Cache hit: One use as an argument gives one additional call |
---|
1216 | n/a | self.assertEqual(f(mock_int, 1), 16) |
---|
1217 | n/a | self.assertEqual(mock_int.__hash__.call_count, 2) |
---|
1218 | n/a | self.assertEqual(f.cache_info(), (1, 1, 1, 1)) |
---|
1219 | n/a | |
---|
1220 | n/a | # Cache eviction: No use as an argument gives no additonal call |
---|
1221 | n/a | self.assertEqual(f(6, 2), 20) |
---|
1222 | n/a | self.assertEqual(mock_int.__hash__.call_count, 2) |
---|
1223 | n/a | self.assertEqual(f.cache_info(), (1, 2, 1, 1)) |
---|
1224 | n/a | |
---|
1225 | n/a | # Cache miss: One use as an argument gives one additional call |
---|
1226 | n/a | self.assertEqual(f(mock_int, 1), 16) |
---|
1227 | n/a | self.assertEqual(mock_int.__hash__.call_count, 3) |
---|
1228 | n/a | self.assertEqual(f.cache_info(), (1, 3, 1, 1)) |
---|
1229 | n/a | |
---|
1230 | n/a | def test_lru_reentrancy_with_len(self): |
---|
1231 | n/a | # Test to make sure the LRU cache code isn't thrown-off by |
---|
1232 | n/a | # caching the built-in len() function. Since len() can be |
---|
1233 | n/a | # cached, we shouldn't use it inside the lru code itself. |
---|
1234 | n/a | old_len = builtins.len |
---|
1235 | n/a | try: |
---|
1236 | n/a | builtins.len = self.module.lru_cache(4)(len) |
---|
1237 | n/a | for i in [0, 0, 1, 2, 3, 3, 4, 5, 6, 1, 7, 2, 1]: |
---|
1238 | n/a | self.assertEqual(len('abcdefghijklmn'[:i]), i) |
---|
1239 | n/a | finally: |
---|
1240 | n/a | builtins.len = old_len |
---|
1241 | n/a | |
---|
1242 | n/a | def test_lru_star_arg_handling(self): |
---|
1243 | n/a | # Test regression that arose in ea064ff3c10f |
---|
1244 | n/a | @functools.lru_cache() |
---|
1245 | n/a | def f(*args): |
---|
1246 | n/a | return args |
---|
1247 | n/a | |
---|
1248 | n/a | self.assertEqual(f(1, 2), (1, 2)) |
---|
1249 | n/a | self.assertEqual(f((1, 2)), ((1, 2),)) |
---|
1250 | n/a | |
---|
1251 | n/a | def test_lru_type_error(self): |
---|
1252 | n/a | # Regression test for issue #28653. |
---|
1253 | n/a | # lru_cache was leaking when one of the arguments |
---|
1254 | n/a | # wasn't cacheable. |
---|
1255 | n/a | |
---|
1256 | n/a | @functools.lru_cache(maxsize=None) |
---|
1257 | n/a | def infinite_cache(o): |
---|
1258 | n/a | pass |
---|
1259 | n/a | |
---|
1260 | n/a | @functools.lru_cache(maxsize=10) |
---|
1261 | n/a | def limited_cache(o): |
---|
1262 | n/a | pass |
---|
1263 | n/a | |
---|
1264 | n/a | with self.assertRaises(TypeError): |
---|
1265 | n/a | infinite_cache([]) |
---|
1266 | n/a | |
---|
1267 | n/a | with self.assertRaises(TypeError): |
---|
1268 | n/a | limited_cache([]) |
---|
1269 | n/a | |
---|
1270 | n/a | def test_lru_with_maxsize_none(self): |
---|
1271 | n/a | @self.module.lru_cache(maxsize=None) |
---|
1272 | n/a | def fib(n): |
---|
1273 | n/a | if n < 2: |
---|
1274 | n/a | return n |
---|
1275 | n/a | return fib(n-1) + fib(n-2) |
---|
1276 | n/a | self.assertEqual([fib(n) for n in range(16)], |
---|
1277 | n/a | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]) |
---|
1278 | n/a | self.assertEqual(fib.cache_info(), |
---|
1279 | n/a | self.module._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)) |
---|
1280 | n/a | fib.cache_clear() |
---|
1281 | n/a | self.assertEqual(fib.cache_info(), |
---|
1282 | n/a | self.module._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)) |
---|
1283 | n/a | |
---|
1284 | n/a | def test_lru_with_maxsize_negative(self): |
---|
1285 | n/a | @self.module.lru_cache(maxsize=-10) |
---|
1286 | n/a | def eq(n): |
---|
1287 | n/a | return n |
---|
1288 | n/a | for i in (0, 1): |
---|
1289 | n/a | self.assertEqual([eq(n) for n in range(150)], list(range(150))) |
---|
1290 | n/a | self.assertEqual(eq.cache_info(), |
---|
1291 | n/a | self.module._CacheInfo(hits=0, misses=300, maxsize=-10, currsize=1)) |
---|
1292 | n/a | |
---|
1293 | n/a | def test_lru_with_exceptions(self): |
---|
1294 | n/a | # Verify that user_function exceptions get passed through without |
---|
1295 | n/a | # creating a hard-to-read chained exception. |
---|
1296 | n/a | # http://bugs.python.org/issue13177 |
---|
1297 | n/a | for maxsize in (None, 128): |
---|
1298 | n/a | @self.module.lru_cache(maxsize) |
---|
1299 | n/a | def func(i): |
---|
1300 | n/a | return 'abc'[i] |
---|
1301 | n/a | self.assertEqual(func(0), 'a') |
---|
1302 | n/a | with self.assertRaises(IndexError) as cm: |
---|
1303 | n/a | func(15) |
---|
1304 | n/a | self.assertIsNone(cm.exception.__context__) |
---|
1305 | n/a | # Verify that the previous exception did not result in a cached entry |
---|
1306 | n/a | with self.assertRaises(IndexError): |
---|
1307 | n/a | func(15) |
---|
1308 | n/a | |
---|
1309 | n/a | def test_lru_with_types(self): |
---|
1310 | n/a | for maxsize in (None, 128): |
---|
1311 | n/a | @self.module.lru_cache(maxsize=maxsize, typed=True) |
---|
1312 | n/a | def square(x): |
---|
1313 | n/a | return x * x |
---|
1314 | n/a | self.assertEqual(square(3), 9) |
---|
1315 | n/a | self.assertEqual(type(square(3)), type(9)) |
---|
1316 | n/a | self.assertEqual(square(3.0), 9.0) |
---|
1317 | n/a | self.assertEqual(type(square(3.0)), type(9.0)) |
---|
1318 | n/a | self.assertEqual(square(x=3), 9) |
---|
1319 | n/a | self.assertEqual(type(square(x=3)), type(9)) |
---|
1320 | n/a | self.assertEqual(square(x=3.0), 9.0) |
---|
1321 | n/a | self.assertEqual(type(square(x=3.0)), type(9.0)) |
---|
1322 | n/a | self.assertEqual(square.cache_info().hits, 4) |
---|
1323 | n/a | self.assertEqual(square.cache_info().misses, 4) |
---|
1324 | n/a | |
---|
1325 | n/a | def test_lru_with_keyword_args(self): |
---|
1326 | n/a | @self.module.lru_cache() |
---|
1327 | n/a | def fib(n): |
---|
1328 | n/a | if n < 2: |
---|
1329 | n/a | return n |
---|
1330 | n/a | return fib(n=n-1) + fib(n=n-2) |
---|
1331 | n/a | self.assertEqual( |
---|
1332 | n/a | [fib(n=number) for number in range(16)], |
---|
1333 | n/a | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] |
---|
1334 | n/a | ) |
---|
1335 | n/a | self.assertEqual(fib.cache_info(), |
---|
1336 | n/a | self.module._CacheInfo(hits=28, misses=16, maxsize=128, currsize=16)) |
---|
1337 | n/a | fib.cache_clear() |
---|
1338 | n/a | self.assertEqual(fib.cache_info(), |
---|
1339 | n/a | self.module._CacheInfo(hits=0, misses=0, maxsize=128, currsize=0)) |
---|
1340 | n/a | |
---|
1341 | n/a | def test_lru_with_keyword_args_maxsize_none(self): |
---|
1342 | n/a | @self.module.lru_cache(maxsize=None) |
---|
1343 | n/a | def fib(n): |
---|
1344 | n/a | if n < 2: |
---|
1345 | n/a | return n |
---|
1346 | n/a | return fib(n=n-1) + fib(n=n-2) |
---|
1347 | n/a | self.assertEqual([fib(n=number) for number in range(16)], |
---|
1348 | n/a | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]) |
---|
1349 | n/a | self.assertEqual(fib.cache_info(), |
---|
1350 | n/a | self.module._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)) |
---|
1351 | n/a | fib.cache_clear() |
---|
1352 | n/a | self.assertEqual(fib.cache_info(), |
---|
1353 | n/a | self.module._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)) |
---|
1354 | n/a | |
---|
1355 | n/a | def test_kwargs_order(self): |
---|
1356 | n/a | # PEP 468: Preserving Keyword Argument Order |
---|
1357 | n/a | @self.module.lru_cache(maxsize=10) |
---|
1358 | n/a | def f(**kwargs): |
---|
1359 | n/a | return list(kwargs.items()) |
---|
1360 | n/a | self.assertEqual(f(a=1, b=2), [('a', 1), ('b', 2)]) |
---|
1361 | n/a | self.assertEqual(f(b=2, a=1), [('b', 2), ('a', 1)]) |
---|
1362 | n/a | self.assertEqual(f.cache_info(), |
---|
1363 | n/a | self.module._CacheInfo(hits=0, misses=2, maxsize=10, currsize=2)) |
---|
1364 | n/a | |
---|
1365 | n/a | def test_lru_cache_decoration(self): |
---|
1366 | n/a | def f(zomg: 'zomg_annotation'): |
---|
1367 | n/a | """f doc string""" |
---|
1368 | n/a | return 42 |
---|
1369 | n/a | g = self.module.lru_cache()(f) |
---|
1370 | n/a | for attr in self.module.WRAPPER_ASSIGNMENTS: |
---|
1371 | n/a | self.assertEqual(getattr(g, attr), getattr(f, attr)) |
---|
1372 | n/a | |
---|
1373 | n/a | @unittest.skipUnless(threading, 'This test requires threading.') |
---|
1374 | n/a | def test_lru_cache_threaded(self): |
---|
1375 | n/a | n, m = 5, 11 |
---|
1376 | n/a | def orig(x, y): |
---|
1377 | n/a | return 3 * x + y |
---|
1378 | n/a | f = self.module.lru_cache(maxsize=n*m)(orig) |
---|
1379 | n/a | hits, misses, maxsize, currsize = f.cache_info() |
---|
1380 | n/a | self.assertEqual(currsize, 0) |
---|
1381 | n/a | |
---|
1382 | n/a | start = threading.Event() |
---|
1383 | n/a | def full(k): |
---|
1384 | n/a | start.wait(10) |
---|
1385 | n/a | for _ in range(m): |
---|
1386 | n/a | self.assertEqual(f(k, 0), orig(k, 0)) |
---|
1387 | n/a | |
---|
1388 | n/a | def clear(): |
---|
1389 | n/a | start.wait(10) |
---|
1390 | n/a | for _ in range(2*m): |
---|
1391 | n/a | f.cache_clear() |
---|
1392 | n/a | |
---|
1393 | n/a | orig_si = sys.getswitchinterval() |
---|
1394 | n/a | support.setswitchinterval(1e-6) |
---|
1395 | n/a | try: |
---|
1396 | n/a | # create n threads in order to fill cache |
---|
1397 | n/a | threads = [threading.Thread(target=full, args=[k]) |
---|
1398 | n/a | for k in range(n)] |
---|
1399 | n/a | with support.start_threads(threads): |
---|
1400 | n/a | start.set() |
---|
1401 | n/a | |
---|
1402 | n/a | hits, misses, maxsize, currsize = f.cache_info() |
---|
1403 | n/a | if self.module is py_functools: |
---|
1404 | n/a | # XXX: Why can be not equal? |
---|
1405 | n/a | self.assertLessEqual(misses, n) |
---|
1406 | n/a | self.assertLessEqual(hits, m*n - misses) |
---|
1407 | n/a | else: |
---|
1408 | n/a | self.assertEqual(misses, n) |
---|
1409 | n/a | self.assertEqual(hits, m*n - misses) |
---|
1410 | n/a | self.assertEqual(currsize, n) |
---|
1411 | n/a | |
---|
1412 | n/a | # create n threads in order to fill cache and 1 to clear it |
---|
1413 | n/a | threads = [threading.Thread(target=clear)] |
---|
1414 | n/a | threads += [threading.Thread(target=full, args=[k]) |
---|
1415 | n/a | for k in range(n)] |
---|
1416 | n/a | start.clear() |
---|
1417 | n/a | with support.start_threads(threads): |
---|
1418 | n/a | start.set() |
---|
1419 | n/a | finally: |
---|
1420 | n/a | sys.setswitchinterval(orig_si) |
---|
1421 | n/a | |
---|
1422 | n/a | @unittest.skipUnless(threading, 'This test requires threading.') |
---|
1423 | n/a | def test_lru_cache_threaded2(self): |
---|
1424 | n/a | # Simultaneous call with the same arguments |
---|
1425 | n/a | n, m = 5, 7 |
---|
1426 | n/a | start = threading.Barrier(n+1) |
---|
1427 | n/a | pause = threading.Barrier(n+1) |
---|
1428 | n/a | stop = threading.Barrier(n+1) |
---|
1429 | n/a | @self.module.lru_cache(maxsize=m*n) |
---|
1430 | n/a | def f(x): |
---|
1431 | n/a | pause.wait(10) |
---|
1432 | n/a | return 3 * x |
---|
1433 | n/a | self.assertEqual(f.cache_info(), (0, 0, m*n, 0)) |
---|
1434 | n/a | def test(): |
---|
1435 | n/a | for i in range(m): |
---|
1436 | n/a | start.wait(10) |
---|
1437 | n/a | self.assertEqual(f(i), 3 * i) |
---|
1438 | n/a | stop.wait(10) |
---|
1439 | n/a | threads = [threading.Thread(target=test) for k in range(n)] |
---|
1440 | n/a | with support.start_threads(threads): |
---|
1441 | n/a | for i in range(m): |
---|
1442 | n/a | start.wait(10) |
---|
1443 | n/a | stop.reset() |
---|
1444 | n/a | pause.wait(10) |
---|
1445 | n/a | start.reset() |
---|
1446 | n/a | stop.wait(10) |
---|
1447 | n/a | pause.reset() |
---|
1448 | n/a | self.assertEqual(f.cache_info(), (0, (i+1)*n, m*n, i+1)) |
---|
1449 | n/a | |
---|
1450 | n/a | @unittest.skipUnless(threading, 'This test requires threading.') |
---|
1451 | n/a | def test_lru_cache_threaded3(self): |
---|
1452 | n/a | @self.module.lru_cache(maxsize=2) |
---|
1453 | n/a | def f(x): |
---|
1454 | n/a | time.sleep(.01) |
---|
1455 | n/a | return 3 * x |
---|
1456 | n/a | def test(i, x): |
---|
1457 | n/a | with self.subTest(thread=i): |
---|
1458 | n/a | self.assertEqual(f(x), 3 * x, i) |
---|
1459 | n/a | threads = [threading.Thread(target=test, args=(i, v)) |
---|
1460 | n/a | for i, v in enumerate([1, 2, 2, 3, 2])] |
---|
1461 | n/a | with support.start_threads(threads): |
---|
1462 | n/a | pass |
---|
1463 | n/a | |
---|
1464 | n/a | def test_need_for_rlock(self): |
---|
1465 | n/a | # This will deadlock on an LRU cache that uses a regular lock |
---|
1466 | n/a | |
---|
1467 | n/a | @self.module.lru_cache(maxsize=10) |
---|
1468 | n/a | def test_func(x): |
---|
1469 | n/a | 'Used to demonstrate a reentrant lru_cache call within a single thread' |
---|
1470 | n/a | return x |
---|
1471 | n/a | |
---|
1472 | n/a | class DoubleEq: |
---|
1473 | n/a | 'Demonstrate a reentrant lru_cache call within a single thread' |
---|
1474 | n/a | def __init__(self, x): |
---|
1475 | n/a | self.x = x |
---|
1476 | n/a | def __hash__(self): |
---|
1477 | n/a | return self.x |
---|
1478 | n/a | def __eq__(self, other): |
---|
1479 | n/a | if self.x == 2: |
---|
1480 | n/a | test_func(DoubleEq(1)) |
---|
1481 | n/a | return self.x == other.x |
---|
1482 | n/a | |
---|
1483 | n/a | test_func(DoubleEq(1)) # Load the cache |
---|
1484 | n/a | test_func(DoubleEq(2)) # Load the cache |
---|
1485 | n/a | self.assertEqual(test_func(DoubleEq(2)), # Trigger a re-entrant __eq__ call |
---|
1486 | n/a | DoubleEq(2)) # Verify the correct return value |
---|
1487 | n/a | |
---|
1488 | n/a | def test_early_detection_of_bad_call(self): |
---|
1489 | n/a | # Issue #22184 |
---|
1490 | n/a | with self.assertRaises(TypeError): |
---|
1491 | n/a | @functools.lru_cache |
---|
1492 | n/a | def f(): |
---|
1493 | n/a | pass |
---|
1494 | n/a | |
---|
1495 | n/a | def test_lru_method(self): |
---|
1496 | n/a | class X(int): |
---|
1497 | n/a | f_cnt = 0 |
---|
1498 | n/a | @self.module.lru_cache(2) |
---|
1499 | n/a | def f(self, x): |
---|
1500 | n/a | self.f_cnt += 1 |
---|
1501 | n/a | return x*10+self |
---|
1502 | n/a | a = X(5) |
---|
1503 | n/a | b = X(5) |
---|
1504 | n/a | c = X(7) |
---|
1505 | n/a | self.assertEqual(X.f.cache_info(), (0, 0, 2, 0)) |
---|
1506 | n/a | |
---|
1507 | n/a | for x in 1, 2, 2, 3, 1, 1, 1, 2, 3, 3: |
---|
1508 | n/a | self.assertEqual(a.f(x), x*10 + 5) |
---|
1509 | n/a | self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 0, 0)) |
---|
1510 | n/a | self.assertEqual(X.f.cache_info(), (4, 6, 2, 2)) |
---|
1511 | n/a | |
---|
1512 | n/a | for x in 1, 2, 1, 1, 1, 1, 3, 2, 2, 2: |
---|
1513 | n/a | self.assertEqual(b.f(x), x*10 + 5) |
---|
1514 | n/a | self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 4, 0)) |
---|
1515 | n/a | self.assertEqual(X.f.cache_info(), (10, 10, 2, 2)) |
---|
1516 | n/a | |
---|
1517 | n/a | for x in 2, 1, 1, 1, 1, 2, 1, 3, 2, 1: |
---|
1518 | n/a | self.assertEqual(c.f(x), x*10 + 7) |
---|
1519 | n/a | self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 4, 5)) |
---|
1520 | n/a | self.assertEqual(X.f.cache_info(), (15, 15, 2, 2)) |
---|
1521 | n/a | |
---|
1522 | n/a | self.assertEqual(a.f.cache_info(), X.f.cache_info()) |
---|
1523 | n/a | self.assertEqual(b.f.cache_info(), X.f.cache_info()) |
---|
1524 | n/a | self.assertEqual(c.f.cache_info(), X.f.cache_info()) |
---|
1525 | n/a | |
---|
1526 | n/a | def test_pickle(self): |
---|
1527 | n/a | cls = self.__class__ |
---|
1528 | n/a | for f in cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth: |
---|
1529 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
1530 | n/a | with self.subTest(proto=proto, func=f): |
---|
1531 | n/a | f_copy = pickle.loads(pickle.dumps(f, proto)) |
---|
1532 | n/a | self.assertIs(f_copy, f) |
---|
1533 | n/a | |
---|
1534 | n/a | def test_copy(self): |
---|
1535 | n/a | cls = self.__class__ |
---|
1536 | n/a | def orig(x, y): |
---|
1537 | n/a | return 3 * x + y |
---|
1538 | n/a | part = self.module.partial(orig, 2) |
---|
1539 | n/a | funcs = (cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth, |
---|
1540 | n/a | self.module.lru_cache(2)(part)) |
---|
1541 | n/a | for f in funcs: |
---|
1542 | n/a | with self.subTest(func=f): |
---|
1543 | n/a | f_copy = copy.copy(f) |
---|
1544 | n/a | self.assertIs(f_copy, f) |
---|
1545 | n/a | |
---|
1546 | n/a | def test_deepcopy(self): |
---|
1547 | n/a | cls = self.__class__ |
---|
1548 | n/a | def orig(x, y): |
---|
1549 | n/a | return 3 * x + y |
---|
1550 | n/a | part = self.module.partial(orig, 2) |
---|
1551 | n/a | funcs = (cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth, |
---|
1552 | n/a | self.module.lru_cache(2)(part)) |
---|
1553 | n/a | for f in funcs: |
---|
1554 | n/a | with self.subTest(func=f): |
---|
1555 | n/a | f_copy = copy.deepcopy(f) |
---|
1556 | n/a | self.assertIs(f_copy, f) |
---|
1557 | n/a | |
---|
1558 | n/a | |
---|
1559 | n/a | @py_functools.lru_cache() |
---|
1560 | n/a | def py_cached_func(x, y): |
---|
1561 | n/a | return 3 * x + y |
---|
1562 | n/a | |
---|
1563 | n/a | @c_functools.lru_cache() |
---|
1564 | n/a | def c_cached_func(x, y): |
---|
1565 | n/a | return 3 * x + y |
---|
1566 | n/a | |
---|
1567 | n/a | |
---|
1568 | n/a | class TestLRUPy(TestLRU, unittest.TestCase): |
---|
1569 | n/a | module = py_functools |
---|
1570 | n/a | cached_func = py_cached_func, |
---|
1571 | n/a | |
---|
1572 | n/a | @module.lru_cache() |
---|
1573 | n/a | def cached_meth(self, x, y): |
---|
1574 | n/a | return 3 * x + y |
---|
1575 | n/a | |
---|
1576 | n/a | @staticmethod |
---|
1577 | n/a | @module.lru_cache() |
---|
1578 | n/a | def cached_staticmeth(x, y): |
---|
1579 | n/a | return 3 * x + y |
---|
1580 | n/a | |
---|
1581 | n/a | |
---|
1582 | n/a | class TestLRUC(TestLRU, unittest.TestCase): |
---|
1583 | n/a | module = c_functools |
---|
1584 | n/a | cached_func = c_cached_func, |
---|
1585 | n/a | |
---|
1586 | n/a | @module.lru_cache() |
---|
1587 | n/a | def cached_meth(self, x, y): |
---|
1588 | n/a | return 3 * x + y |
---|
1589 | n/a | |
---|
1590 | n/a | @staticmethod |
---|
1591 | n/a | @module.lru_cache() |
---|
1592 | n/a | def cached_staticmeth(x, y): |
---|
1593 | n/a | return 3 * x + y |
---|
1594 | n/a | |
---|
1595 | n/a | |
---|
1596 | n/a | class TestSingleDispatch(unittest.TestCase): |
---|
1597 | n/a | def test_simple_overloads(self): |
---|
1598 | n/a | @functools.singledispatch |
---|
1599 | n/a | def g(obj): |
---|
1600 | n/a | return "base" |
---|
1601 | n/a | def g_int(i): |
---|
1602 | n/a | return "integer" |
---|
1603 | n/a | g.register(int, g_int) |
---|
1604 | n/a | self.assertEqual(g("str"), "base") |
---|
1605 | n/a | self.assertEqual(g(1), "integer") |
---|
1606 | n/a | self.assertEqual(g([1,2,3]), "base") |
---|
1607 | n/a | |
---|
1608 | n/a | def test_mro(self): |
---|
1609 | n/a | @functools.singledispatch |
---|
1610 | n/a | def g(obj): |
---|
1611 | n/a | return "base" |
---|
1612 | n/a | class A: |
---|
1613 | n/a | pass |
---|
1614 | n/a | class C(A): |
---|
1615 | n/a | pass |
---|
1616 | n/a | class B(A): |
---|
1617 | n/a | pass |
---|
1618 | n/a | class D(C, B): |
---|
1619 | n/a | pass |
---|
1620 | n/a | def g_A(a): |
---|
1621 | n/a | return "A" |
---|
1622 | n/a | def g_B(b): |
---|
1623 | n/a | return "B" |
---|
1624 | n/a | g.register(A, g_A) |
---|
1625 | n/a | g.register(B, g_B) |
---|
1626 | n/a | self.assertEqual(g(A()), "A") |
---|
1627 | n/a | self.assertEqual(g(B()), "B") |
---|
1628 | n/a | self.assertEqual(g(C()), "A") |
---|
1629 | n/a | self.assertEqual(g(D()), "B") |
---|
1630 | n/a | |
---|
1631 | n/a | def test_register_decorator(self): |
---|
1632 | n/a | @functools.singledispatch |
---|
1633 | n/a | def g(obj): |
---|
1634 | n/a | return "base" |
---|
1635 | n/a | @g.register(int) |
---|
1636 | n/a | def g_int(i): |
---|
1637 | n/a | return "int %s" % (i,) |
---|
1638 | n/a | self.assertEqual(g(""), "base") |
---|
1639 | n/a | self.assertEqual(g(12), "int 12") |
---|
1640 | n/a | self.assertIs(g.dispatch(int), g_int) |
---|
1641 | n/a | self.assertIs(g.dispatch(object), g.dispatch(str)) |
---|
1642 | n/a | # Note: in the assert above this is not g. |
---|
1643 | n/a | # @singledispatch returns the wrapper. |
---|
1644 | n/a | |
---|
1645 | n/a | def test_wrapping_attributes(self): |
---|
1646 | n/a | @functools.singledispatch |
---|
1647 | n/a | def g(obj): |
---|
1648 | n/a | "Simple test" |
---|
1649 | n/a | return "Test" |
---|
1650 | n/a | self.assertEqual(g.__name__, "g") |
---|
1651 | n/a | if sys.flags.optimize < 2: |
---|
1652 | n/a | self.assertEqual(g.__doc__, "Simple test") |
---|
1653 | n/a | |
---|
1654 | n/a | @unittest.skipUnless(decimal, 'requires _decimal') |
---|
1655 | n/a | @support.cpython_only |
---|
1656 | n/a | def test_c_classes(self): |
---|
1657 | n/a | @functools.singledispatch |
---|
1658 | n/a | def g(obj): |
---|
1659 | n/a | return "base" |
---|
1660 | n/a | @g.register(decimal.DecimalException) |
---|
1661 | n/a | def _(obj): |
---|
1662 | n/a | return obj.args |
---|
1663 | n/a | subn = decimal.Subnormal("Exponent < Emin") |
---|
1664 | n/a | rnd = decimal.Rounded("Number got rounded") |
---|
1665 | n/a | self.assertEqual(g(subn), ("Exponent < Emin",)) |
---|
1666 | n/a | self.assertEqual(g(rnd), ("Number got rounded",)) |
---|
1667 | n/a | @g.register(decimal.Subnormal) |
---|
1668 | n/a | def _(obj): |
---|
1669 | n/a | return "Too small to care." |
---|
1670 | n/a | self.assertEqual(g(subn), "Too small to care.") |
---|
1671 | n/a | self.assertEqual(g(rnd), ("Number got rounded",)) |
---|
1672 | n/a | |
---|
1673 | n/a | def test_compose_mro(self): |
---|
1674 | n/a | # None of the examples in this test depend on haystack ordering. |
---|
1675 | n/a | c = collections |
---|
1676 | n/a | mro = functools._compose_mro |
---|
1677 | n/a | bases = [c.Sequence, c.MutableMapping, c.Mapping, c.Set] |
---|
1678 | n/a | for haystack in permutations(bases): |
---|
1679 | n/a | m = mro(dict, haystack) |
---|
1680 | n/a | self.assertEqual(m, [dict, c.MutableMapping, c.Mapping, |
---|
1681 | n/a | c.Collection, c.Sized, c.Iterable, |
---|
1682 | n/a | c.Container, object]) |
---|
1683 | n/a | bases = [c.Container, c.Mapping, c.MutableMapping, c.OrderedDict] |
---|
1684 | n/a | for haystack in permutations(bases): |
---|
1685 | n/a | m = mro(c.ChainMap, haystack) |
---|
1686 | n/a | self.assertEqual(m, [c.ChainMap, c.MutableMapping, c.Mapping, |
---|
1687 | n/a | c.Collection, c.Sized, c.Iterable, |
---|
1688 | n/a | c.Container, object]) |
---|
1689 | n/a | |
---|
1690 | n/a | # If there's a generic function with implementations registered for |
---|
1691 | n/a | # both Sized and Container, passing a defaultdict to it results in an |
---|
1692 | n/a | # ambiguous dispatch which will cause a RuntimeError (see |
---|
1693 | n/a | # test_mro_conflicts). |
---|
1694 | n/a | bases = [c.Container, c.Sized, str] |
---|
1695 | n/a | for haystack in permutations(bases): |
---|
1696 | n/a | m = mro(c.defaultdict, [c.Sized, c.Container, str]) |
---|
1697 | n/a | self.assertEqual(m, [c.defaultdict, dict, c.Sized, c.Container, |
---|
1698 | n/a | object]) |
---|
1699 | n/a | |
---|
1700 | n/a | # MutableSequence below is registered directly on D. In other words, it |
---|
1701 | n/a | # precedes MutableMapping which means single dispatch will always |
---|
1702 | n/a | # choose MutableSequence here. |
---|
1703 | n/a | class D(c.defaultdict): |
---|
1704 | n/a | pass |
---|
1705 | n/a | c.MutableSequence.register(D) |
---|
1706 | n/a | bases = [c.MutableSequence, c.MutableMapping] |
---|
1707 | n/a | for haystack in permutations(bases): |
---|
1708 | n/a | m = mro(D, bases) |
---|
1709 | n/a | self.assertEqual(m, [D, c.MutableSequence, c.Sequence, c.Reversible, |
---|
1710 | n/a | c.defaultdict, dict, c.MutableMapping, c.Mapping, |
---|
1711 | n/a | c.Collection, c.Sized, c.Iterable, c.Container, |
---|
1712 | n/a | object]) |
---|
1713 | n/a | |
---|
1714 | n/a | # Container and Callable are registered on different base classes and |
---|
1715 | n/a | # a generic function supporting both should always pick the Callable |
---|
1716 | n/a | # implementation if a C instance is passed. |
---|
1717 | n/a | class C(c.defaultdict): |
---|
1718 | n/a | def __call__(self): |
---|
1719 | n/a | pass |
---|
1720 | n/a | bases = [c.Sized, c.Callable, c.Container, c.Mapping] |
---|
1721 | n/a | for haystack in permutations(bases): |
---|
1722 | n/a | m = mro(C, haystack) |
---|
1723 | n/a | self.assertEqual(m, [C, c.Callable, c.defaultdict, dict, c.Mapping, |
---|
1724 | n/a | c.Collection, c.Sized, c.Iterable, |
---|
1725 | n/a | c.Container, object]) |
---|
1726 | n/a | |
---|
1727 | n/a | def test_register_abc(self): |
---|
1728 | n/a | c = collections |
---|
1729 | n/a | d = {"a": "b"} |
---|
1730 | n/a | l = [1, 2, 3] |
---|
1731 | n/a | s = {object(), None} |
---|
1732 | n/a | f = frozenset(s) |
---|
1733 | n/a | t = (1, 2, 3) |
---|
1734 | n/a | @functools.singledispatch |
---|
1735 | n/a | def g(obj): |
---|
1736 | n/a | return "base" |
---|
1737 | n/a | self.assertEqual(g(d), "base") |
---|
1738 | n/a | self.assertEqual(g(l), "base") |
---|
1739 | n/a | self.assertEqual(g(s), "base") |
---|
1740 | n/a | self.assertEqual(g(f), "base") |
---|
1741 | n/a | self.assertEqual(g(t), "base") |
---|
1742 | n/a | g.register(c.Sized, lambda obj: "sized") |
---|
1743 | n/a | self.assertEqual(g(d), "sized") |
---|
1744 | n/a | self.assertEqual(g(l), "sized") |
---|
1745 | n/a | self.assertEqual(g(s), "sized") |
---|
1746 | n/a | self.assertEqual(g(f), "sized") |
---|
1747 | n/a | self.assertEqual(g(t), "sized") |
---|
1748 | n/a | g.register(c.MutableMapping, lambda obj: "mutablemapping") |
---|
1749 | n/a | self.assertEqual(g(d), "mutablemapping") |
---|
1750 | n/a | self.assertEqual(g(l), "sized") |
---|
1751 | n/a | self.assertEqual(g(s), "sized") |
---|
1752 | n/a | self.assertEqual(g(f), "sized") |
---|
1753 | n/a | self.assertEqual(g(t), "sized") |
---|
1754 | n/a | g.register(c.ChainMap, lambda obj: "chainmap") |
---|
1755 | n/a | self.assertEqual(g(d), "mutablemapping") # irrelevant ABCs registered |
---|
1756 | n/a | self.assertEqual(g(l), "sized") |
---|
1757 | n/a | self.assertEqual(g(s), "sized") |
---|
1758 | n/a | self.assertEqual(g(f), "sized") |
---|
1759 | n/a | self.assertEqual(g(t), "sized") |
---|
1760 | n/a | g.register(c.MutableSequence, lambda obj: "mutablesequence") |
---|
1761 | n/a | self.assertEqual(g(d), "mutablemapping") |
---|
1762 | n/a | self.assertEqual(g(l), "mutablesequence") |
---|
1763 | n/a | self.assertEqual(g(s), "sized") |
---|
1764 | n/a | self.assertEqual(g(f), "sized") |
---|
1765 | n/a | self.assertEqual(g(t), "sized") |
---|
1766 | n/a | g.register(c.MutableSet, lambda obj: "mutableset") |
---|
1767 | n/a | self.assertEqual(g(d), "mutablemapping") |
---|
1768 | n/a | self.assertEqual(g(l), "mutablesequence") |
---|
1769 | n/a | self.assertEqual(g(s), "mutableset") |
---|
1770 | n/a | self.assertEqual(g(f), "sized") |
---|
1771 | n/a | self.assertEqual(g(t), "sized") |
---|
1772 | n/a | g.register(c.Mapping, lambda obj: "mapping") |
---|
1773 | n/a | self.assertEqual(g(d), "mutablemapping") # not specific enough |
---|
1774 | n/a | self.assertEqual(g(l), "mutablesequence") |
---|
1775 | n/a | self.assertEqual(g(s), "mutableset") |
---|
1776 | n/a | self.assertEqual(g(f), "sized") |
---|
1777 | n/a | self.assertEqual(g(t), "sized") |
---|
1778 | n/a | g.register(c.Sequence, lambda obj: "sequence") |
---|
1779 | n/a | self.assertEqual(g(d), "mutablemapping") |
---|
1780 | n/a | self.assertEqual(g(l), "mutablesequence") |
---|
1781 | n/a | self.assertEqual(g(s), "mutableset") |
---|
1782 | n/a | self.assertEqual(g(f), "sized") |
---|
1783 | n/a | self.assertEqual(g(t), "sequence") |
---|
1784 | n/a | g.register(c.Set, lambda obj: "set") |
---|
1785 | n/a | self.assertEqual(g(d), "mutablemapping") |
---|
1786 | n/a | self.assertEqual(g(l), "mutablesequence") |
---|
1787 | n/a | self.assertEqual(g(s), "mutableset") |
---|
1788 | n/a | self.assertEqual(g(f), "set") |
---|
1789 | n/a | self.assertEqual(g(t), "sequence") |
---|
1790 | n/a | g.register(dict, lambda obj: "dict") |
---|
1791 | n/a | self.assertEqual(g(d), "dict") |
---|
1792 | n/a | self.assertEqual(g(l), "mutablesequence") |
---|
1793 | n/a | self.assertEqual(g(s), "mutableset") |
---|
1794 | n/a | self.assertEqual(g(f), "set") |
---|
1795 | n/a | self.assertEqual(g(t), "sequence") |
---|
1796 | n/a | g.register(list, lambda obj: "list") |
---|
1797 | n/a | self.assertEqual(g(d), "dict") |
---|
1798 | n/a | self.assertEqual(g(l), "list") |
---|
1799 | n/a | self.assertEqual(g(s), "mutableset") |
---|
1800 | n/a | self.assertEqual(g(f), "set") |
---|
1801 | n/a | self.assertEqual(g(t), "sequence") |
---|
1802 | n/a | g.register(set, lambda obj: "concrete-set") |
---|
1803 | n/a | self.assertEqual(g(d), "dict") |
---|
1804 | n/a | self.assertEqual(g(l), "list") |
---|
1805 | n/a | self.assertEqual(g(s), "concrete-set") |
---|
1806 | n/a | self.assertEqual(g(f), "set") |
---|
1807 | n/a | self.assertEqual(g(t), "sequence") |
---|
1808 | n/a | g.register(frozenset, lambda obj: "frozen-set") |
---|
1809 | n/a | self.assertEqual(g(d), "dict") |
---|
1810 | n/a | self.assertEqual(g(l), "list") |
---|
1811 | n/a | self.assertEqual(g(s), "concrete-set") |
---|
1812 | n/a | self.assertEqual(g(f), "frozen-set") |
---|
1813 | n/a | self.assertEqual(g(t), "sequence") |
---|
1814 | n/a | g.register(tuple, lambda obj: "tuple") |
---|
1815 | n/a | self.assertEqual(g(d), "dict") |
---|
1816 | n/a | self.assertEqual(g(l), "list") |
---|
1817 | n/a | self.assertEqual(g(s), "concrete-set") |
---|
1818 | n/a | self.assertEqual(g(f), "frozen-set") |
---|
1819 | n/a | self.assertEqual(g(t), "tuple") |
---|
1820 | n/a | |
---|
1821 | n/a | def test_c3_abc(self): |
---|
1822 | n/a | c = collections |
---|
1823 | n/a | mro = functools._c3_mro |
---|
1824 | n/a | class A(object): |
---|
1825 | n/a | pass |
---|
1826 | n/a | class B(A): |
---|
1827 | n/a | def __len__(self): |
---|
1828 | n/a | return 0 # implies Sized |
---|
1829 | n/a | @c.Container.register |
---|
1830 | n/a | class C(object): |
---|
1831 | n/a | pass |
---|
1832 | n/a | class D(object): |
---|
1833 | n/a | pass # unrelated |
---|
1834 | n/a | class X(D, C, B): |
---|
1835 | n/a | def __call__(self): |
---|
1836 | n/a | pass # implies Callable |
---|
1837 | n/a | expected = [X, c.Callable, D, C, c.Container, B, c.Sized, A, object] |
---|
1838 | n/a | for abcs in permutations([c.Sized, c.Callable, c.Container]): |
---|
1839 | n/a | self.assertEqual(mro(X, abcs=abcs), expected) |
---|
1840 | n/a | # unrelated ABCs don't appear in the resulting MRO |
---|
1841 | n/a | many_abcs = [c.Mapping, c.Sized, c.Callable, c.Container, c.Iterable] |
---|
1842 | n/a | self.assertEqual(mro(X, abcs=many_abcs), expected) |
---|
1843 | n/a | |
---|
1844 | n/a | def test_false_meta(self): |
---|
1845 | n/a | # see issue23572 |
---|
1846 | n/a | class MetaA(type): |
---|
1847 | n/a | def __len__(self): |
---|
1848 | n/a | return 0 |
---|
1849 | n/a | class A(metaclass=MetaA): |
---|
1850 | n/a | pass |
---|
1851 | n/a | class AA(A): |
---|
1852 | n/a | pass |
---|
1853 | n/a | @functools.singledispatch |
---|
1854 | n/a | def fun(a): |
---|
1855 | n/a | return 'base A' |
---|
1856 | n/a | @fun.register(A) |
---|
1857 | n/a | def _(a): |
---|
1858 | n/a | return 'fun A' |
---|
1859 | n/a | aa = AA() |
---|
1860 | n/a | self.assertEqual(fun(aa), 'fun A') |
---|
1861 | n/a | |
---|
1862 | n/a | def test_mro_conflicts(self): |
---|
1863 | n/a | c = collections |
---|
1864 | n/a | @functools.singledispatch |
---|
1865 | n/a | def g(arg): |
---|
1866 | n/a | return "base" |
---|
1867 | n/a | class O(c.Sized): |
---|
1868 | n/a | def __len__(self): |
---|
1869 | n/a | return 0 |
---|
1870 | n/a | o = O() |
---|
1871 | n/a | self.assertEqual(g(o), "base") |
---|
1872 | n/a | g.register(c.Iterable, lambda arg: "iterable") |
---|
1873 | n/a | g.register(c.Container, lambda arg: "container") |
---|
1874 | n/a | g.register(c.Sized, lambda arg: "sized") |
---|
1875 | n/a | g.register(c.Set, lambda arg: "set") |
---|
1876 | n/a | self.assertEqual(g(o), "sized") |
---|
1877 | n/a | c.Iterable.register(O) |
---|
1878 | n/a | self.assertEqual(g(o), "sized") # because it's explicitly in __mro__ |
---|
1879 | n/a | c.Container.register(O) |
---|
1880 | n/a | self.assertEqual(g(o), "sized") # see above: Sized is in __mro__ |
---|
1881 | n/a | c.Set.register(O) |
---|
1882 | n/a | self.assertEqual(g(o), "set") # because c.Set is a subclass of |
---|
1883 | n/a | # c.Sized and c.Container |
---|
1884 | n/a | class P: |
---|
1885 | n/a | pass |
---|
1886 | n/a | p = P() |
---|
1887 | n/a | self.assertEqual(g(p), "base") |
---|
1888 | n/a | c.Iterable.register(P) |
---|
1889 | n/a | self.assertEqual(g(p), "iterable") |
---|
1890 | n/a | c.Container.register(P) |
---|
1891 | n/a | with self.assertRaises(RuntimeError) as re_one: |
---|
1892 | n/a | g(p) |
---|
1893 | n/a | self.assertIn( |
---|
1894 | n/a | str(re_one.exception), |
---|
1895 | n/a | (("Ambiguous dispatch: <class 'collections.abc.Container'> " |
---|
1896 | n/a | "or <class 'collections.abc.Iterable'>"), |
---|
1897 | n/a | ("Ambiguous dispatch: <class 'collections.abc.Iterable'> " |
---|
1898 | n/a | "or <class 'collections.abc.Container'>")), |
---|
1899 | n/a | ) |
---|
1900 | n/a | class Q(c.Sized): |
---|
1901 | n/a | def __len__(self): |
---|
1902 | n/a | return 0 |
---|
1903 | n/a | q = Q() |
---|
1904 | n/a | self.assertEqual(g(q), "sized") |
---|
1905 | n/a | c.Iterable.register(Q) |
---|
1906 | n/a | self.assertEqual(g(q), "sized") # because it's explicitly in __mro__ |
---|
1907 | n/a | c.Set.register(Q) |
---|
1908 | n/a | self.assertEqual(g(q), "set") # because c.Set is a subclass of |
---|
1909 | n/a | # c.Sized and c.Iterable |
---|
1910 | n/a | @functools.singledispatch |
---|
1911 | n/a | def h(arg): |
---|
1912 | n/a | return "base" |
---|
1913 | n/a | @h.register(c.Sized) |
---|
1914 | n/a | def _(arg): |
---|
1915 | n/a | return "sized" |
---|
1916 | n/a | @h.register(c.Container) |
---|
1917 | n/a | def _(arg): |
---|
1918 | n/a | return "container" |
---|
1919 | n/a | # Even though Sized and Container are explicit bases of MutableMapping, |
---|
1920 | n/a | # this ABC is implicitly registered on defaultdict which makes all of |
---|
1921 | n/a | # MutableMapping's bases implicit as well from defaultdict's |
---|
1922 | n/a | # perspective. |
---|
1923 | n/a | with self.assertRaises(RuntimeError) as re_two: |
---|
1924 | n/a | h(c.defaultdict(lambda: 0)) |
---|
1925 | n/a | self.assertIn( |
---|
1926 | n/a | str(re_two.exception), |
---|
1927 | n/a | (("Ambiguous dispatch: <class 'collections.abc.Container'> " |
---|
1928 | n/a | "or <class 'collections.abc.Sized'>"), |
---|
1929 | n/a | ("Ambiguous dispatch: <class 'collections.abc.Sized'> " |
---|
1930 | n/a | "or <class 'collections.abc.Container'>")), |
---|
1931 | n/a | ) |
---|
1932 | n/a | class R(c.defaultdict): |
---|
1933 | n/a | pass |
---|
1934 | n/a | c.MutableSequence.register(R) |
---|
1935 | n/a | @functools.singledispatch |
---|
1936 | n/a | def i(arg): |
---|
1937 | n/a | return "base" |
---|
1938 | n/a | @i.register(c.MutableMapping) |
---|
1939 | n/a | def _(arg): |
---|
1940 | n/a | return "mapping" |
---|
1941 | n/a | @i.register(c.MutableSequence) |
---|
1942 | n/a | def _(arg): |
---|
1943 | n/a | return "sequence" |
---|
1944 | n/a | r = R() |
---|
1945 | n/a | self.assertEqual(i(r), "sequence") |
---|
1946 | n/a | class S: |
---|
1947 | n/a | pass |
---|
1948 | n/a | class T(S, c.Sized): |
---|
1949 | n/a | def __len__(self): |
---|
1950 | n/a | return 0 |
---|
1951 | n/a | t = T() |
---|
1952 | n/a | self.assertEqual(h(t), "sized") |
---|
1953 | n/a | c.Container.register(T) |
---|
1954 | n/a | self.assertEqual(h(t), "sized") # because it's explicitly in the MRO |
---|
1955 | n/a | class U: |
---|
1956 | n/a | def __len__(self): |
---|
1957 | n/a | return 0 |
---|
1958 | n/a | u = U() |
---|
1959 | n/a | self.assertEqual(h(u), "sized") # implicit Sized subclass inferred |
---|
1960 | n/a | # from the existence of __len__() |
---|
1961 | n/a | c.Container.register(U) |
---|
1962 | n/a | # There is no preference for registered versus inferred ABCs. |
---|
1963 | n/a | with self.assertRaises(RuntimeError) as re_three: |
---|
1964 | n/a | h(u) |
---|
1965 | n/a | self.assertIn( |
---|
1966 | n/a | str(re_three.exception), |
---|
1967 | n/a | (("Ambiguous dispatch: <class 'collections.abc.Container'> " |
---|
1968 | n/a | "or <class 'collections.abc.Sized'>"), |
---|
1969 | n/a | ("Ambiguous dispatch: <class 'collections.abc.Sized'> " |
---|
1970 | n/a | "or <class 'collections.abc.Container'>")), |
---|
1971 | n/a | ) |
---|
1972 | n/a | class V(c.Sized, S): |
---|
1973 | n/a | def __len__(self): |
---|
1974 | n/a | return 0 |
---|
1975 | n/a | @functools.singledispatch |
---|
1976 | n/a | def j(arg): |
---|
1977 | n/a | return "base" |
---|
1978 | n/a | @j.register(S) |
---|
1979 | n/a | def _(arg): |
---|
1980 | n/a | return "s" |
---|
1981 | n/a | @j.register(c.Container) |
---|
1982 | n/a | def _(arg): |
---|
1983 | n/a | return "container" |
---|
1984 | n/a | v = V() |
---|
1985 | n/a | self.assertEqual(j(v), "s") |
---|
1986 | n/a | c.Container.register(V) |
---|
1987 | n/a | self.assertEqual(j(v), "container") # because it ends up right after |
---|
1988 | n/a | # Sized in the MRO |
---|
1989 | n/a | |
---|
1990 | n/a | def test_cache_invalidation(self): |
---|
1991 | n/a | from collections import UserDict |
---|
1992 | n/a | class TracingDict(UserDict): |
---|
1993 | n/a | def __init__(self, *args, **kwargs): |
---|
1994 | n/a | super(TracingDict, self).__init__(*args, **kwargs) |
---|
1995 | n/a | self.set_ops = [] |
---|
1996 | n/a | self.get_ops = [] |
---|
1997 | n/a | def __getitem__(self, key): |
---|
1998 | n/a | result = self.data[key] |
---|
1999 | n/a | self.get_ops.append(key) |
---|
2000 | n/a | return result |
---|
2001 | n/a | def __setitem__(self, key, value): |
---|
2002 | n/a | self.set_ops.append(key) |
---|
2003 | n/a | self.data[key] = value |
---|
2004 | n/a | def clear(self): |
---|
2005 | n/a | self.data.clear() |
---|
2006 | n/a | _orig_wkd = functools.WeakKeyDictionary |
---|
2007 | n/a | td = TracingDict() |
---|
2008 | n/a | functools.WeakKeyDictionary = lambda: td |
---|
2009 | n/a | c = collections |
---|
2010 | n/a | @functools.singledispatch |
---|
2011 | n/a | def g(arg): |
---|
2012 | n/a | return "base" |
---|
2013 | n/a | d = {} |
---|
2014 | n/a | l = [] |
---|
2015 | n/a | self.assertEqual(len(td), 0) |
---|
2016 | n/a | self.assertEqual(g(d), "base") |
---|
2017 | n/a | self.assertEqual(len(td), 1) |
---|
2018 | n/a | self.assertEqual(td.get_ops, []) |
---|
2019 | n/a | self.assertEqual(td.set_ops, [dict]) |
---|
2020 | n/a | self.assertEqual(td.data[dict], g.registry[object]) |
---|
2021 | n/a | self.assertEqual(g(l), "base") |
---|
2022 | n/a | self.assertEqual(len(td), 2) |
---|
2023 | n/a | self.assertEqual(td.get_ops, []) |
---|
2024 | n/a | self.assertEqual(td.set_ops, [dict, list]) |
---|
2025 | n/a | self.assertEqual(td.data[dict], g.registry[object]) |
---|
2026 | n/a | self.assertEqual(td.data[list], g.registry[object]) |
---|
2027 | n/a | self.assertEqual(td.data[dict], td.data[list]) |
---|
2028 | n/a | self.assertEqual(g(l), "base") |
---|
2029 | n/a | self.assertEqual(g(d), "base") |
---|
2030 | n/a | self.assertEqual(td.get_ops, [list, dict]) |
---|
2031 | n/a | self.assertEqual(td.set_ops, [dict, list]) |
---|
2032 | n/a | g.register(list, lambda arg: "list") |
---|
2033 | n/a | self.assertEqual(td.get_ops, [list, dict]) |
---|
2034 | n/a | self.assertEqual(len(td), 0) |
---|
2035 | n/a | self.assertEqual(g(d), "base") |
---|
2036 | n/a | self.assertEqual(len(td), 1) |
---|
2037 | n/a | self.assertEqual(td.get_ops, [list, dict]) |
---|
2038 | n/a | self.assertEqual(td.set_ops, [dict, list, dict]) |
---|
2039 | n/a | self.assertEqual(td.data[dict], |
---|
2040 | n/a | functools._find_impl(dict, g.registry)) |
---|
2041 | n/a | self.assertEqual(g(l), "list") |
---|
2042 | n/a | self.assertEqual(len(td), 2) |
---|
2043 | n/a | self.assertEqual(td.get_ops, [list, dict]) |
---|
2044 | n/a | self.assertEqual(td.set_ops, [dict, list, dict, list]) |
---|
2045 | n/a | self.assertEqual(td.data[list], |
---|
2046 | n/a | functools._find_impl(list, g.registry)) |
---|
2047 | n/a | class X: |
---|
2048 | n/a | pass |
---|
2049 | n/a | c.MutableMapping.register(X) # Will not invalidate the cache, |
---|
2050 | n/a | # not using ABCs yet. |
---|
2051 | n/a | self.assertEqual(g(d), "base") |
---|
2052 | n/a | self.assertEqual(g(l), "list") |
---|
2053 | n/a | self.assertEqual(td.get_ops, [list, dict, dict, list]) |
---|
2054 | n/a | self.assertEqual(td.set_ops, [dict, list, dict, list]) |
---|
2055 | n/a | g.register(c.Sized, lambda arg: "sized") |
---|
2056 | n/a | self.assertEqual(len(td), 0) |
---|
2057 | n/a | self.assertEqual(g(d), "sized") |
---|
2058 | n/a | self.assertEqual(len(td), 1) |
---|
2059 | n/a | self.assertEqual(td.get_ops, [list, dict, dict, list]) |
---|
2060 | n/a | self.assertEqual(td.set_ops, [dict, list, dict, list, dict]) |
---|
2061 | n/a | self.assertEqual(g(l), "list") |
---|
2062 | n/a | self.assertEqual(len(td), 2) |
---|
2063 | n/a | self.assertEqual(td.get_ops, [list, dict, dict, list]) |
---|
2064 | n/a | self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list]) |
---|
2065 | n/a | self.assertEqual(g(l), "list") |
---|
2066 | n/a | self.assertEqual(g(d), "sized") |
---|
2067 | n/a | self.assertEqual(td.get_ops, [list, dict, dict, list, list, dict]) |
---|
2068 | n/a | self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list]) |
---|
2069 | n/a | g.dispatch(list) |
---|
2070 | n/a | g.dispatch(dict) |
---|
2071 | n/a | self.assertEqual(td.get_ops, [list, dict, dict, list, list, dict, |
---|
2072 | n/a | list, dict]) |
---|
2073 | n/a | self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list]) |
---|
2074 | n/a | c.MutableSet.register(X) # Will invalidate the cache. |
---|
2075 | n/a | self.assertEqual(len(td), 2) # Stale cache. |
---|
2076 | n/a | self.assertEqual(g(l), "list") |
---|
2077 | n/a | self.assertEqual(len(td), 1) |
---|
2078 | n/a | g.register(c.MutableMapping, lambda arg: "mutablemapping") |
---|
2079 | n/a | self.assertEqual(len(td), 0) |
---|
2080 | n/a | self.assertEqual(g(d), "mutablemapping") |
---|
2081 | n/a | self.assertEqual(len(td), 1) |
---|
2082 | n/a | self.assertEqual(g(l), "list") |
---|
2083 | n/a | self.assertEqual(len(td), 2) |
---|
2084 | n/a | g.register(dict, lambda arg: "dict") |
---|
2085 | n/a | self.assertEqual(g(d), "dict") |
---|
2086 | n/a | self.assertEqual(g(l), "list") |
---|
2087 | n/a | g._clear_cache() |
---|
2088 | n/a | self.assertEqual(len(td), 0) |
---|
2089 | n/a | functools.WeakKeyDictionary = _orig_wkd |
---|
2090 | n/a | |
---|
2091 | n/a | |
---|
2092 | n/a | if __name__ == '__main__': |
---|
2093 | n/a | unittest.main() |
---|