Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1 | import functools |
Raymond Hettinger | 003be52 | 2011-05-03 11:01:32 -0700 | [diff] [blame] | 2 | import collections |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 3 | import sys |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 4 | import unittest |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 5 | from test import support |
Raymond Hettinger | c8b6d1b | 2005-03-08 06:14:50 +0000 | [diff] [blame] | 6 | from weakref import proxy |
Jack Diederich | e0cbd69 | 2009-04-01 04:27:09 +0000 | [diff] [blame] | 7 | import pickle |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 8 | from random import choice |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 9 | |
| 10 | @staticmethod |
| 11 | def PythonPartial(func, *args, **keywords): |
| 12 | 'Pure Python approximation of partial()' |
| 13 | def newfunc(*fargs, **fkeywords): |
| 14 | newkeywords = keywords.copy() |
| 15 | newkeywords.update(fkeywords) |
| 16 | return func(*(args + fargs), **newkeywords) |
| 17 | newfunc.func = func |
| 18 | newfunc.args = args |
| 19 | newfunc.keywords = keywords |
| 20 | return newfunc |
| 21 | |
| 22 | def capture(*args, **kw): |
| 23 | """capture all positional and keyword arguments""" |
| 24 | return args, kw |
| 25 | |
Jack Diederich | e0cbd69 | 2009-04-01 04:27:09 +0000 | [diff] [blame] | 26 | def signature(part): |
| 27 | """ return the signature of a partial object """ |
| 28 | return (part.func, part.args, part.keywords, part.__dict__) |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 29 | |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 30 | class TestPartial(unittest.TestCase): |
| 31 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 32 | thetype = functools.partial |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 33 | |
| 34 | def test_basic_examples(self): |
| 35 | p = self.thetype(capture, 1, 2, a=10, b=20) |
| 36 | self.assertEqual(p(3, 4, b=30, c=40), |
| 37 | ((1, 2, 3, 4), dict(a=10, b=30, c=40))) |
| 38 | p = self.thetype(map, lambda x: x*10) |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 39 | self.assertEqual(list(p([1,2,3,4])), [10, 20, 30, 40]) |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 40 | |
| 41 | def test_attributes(self): |
| 42 | p = self.thetype(capture, 1, 2, a=10, b=20) |
| 43 | # attributes should be readable |
| 44 | self.assertEqual(p.func, capture) |
| 45 | self.assertEqual(p.args, (1, 2)) |
| 46 | self.assertEqual(p.keywords, dict(a=10, b=20)) |
| 47 | # attributes should not be writable |
| 48 | if not isinstance(self.thetype, type): |
| 49 | return |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 50 | self.assertRaises(AttributeError, setattr, p, 'func', map) |
| 51 | self.assertRaises(AttributeError, setattr, p, 'args', (1, 2)) |
| 52 | self.assertRaises(AttributeError, setattr, p, 'keywords', dict(a=1, b=2)) |
| 53 | |
| 54 | p = self.thetype(hex) |
| 55 | try: |
| 56 | del p.__dict__ |
| 57 | except TypeError: |
| 58 | pass |
| 59 | else: |
| 60 | self.fail('partial object allowed __dict__ to be deleted') |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 61 | |
| 62 | def test_argument_checking(self): |
| 63 | self.assertRaises(TypeError, self.thetype) # need at least a func arg |
| 64 | try: |
| 65 | self.thetype(2)() |
| 66 | except TypeError: |
| 67 | pass |
| 68 | else: |
| 69 | self.fail('First arg not checked for callability') |
| 70 | |
| 71 | def test_protection_of_callers_dict_argument(self): |
| 72 | # a caller's dictionary should not be altered by partial |
| 73 | def func(a=10, b=20): |
| 74 | return a |
| 75 | d = {'a':3} |
| 76 | p = self.thetype(func, a=5) |
| 77 | self.assertEqual(p(**d), 3) |
| 78 | self.assertEqual(d, {'a':3}) |
| 79 | p(b=7) |
| 80 | self.assertEqual(d, {'a':3}) |
| 81 | |
| 82 | def test_arg_combinations(self): |
| 83 | # exercise special code paths for zero args in either partial |
| 84 | # object or the caller |
| 85 | p = self.thetype(capture) |
| 86 | self.assertEqual(p(), ((), {})) |
| 87 | self.assertEqual(p(1,2), ((1,2), {})) |
| 88 | p = self.thetype(capture, 1, 2) |
| 89 | self.assertEqual(p(), ((1,2), {})) |
| 90 | self.assertEqual(p(3,4), ((1,2,3,4), {})) |
| 91 | |
| 92 | def test_kw_combinations(self): |
| 93 | # exercise special code paths for no keyword args in |
| 94 | # either the partial object or the caller |
| 95 | p = self.thetype(capture) |
| 96 | self.assertEqual(p(), ((), {})) |
| 97 | self.assertEqual(p(a=1), ((), {'a':1})) |
| 98 | p = self.thetype(capture, a=1) |
| 99 | self.assertEqual(p(), ((), {'a':1})) |
| 100 | self.assertEqual(p(b=2), ((), {'a':1, 'b':2})) |
| 101 | # keyword args in the call override those in the partial object |
| 102 | self.assertEqual(p(a=3, b=2), ((), {'a':3, 'b':2})) |
| 103 | |
| 104 | def test_positional(self): |
| 105 | # make sure positional arguments are captured correctly |
| 106 | for args in [(), (0,), (0,1), (0,1,2), (0,1,2,3)]: |
| 107 | p = self.thetype(capture, *args) |
| 108 | expected = args + ('x',) |
| 109 | got, empty = p('x') |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 110 | self.assertTrue(expected == got and empty == {}) |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 111 | |
| 112 | def test_keyword(self): |
| 113 | # make sure keyword arguments are captured correctly |
| 114 | for a in ['a', 0, None, 3.5]: |
| 115 | p = self.thetype(capture, a=a) |
| 116 | expected = {'a':a,'x':None} |
| 117 | empty, got = p(x=None) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 118 | self.assertTrue(expected == got and empty == ()) |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 119 | |
| 120 | def test_no_side_effects(self): |
| 121 | # make sure there are no side effects that affect subsequent calls |
| 122 | p = self.thetype(capture, 0, a=1) |
| 123 | args1, kw1 = p(1, b=2) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 124 | self.assertTrue(args1 == (0,1) and kw1 == {'a':1,'b':2}) |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 125 | args2, kw2 = p() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 126 | self.assertTrue(args2 == (0,) and kw2 == {'a':1}) |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 127 | |
| 128 | def test_error_propagation(self): |
| 129 | def f(x, y): |
| 130 | x / y |
| 131 | self.assertRaises(ZeroDivisionError, self.thetype(f, 1, 0)) |
| 132 | self.assertRaises(ZeroDivisionError, self.thetype(f, 1), 0) |
| 133 | self.assertRaises(ZeroDivisionError, self.thetype(f), 1, 0) |
| 134 | self.assertRaises(ZeroDivisionError, self.thetype(f, y=0), 1) |
| 135 | |
Raymond Hettinger | c8b6d1b | 2005-03-08 06:14:50 +0000 | [diff] [blame] | 136 | def test_weakref(self): |
| 137 | f = self.thetype(int, base=16) |
| 138 | p = proxy(f) |
| 139 | self.assertEqual(f.func, p.func) |
| 140 | f = None |
| 141 | self.assertRaises(ReferenceError, getattr, p, 'func') |
| 142 | |
Raymond Hettinger | 26e512a | 2005-03-11 06:48:49 +0000 | [diff] [blame] | 143 | def test_with_bound_and_unbound_methods(self): |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 144 | data = list(map(str, range(10))) |
Raymond Hettinger | 26e512a | 2005-03-11 06:48:49 +0000 | [diff] [blame] | 145 | join = self.thetype(str.join, '') |
| 146 | self.assertEqual(join(data), '0123456789') |
| 147 | join = self.thetype(''.join) |
| 148 | self.assertEqual(join(data), '0123456789') |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 149 | |
Alexander Belopolsky | 41e422a | 2010-12-01 20:05:49 +0000 | [diff] [blame] | 150 | def test_repr(self): |
| 151 | args = (object(), object()) |
| 152 | args_repr = ', '.join(repr(a) for a in args) |
| 153 | kwargs = {'a': object(), 'b': object()} |
| 154 | kwargs_repr = ', '.join("%s=%r" % (k, v) for k, v in kwargs.items()) |
| 155 | if self.thetype is functools.partial: |
| 156 | name = 'functools.partial' |
| 157 | else: |
| 158 | name = self.thetype.__name__ |
| 159 | |
| 160 | f = self.thetype(capture) |
| 161 | self.assertEqual('{}({!r})'.format(name, capture), |
| 162 | repr(f)) |
| 163 | |
| 164 | f = self.thetype(capture, *args) |
| 165 | self.assertEqual('{}({!r}, {})'.format(name, capture, args_repr), |
| 166 | repr(f)) |
| 167 | |
| 168 | f = self.thetype(capture, **kwargs) |
| 169 | self.assertEqual('{}({!r}, {})'.format(name, capture, kwargs_repr), |
| 170 | repr(f)) |
| 171 | |
| 172 | f = self.thetype(capture, *args, **kwargs) |
| 173 | self.assertEqual('{}({!r}, {}, {})'.format(name, capture, args_repr, kwargs_repr), |
| 174 | repr(f)) |
| 175 | |
Jack Diederich | e0cbd69 | 2009-04-01 04:27:09 +0000 | [diff] [blame] | 176 | def test_pickle(self): |
| 177 | f = self.thetype(signature, 'asdf', bar=True) |
| 178 | f.add_something_to__dict__ = True |
| 179 | f_copy = pickle.loads(pickle.dumps(f)) |
| 180 | self.assertEqual(signature(f), signature(f_copy)) |
| 181 | |
Serhiy Storchaka | 19c4e0d | 2013-02-04 12:47:24 +0200 | [diff] [blame] | 182 | # Issue 6083: Reference counting bug |
| 183 | def test_setstate_refcount(self): |
| 184 | class BadSequence: |
| 185 | def __len__(self): |
| 186 | return 4 |
| 187 | def __getitem__(self, key): |
| 188 | if key == 0: |
| 189 | return max |
| 190 | elif key == 1: |
| 191 | return tuple(range(1000000)) |
| 192 | elif key in (2, 3): |
| 193 | return {} |
| 194 | raise IndexError |
| 195 | |
| 196 | f = self.thetype(object) |
| 197 | self.assertRaisesRegex(SystemError, |
| 198 | "new style getargs format but argument is not a tuple", |
| 199 | f.__setstate__, BadSequence()) |
| 200 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 201 | class PartialSubclass(functools.partial): |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 202 | pass |
| 203 | |
| 204 | class TestPartialSubclass(TestPartial): |
| 205 | |
| 206 | thetype = PartialSubclass |
| 207 | |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 208 | class TestPythonPartial(TestPartial): |
| 209 | |
| 210 | thetype = PythonPartial |
| 211 | |
Alexander Belopolsky | 41e422a | 2010-12-01 20:05:49 +0000 | [diff] [blame] | 212 | # the python version hasn't a nice repr |
| 213 | def test_repr(self): pass |
| 214 | |
Jack Diederich | e0cbd69 | 2009-04-01 04:27:09 +0000 | [diff] [blame] | 215 | # the python version isn't picklable |
| 216 | def test_pickle(self): pass |
Serhiy Storchaka | 19c4e0d | 2013-02-04 12:47:24 +0200 | [diff] [blame] | 217 | def test_setstate_refcount(self): pass |
Jack Diederich | e0cbd69 | 2009-04-01 04:27:09 +0000 | [diff] [blame] | 218 | |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 219 | class TestUpdateWrapper(unittest.TestCase): |
| 220 | |
| 221 | def check_wrapper(self, wrapper, wrapped, |
| 222 | assigned=functools.WRAPPER_ASSIGNMENTS, |
| 223 | updated=functools.WRAPPER_UPDATES): |
| 224 | # Check attributes were assigned |
| 225 | for name in assigned: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 226 | self.assertTrue(getattr(wrapper, name) is getattr(wrapped, name)) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 227 | # Check attributes were updated |
| 228 | for name in updated: |
| 229 | wrapper_attr = getattr(wrapper, name) |
| 230 | wrapped_attr = getattr(wrapped, name) |
| 231 | for key in wrapped_attr: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 232 | self.assertTrue(wrapped_attr[key] is wrapper_attr[key]) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 233 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 234 | def _default_update(self): |
Antoine Pitrou | 560f764 | 2010-08-04 18:28:02 +0000 | [diff] [blame] | 235 | def f(a:'This is a new annotation'): |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 236 | """This is a test""" |
| 237 | pass |
| 238 | f.attr = 'This is also a test' |
Antoine Pitrou | 560f764 | 2010-08-04 18:28:02 +0000 | [diff] [blame] | 239 | def wrapper(b:'This is the prior annotation'): |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 240 | pass |
| 241 | functools.update_wrapper(wrapper, f) |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 242 | return wrapper, f |
| 243 | |
| 244 | def test_default_update(self): |
| 245 | wrapper, f = self._default_update() |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 246 | self.check_wrapper(wrapper, f) |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 247 | self.assertIs(wrapper.__wrapped__, f) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 248 | self.assertEqual(wrapper.__name__, 'f') |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 249 | self.assertEqual(wrapper.__qualname__, f.__qualname__) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 250 | self.assertEqual(wrapper.attr, 'This is also a test') |
Antoine Pitrou | 560f764 | 2010-08-04 18:28:02 +0000 | [diff] [blame] | 251 | self.assertEqual(wrapper.__annotations__['a'], 'This is a new annotation') |
| 252 | self.assertNotIn('b', wrapper.__annotations__) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 253 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 254 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 255 | "Docstrings are omitted with -O2 and above") |
| 256 | def test_default_update_doc(self): |
| 257 | wrapper, f = self._default_update() |
| 258 | self.assertEqual(wrapper.__doc__, 'This is a test') |
| 259 | |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 260 | def test_no_update(self): |
| 261 | def f(): |
| 262 | """This is a test""" |
| 263 | pass |
| 264 | f.attr = 'This is also a test' |
| 265 | def wrapper(): |
| 266 | pass |
| 267 | functools.update_wrapper(wrapper, f, (), ()) |
| 268 | self.check_wrapper(wrapper, f, (), ()) |
| 269 | self.assertEqual(wrapper.__name__, 'wrapper') |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 270 | self.assertNotEqual(wrapper.__qualname__, f.__qualname__) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 271 | self.assertEqual(wrapper.__doc__, None) |
Antoine Pitrou | 560f764 | 2010-08-04 18:28:02 +0000 | [diff] [blame] | 272 | self.assertEqual(wrapper.__annotations__, {}) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 273 | self.assertFalse(hasattr(wrapper, 'attr')) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 274 | |
| 275 | def test_selective_update(self): |
| 276 | def f(): |
| 277 | pass |
| 278 | f.attr = 'This is a different test' |
| 279 | f.dict_attr = dict(a=1, b=2, c=3) |
| 280 | def wrapper(): |
| 281 | pass |
| 282 | wrapper.dict_attr = {} |
| 283 | assign = ('attr',) |
| 284 | update = ('dict_attr',) |
| 285 | functools.update_wrapper(wrapper, f, assign, update) |
| 286 | self.check_wrapper(wrapper, f, assign, update) |
| 287 | self.assertEqual(wrapper.__name__, 'wrapper') |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 288 | self.assertNotEqual(wrapper.__qualname__, f.__qualname__) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 289 | self.assertEqual(wrapper.__doc__, None) |
| 290 | self.assertEqual(wrapper.attr, 'This is a different test') |
| 291 | self.assertEqual(wrapper.dict_attr, f.dict_attr) |
| 292 | |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 293 | def test_missing_attributes(self): |
| 294 | def f(): |
| 295 | pass |
| 296 | def wrapper(): |
| 297 | pass |
| 298 | wrapper.dict_attr = {} |
| 299 | assign = ('attr',) |
| 300 | update = ('dict_attr',) |
| 301 | # Missing attributes on wrapped object are ignored |
| 302 | functools.update_wrapper(wrapper, f, assign, update) |
| 303 | self.assertNotIn('attr', wrapper.__dict__) |
| 304 | self.assertEqual(wrapper.dict_attr, {}) |
| 305 | # Wrapper must have expected attributes for updating |
| 306 | del wrapper.dict_attr |
| 307 | with self.assertRaises(AttributeError): |
| 308 | functools.update_wrapper(wrapper, f, assign, update) |
| 309 | wrapper.dict_attr = 1 |
| 310 | with self.assertRaises(AttributeError): |
| 311 | functools.update_wrapper(wrapper, f, assign, update) |
| 312 | |
Serhiy Storchaka | 9d0add0 | 2013-01-27 19:47:45 +0200 | [diff] [blame] | 313 | @support.requires_docstrings |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 314 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 315 | "Docstrings are omitted with -O2 and above") |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 316 | def test_builtin_update(self): |
| 317 | # Test for bug #1576241 |
| 318 | def wrapper(): |
| 319 | pass |
| 320 | functools.update_wrapper(wrapper, max) |
| 321 | self.assertEqual(wrapper.__name__, 'max') |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 322 | self.assertTrue(wrapper.__doc__.startswith('max(')) |
Antoine Pitrou | 560f764 | 2010-08-04 18:28:02 +0000 | [diff] [blame] | 323 | self.assertEqual(wrapper.__annotations__, {}) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 324 | |
| 325 | class TestWraps(TestUpdateWrapper): |
| 326 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 327 | def _default_update(self): |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 328 | def f(): |
| 329 | """This is a test""" |
| 330 | pass |
| 331 | f.attr = 'This is also a test' |
| 332 | @functools.wraps(f) |
| 333 | def wrapper(): |
| 334 | pass |
| 335 | self.check_wrapper(wrapper, f) |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 336 | return wrapper, f |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 337 | |
| 338 | def test_default_update(self): |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 339 | wrapper, f = self._default_update() |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 340 | self.assertEqual(wrapper.__name__, 'f') |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 341 | self.assertEqual(wrapper.__qualname__, f.__qualname__) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 342 | self.assertEqual(wrapper.attr, 'This is also a test') |
| 343 | |
Serhiy Storchaka | 8e0ae2a | 2013-01-28 13:25:44 +0200 | [diff] [blame] | 344 | @unittest.skipIf(sys.flags.optimize >= 2, |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 345 | "Docstrings are omitted with -O2 and above") |
| 346 | def test_default_update_doc(self): |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 347 | wrapper, _ = self._default_update() |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 348 | self.assertEqual(wrapper.__doc__, 'This is a test') |
| 349 | |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 350 | def test_no_update(self): |
| 351 | def f(): |
| 352 | """This is a test""" |
| 353 | pass |
| 354 | f.attr = 'This is also a test' |
| 355 | @functools.wraps(f, (), ()) |
| 356 | def wrapper(): |
| 357 | pass |
| 358 | self.check_wrapper(wrapper, f, (), ()) |
| 359 | self.assertEqual(wrapper.__name__, 'wrapper') |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 360 | self.assertNotEqual(wrapper.__qualname__, f.__qualname__) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 361 | self.assertEqual(wrapper.__doc__, None) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 362 | self.assertFalse(hasattr(wrapper, 'attr')) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 363 | |
| 364 | def test_selective_update(self): |
| 365 | def f(): |
| 366 | pass |
| 367 | f.attr = 'This is a different test' |
| 368 | f.dict_attr = dict(a=1, b=2, c=3) |
| 369 | def add_dict_attr(f): |
| 370 | f.dict_attr = {} |
| 371 | return f |
| 372 | assign = ('attr',) |
| 373 | update = ('dict_attr',) |
| 374 | @functools.wraps(f, assign, update) |
| 375 | @add_dict_attr |
| 376 | def wrapper(): |
| 377 | pass |
| 378 | self.check_wrapper(wrapper, f, assign, update) |
| 379 | self.assertEqual(wrapper.__name__, 'wrapper') |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 380 | self.assertNotEqual(wrapper.__qualname__, f.__qualname__) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 381 | self.assertEqual(wrapper.__doc__, None) |
| 382 | self.assertEqual(wrapper.attr, 'This is a different test') |
| 383 | self.assertEqual(wrapper.dict_attr, f.dict_attr) |
| 384 | |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 385 | class TestReduce(unittest.TestCase): |
| 386 | func = functools.reduce |
| 387 | |
| 388 | def test_reduce(self): |
| 389 | class Squares: |
| 390 | def __init__(self, max): |
| 391 | self.max = max |
| 392 | self.sofar = [] |
| 393 | |
| 394 | def __len__(self): |
| 395 | return len(self.sofar) |
| 396 | |
| 397 | def __getitem__(self, i): |
| 398 | if not 0 <= i < self.max: raise IndexError |
| 399 | n = len(self.sofar) |
| 400 | while n <= i: |
| 401 | self.sofar.append(n*n) |
| 402 | n += 1 |
| 403 | return self.sofar[i] |
Alexander Belopolsky | e29e6bf | 2010-08-16 18:55:46 +0000 | [diff] [blame] | 404 | def add(x, y): |
| 405 | return x + y |
| 406 | self.assertEqual(self.func(add, ['a', 'b', 'c'], ''), 'abc') |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 407 | self.assertEqual( |
Alexander Belopolsky | e29e6bf | 2010-08-16 18:55:46 +0000 | [diff] [blame] | 408 | self.func(add, [['a', 'c'], [], ['d', 'w']], []), |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 409 | ['a','c','d','w'] |
| 410 | ) |
| 411 | self.assertEqual(self.func(lambda x, y: x*y, range(2,8), 1), 5040) |
| 412 | self.assertEqual( |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 413 | self.func(lambda x, y: x*y, range(2,21), 1), |
| 414 | 2432902008176640000 |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 415 | ) |
Alexander Belopolsky | e29e6bf | 2010-08-16 18:55:46 +0000 | [diff] [blame] | 416 | self.assertEqual(self.func(add, Squares(10)), 285) |
| 417 | self.assertEqual(self.func(add, Squares(10), 0), 285) |
| 418 | self.assertEqual(self.func(add, Squares(0), 0), 0) |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 419 | self.assertRaises(TypeError, self.func) |
| 420 | self.assertRaises(TypeError, self.func, 42, 42) |
| 421 | self.assertRaises(TypeError, self.func, 42, 42, 42) |
| 422 | self.assertEqual(self.func(42, "1"), "1") # func is never called with one item |
| 423 | self.assertEqual(self.func(42, "", "1"), "1") # func is never called with one item |
| 424 | self.assertRaises(TypeError, self.func, 42, (42, 42)) |
Alexander Belopolsky | e29e6bf | 2010-08-16 18:55:46 +0000 | [diff] [blame] | 425 | self.assertRaises(TypeError, self.func, add, []) # arg 2 must not be empty sequence with no initial value |
| 426 | self.assertRaises(TypeError, self.func, add, "") |
| 427 | self.assertRaises(TypeError, self.func, add, ()) |
| 428 | self.assertRaises(TypeError, self.func, add, object()) |
| 429 | |
| 430 | class TestFailingIter: |
| 431 | def __iter__(self): |
| 432 | raise RuntimeError |
| 433 | self.assertRaises(RuntimeError, self.func, add, TestFailingIter()) |
| 434 | |
| 435 | self.assertEqual(self.func(add, [], None), None) |
| 436 | self.assertEqual(self.func(add, [], 42), 42) |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 437 | |
| 438 | class BadSeq: |
| 439 | def __getitem__(self, index): |
| 440 | raise ValueError |
| 441 | self.assertRaises(ValueError, self.func, 42, BadSeq()) |
| 442 | |
| 443 | # Test reduce()'s use of iterators. |
| 444 | def test_iterator_usage(self): |
| 445 | class SequenceClass: |
| 446 | def __init__(self, n): |
| 447 | self.n = n |
| 448 | def __getitem__(self, i): |
| 449 | if 0 <= i < self.n: |
| 450 | return i |
| 451 | else: |
| 452 | raise IndexError |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 453 | |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 454 | from operator import add |
| 455 | self.assertEqual(self.func(add, SequenceClass(5)), 10) |
| 456 | self.assertEqual(self.func(add, SequenceClass(5), 42), 52) |
| 457 | self.assertRaises(TypeError, self.func, add, SequenceClass(0)) |
| 458 | self.assertEqual(self.func(add, SequenceClass(0), 42), 42) |
| 459 | self.assertEqual(self.func(add, SequenceClass(1)), 0) |
| 460 | self.assertEqual(self.func(add, SequenceClass(1), 42), 42) |
| 461 | |
| 462 | d = {"one": 1, "two": 2, "three": 3} |
| 463 | self.assertEqual(self.func(add, d), "".join(d.keys())) |
| 464 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 465 | class TestCmpToKey(unittest.TestCase): |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 466 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 467 | def test_cmp_to_key(self): |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 468 | def cmp1(x, y): |
| 469 | return (x > y) - (x < y) |
| 470 | key = functools.cmp_to_key(cmp1) |
| 471 | self.assertEqual(key(3), key(3)) |
| 472 | self.assertGreater(key(3), key(1)) |
| 473 | def cmp2(x, y): |
| 474 | return int(x) - int(y) |
| 475 | key = functools.cmp_to_key(cmp2) |
| 476 | self.assertEqual(key(4.0), key('4')) |
| 477 | self.assertLess(key(2), key('35')) |
| 478 | |
| 479 | def test_cmp_to_key_arguments(self): |
| 480 | def cmp1(x, y): |
| 481 | return (x > y) - (x < y) |
| 482 | key = functools.cmp_to_key(mycmp=cmp1) |
| 483 | self.assertEqual(key(obj=3), key(obj=3)) |
| 484 | self.assertGreater(key(obj=3), key(obj=1)) |
| 485 | with self.assertRaises((TypeError, AttributeError)): |
| 486 | key(3) > 1 # rhs is not a K object |
| 487 | with self.assertRaises((TypeError, AttributeError)): |
| 488 | 1 < key(3) # lhs is not a K object |
| 489 | with self.assertRaises(TypeError): |
| 490 | key = functools.cmp_to_key() # too few args |
| 491 | with self.assertRaises(TypeError): |
| 492 | key = functools.cmp_to_key(cmp1, None) # too many args |
| 493 | key = functools.cmp_to_key(cmp1) |
| 494 | with self.assertRaises(TypeError): |
| 495 | key() # too few args |
| 496 | with self.assertRaises(TypeError): |
| 497 | key(None, None) # too many args |
| 498 | |
| 499 | def test_bad_cmp(self): |
| 500 | def cmp1(x, y): |
| 501 | raise ZeroDivisionError |
| 502 | key = functools.cmp_to_key(cmp1) |
| 503 | with self.assertRaises(ZeroDivisionError): |
| 504 | key(3) > key(1) |
| 505 | |
| 506 | class BadCmp: |
| 507 | def __lt__(self, other): |
| 508 | raise ZeroDivisionError |
| 509 | def cmp1(x, y): |
| 510 | return BadCmp() |
| 511 | with self.assertRaises(ZeroDivisionError): |
| 512 | key(3) > key(1) |
| 513 | |
| 514 | def test_obj_field(self): |
| 515 | def cmp1(x, y): |
| 516 | return (x > y) - (x < y) |
| 517 | key = functools.cmp_to_key(mycmp=cmp1) |
| 518 | self.assertEqual(key(50).obj, 50) |
| 519 | |
| 520 | def test_sort_int(self): |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 521 | def mycmp(x, y): |
| 522 | return y - x |
| 523 | self.assertEqual(sorted(range(5), key=functools.cmp_to_key(mycmp)), |
| 524 | [4, 3, 2, 1, 0]) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 525 | |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 526 | def test_sort_int_str(self): |
| 527 | def mycmp(x, y): |
| 528 | x, y = int(x), int(y) |
| 529 | return (x > y) - (x < y) |
| 530 | values = [5, '3', 7, 2, '0', '1', 4, '10', 1] |
| 531 | values = sorted(values, key=functools.cmp_to_key(mycmp)) |
| 532 | self.assertEqual([int(value) for value in values], |
| 533 | [0, 1, 1, 2, 3, 4, 5, 7, 10]) |
| 534 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 535 | def test_hash(self): |
| 536 | def mycmp(x, y): |
| 537 | return y - x |
| 538 | key = functools.cmp_to_key(mycmp) |
| 539 | k = key(10) |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 540 | self.assertRaises(TypeError, hash, k) |
Raymond Hettinger | e7a2430 | 2011-05-03 11:16:36 -0700 | [diff] [blame] | 541 | self.assertNotIsInstance(k, collections.Hashable) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 542 | |
| 543 | class TestTotalOrdering(unittest.TestCase): |
| 544 | |
| 545 | def test_total_ordering_lt(self): |
| 546 | @functools.total_ordering |
| 547 | class A: |
| 548 | def __init__(self, value): |
| 549 | self.value = value |
| 550 | def __lt__(self, other): |
| 551 | return self.value < other.value |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 552 | def __eq__(self, other): |
| 553 | return self.value == other.value |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 554 | self.assertTrue(A(1) < A(2)) |
| 555 | self.assertTrue(A(2) > A(1)) |
| 556 | self.assertTrue(A(1) <= A(2)) |
| 557 | self.assertTrue(A(2) >= A(1)) |
| 558 | self.assertTrue(A(2) <= A(2)) |
| 559 | self.assertTrue(A(2) >= A(2)) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 560 | |
| 561 | def test_total_ordering_le(self): |
| 562 | @functools.total_ordering |
| 563 | class A: |
| 564 | def __init__(self, value): |
| 565 | self.value = value |
| 566 | def __le__(self, other): |
| 567 | return self.value <= other.value |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 568 | def __eq__(self, other): |
| 569 | return self.value == other.value |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 570 | self.assertTrue(A(1) < A(2)) |
| 571 | self.assertTrue(A(2) > A(1)) |
| 572 | self.assertTrue(A(1) <= A(2)) |
| 573 | self.assertTrue(A(2) >= A(1)) |
| 574 | self.assertTrue(A(2) <= A(2)) |
| 575 | self.assertTrue(A(2) >= A(2)) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 576 | |
| 577 | def test_total_ordering_gt(self): |
| 578 | @functools.total_ordering |
| 579 | class A: |
| 580 | def __init__(self, value): |
| 581 | self.value = value |
| 582 | def __gt__(self, other): |
| 583 | return self.value > other.value |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 584 | def __eq__(self, other): |
| 585 | return self.value == other.value |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 586 | self.assertTrue(A(1) < A(2)) |
| 587 | self.assertTrue(A(2) > A(1)) |
| 588 | self.assertTrue(A(1) <= A(2)) |
| 589 | self.assertTrue(A(2) >= A(1)) |
| 590 | self.assertTrue(A(2) <= A(2)) |
| 591 | self.assertTrue(A(2) >= A(2)) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 592 | |
| 593 | def test_total_ordering_ge(self): |
| 594 | @functools.total_ordering |
| 595 | class A: |
| 596 | def __init__(self, value): |
| 597 | self.value = value |
| 598 | def __ge__(self, other): |
| 599 | return self.value >= other.value |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 600 | def __eq__(self, other): |
| 601 | return self.value == other.value |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 602 | self.assertTrue(A(1) < A(2)) |
| 603 | self.assertTrue(A(2) > A(1)) |
| 604 | self.assertTrue(A(1) <= A(2)) |
| 605 | self.assertTrue(A(2) >= A(1)) |
| 606 | self.assertTrue(A(2) <= A(2)) |
| 607 | self.assertTrue(A(2) >= A(2)) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 608 | |
| 609 | def test_total_ordering_no_overwrite(self): |
| 610 | # new methods should not overwrite existing |
| 611 | @functools.total_ordering |
| 612 | class A(int): |
Benjamin Peterson | 9c2930e | 2010-08-23 17:40:33 +0000 | [diff] [blame] | 613 | pass |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 614 | self.assertTrue(A(1) < A(2)) |
| 615 | self.assertTrue(A(2) > A(1)) |
| 616 | self.assertTrue(A(1) <= A(2)) |
| 617 | self.assertTrue(A(2) >= A(1)) |
| 618 | self.assertTrue(A(2) <= A(2)) |
| 619 | self.assertTrue(A(2) >= A(2)) |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 620 | |
Benjamin Peterson | 42ebee3 | 2010-04-11 01:43:16 +0000 | [diff] [blame] | 621 | def test_no_operations_defined(self): |
| 622 | with self.assertRaises(ValueError): |
| 623 | @functools.total_ordering |
| 624 | class A: |
| 625 | pass |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 626 | |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 627 | def test_bug_10042(self): |
| 628 | @functools.total_ordering |
| 629 | class TestTO: |
| 630 | def __init__(self, value): |
| 631 | self.value = value |
| 632 | def __eq__(self, other): |
| 633 | if isinstance(other, TestTO): |
| 634 | return self.value == other.value |
| 635 | return False |
| 636 | def __lt__(self, other): |
| 637 | if isinstance(other, TestTO): |
| 638 | return self.value < other.value |
| 639 | raise TypeError |
| 640 | with self.assertRaises(TypeError): |
| 641 | TestTO(8) <= () |
| 642 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 643 | class TestLRU(unittest.TestCase): |
| 644 | |
| 645 | def test_lru(self): |
| 646 | def orig(x, y): |
| 647 | return 3*x+y |
| 648 | f = functools.lru_cache(maxsize=20)(orig) |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 649 | hits, misses, maxsize, currsize = f.cache_info() |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 650 | self.assertEqual(maxsize, 20) |
| 651 | self.assertEqual(currsize, 0) |
| 652 | self.assertEqual(hits, 0) |
| 653 | self.assertEqual(misses, 0) |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 654 | |
| 655 | domain = range(5) |
| 656 | for i in range(1000): |
| 657 | x, y = choice(domain), choice(domain) |
| 658 | actual = f(x, y) |
| 659 | expected = orig(x, y) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 660 | self.assertEqual(actual, expected) |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 661 | hits, misses, maxsize, currsize = f.cache_info() |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 662 | self.assertTrue(hits > misses) |
| 663 | self.assertEqual(hits + misses, 1000) |
| 664 | self.assertEqual(currsize, 20) |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 665 | |
Raymond Hettinger | 02566ec | 2010-09-04 22:46:06 +0000 | [diff] [blame] | 666 | f.cache_clear() # test clearing |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 667 | hits, misses, maxsize, currsize = f.cache_info() |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 668 | self.assertEqual(hits, 0) |
| 669 | self.assertEqual(misses, 0) |
| 670 | self.assertEqual(currsize, 0) |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 671 | f(x, y) |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 672 | hits, misses, maxsize, currsize = f.cache_info() |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 673 | self.assertEqual(hits, 0) |
| 674 | self.assertEqual(misses, 1) |
| 675 | self.assertEqual(currsize, 1) |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 676 | |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 677 | # Test bypassing the cache |
| 678 | self.assertIs(f.__wrapped__, orig) |
| 679 | f.__wrapped__(x, y) |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 680 | hits, misses, maxsize, currsize = f.cache_info() |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 681 | self.assertEqual(hits, 0) |
| 682 | self.assertEqual(misses, 1) |
| 683 | self.assertEqual(currsize, 1) |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 684 | |
Raymond Hettinger | 0f56e90 | 2010-08-14 23:52:08 +0000 | [diff] [blame] | 685 | # test size zero (which means "never-cache") |
Raymond Hettinger | 0f56e90 | 2010-08-14 23:52:08 +0000 | [diff] [blame] | 686 | @functools.lru_cache(0) |
| 687 | def f(): |
| 688 | nonlocal f_cnt |
| 689 | f_cnt += 1 |
| 690 | return 20 |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 691 | self.assertEqual(f.cache_info().maxsize, 0) |
Raymond Hettinger | f309828 | 2010-08-15 03:30:45 +0000 | [diff] [blame] | 692 | f_cnt = 0 |
| 693 | for i in range(5): |
| 694 | self.assertEqual(f(), 20) |
| 695 | self.assertEqual(f_cnt, 5) |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 696 | hits, misses, maxsize, currsize = f.cache_info() |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 697 | self.assertEqual(hits, 0) |
| 698 | self.assertEqual(misses, 5) |
| 699 | self.assertEqual(currsize, 0) |
Raymond Hettinger | 0f56e90 | 2010-08-14 23:52:08 +0000 | [diff] [blame] | 700 | |
| 701 | # test size one |
Raymond Hettinger | 0f56e90 | 2010-08-14 23:52:08 +0000 | [diff] [blame] | 702 | @functools.lru_cache(1) |
| 703 | def f(): |
| 704 | nonlocal f_cnt |
| 705 | f_cnt += 1 |
| 706 | return 20 |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 707 | self.assertEqual(f.cache_info().maxsize, 1) |
Raymond Hettinger | f309828 | 2010-08-15 03:30:45 +0000 | [diff] [blame] | 708 | f_cnt = 0 |
| 709 | for i in range(5): |
| 710 | self.assertEqual(f(), 20) |
Raymond Hettinger | 0f56e90 | 2010-08-14 23:52:08 +0000 | [diff] [blame] | 711 | self.assertEqual(f_cnt, 1) |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 712 | hits, misses, maxsize, currsize = f.cache_info() |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 713 | self.assertEqual(hits, 4) |
| 714 | self.assertEqual(misses, 1) |
| 715 | self.assertEqual(currsize, 1) |
Raymond Hettinger | 0f56e90 | 2010-08-14 23:52:08 +0000 | [diff] [blame] | 716 | |
Raymond Hettinger | f309828 | 2010-08-15 03:30:45 +0000 | [diff] [blame] | 717 | # test size two |
| 718 | @functools.lru_cache(2) |
| 719 | def f(x): |
Raymond Hettinger | 0f56e90 | 2010-08-14 23:52:08 +0000 | [diff] [blame] | 720 | nonlocal f_cnt |
| 721 | f_cnt += 1 |
Raymond Hettinger | f309828 | 2010-08-15 03:30:45 +0000 | [diff] [blame] | 722 | return x*10 |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 723 | self.assertEqual(f.cache_info().maxsize, 2) |
Raymond Hettinger | 0f56e90 | 2010-08-14 23:52:08 +0000 | [diff] [blame] | 724 | f_cnt = 0 |
Raymond Hettinger | f309828 | 2010-08-15 03:30:45 +0000 | [diff] [blame] | 725 | for x in 7, 9, 7, 9, 7, 9, 8, 8, 8, 9, 9, 9, 8, 8, 8, 7: |
| 726 | # * * * * |
| 727 | self.assertEqual(f(x), x*10) |
| 728 | self.assertEqual(f_cnt, 4) |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 729 | hits, misses, maxsize, currsize = f.cache_info() |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 730 | self.assertEqual(hits, 12) |
| 731 | self.assertEqual(misses, 4) |
| 732 | self.assertEqual(currsize, 2) |
Raymond Hettinger | 0f56e90 | 2010-08-14 23:52:08 +0000 | [diff] [blame] | 733 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 734 | def test_lru_with_maxsize_none(self): |
| 735 | @functools.lru_cache(maxsize=None) |
| 736 | def fib(n): |
| 737 | if n < 2: |
| 738 | return n |
| 739 | return fib(n-1) + fib(n-2) |
| 740 | self.assertEqual([fib(n) for n in range(16)], |
| 741 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]) |
| 742 | self.assertEqual(fib.cache_info(), |
| 743 | functools._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)) |
| 744 | fib.cache_clear() |
| 745 | self.assertEqual(fib.cache_info(), |
| 746 | functools._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)) |
| 747 | |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 748 | def test_lru_with_exceptions(self): |
| 749 | # Verify that user_function exceptions get passed through without |
| 750 | # creating a hard-to-read chained exception. |
| 751 | # http://bugs.python.org/issue13177 |
| 752 | for maxsize in (None, 100): |
| 753 | @functools.lru_cache(maxsize) |
| 754 | def func(i): |
| 755 | return 'abc'[i] |
| 756 | self.assertEqual(func(0), 'a') |
| 757 | with self.assertRaises(IndexError) as cm: |
| 758 | func(15) |
| 759 | self.assertIsNone(cm.exception.__context__) |
| 760 | # Verify that the previous exception did not result in a cached entry |
| 761 | with self.assertRaises(IndexError): |
| 762 | func(15) |
| 763 | |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 764 | def test_lru_with_types(self): |
| 765 | for maxsize in (None, 100): |
| 766 | @functools.lru_cache(maxsize=maxsize, typed=True) |
| 767 | def square(x): |
| 768 | return x * x |
| 769 | self.assertEqual(square(3), 9) |
| 770 | self.assertEqual(type(square(3)), type(9)) |
| 771 | self.assertEqual(square(3.0), 9.0) |
| 772 | self.assertEqual(type(square(3.0)), type(9.0)) |
| 773 | self.assertEqual(square(x=3), 9) |
| 774 | self.assertEqual(type(square(x=3)), type(9)) |
| 775 | self.assertEqual(square(x=3.0), 9.0) |
| 776 | self.assertEqual(type(square(x=3.0)), type(9.0)) |
| 777 | self.assertEqual(square.cache_info().hits, 4) |
| 778 | self.assertEqual(square.cache_info().misses, 4) |
| 779 | |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 780 | def test_main(verbose=None): |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 781 | test_classes = ( |
| 782 | TestPartial, |
| 783 | TestPartialSubclass, |
| 784 | TestPythonPartial, |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 785 | TestUpdateWrapper, |
Benjamin Peterson | 9c2930e | 2010-08-23 17:40:33 +0000 | [diff] [blame] | 786 | TestTotalOrdering, |
Raymond Hettinger | 003be52 | 2011-05-03 11:01:32 -0700 | [diff] [blame] | 787 | TestCmpToKey, |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 788 | TestWraps, |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 789 | TestReduce, |
| 790 | TestLRU, |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 791 | ) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 792 | support.run_unittest(*test_classes) |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 793 | |
| 794 | # verify reference counting |
| 795 | if verbose and hasattr(sys, "gettotalrefcount"): |
| 796 | import gc |
| 797 | counts = [None] * 5 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 798 | for i in range(len(counts)): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 799 | support.run_unittest(*test_classes) |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 800 | gc.collect() |
| 801 | counts[i] = sys.gettotalrefcount() |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 802 | print(counts) |
Raymond Hettinger | 9c323f8 | 2005-02-28 19:39:44 +0000 | [diff] [blame] | 803 | |
| 804 | if __name__ == '__main__': |
| 805 | test_main(verbose=True) |