Issue #5788: `datetime.timedelta` objects get a new `total_seconds()` method returning
[python.git] / Lib / test / test_copy.py
blobccbd2318606beabbe264f43f26881121f1140e35
1 """Unit tests for the copy module."""
3 import copy
4 import copy_reg
5 import weakref
6 import operator
8 import unittest
9 from test import test_support
11 class TestCopy(unittest.TestCase):
13 # Attempt full line coverage of copy.py from top to bottom
15 def test_exceptions(self):
16 self.assertTrue(copy.Error is copy.error)
17 self.assertTrue(issubclass(copy.Error, Exception))
19 # The copy() method
21 def test_copy_basic(self):
22 x = 42
23 y = copy.copy(x)
24 self.assertEqual(x, y)
26 def test_copy_copy(self):
27 class C(object):
28 def __init__(self, foo):
29 self.foo = foo
30 def __copy__(self):
31 return C(self.foo)
32 x = C(42)
33 y = copy.copy(x)
34 self.assertEqual(y.__class__, x.__class__)
35 self.assertEqual(y.foo, x.foo)
37 def test_copy_registry(self):
38 class C(object):
39 def __new__(cls, foo):
40 obj = object.__new__(cls)
41 obj.foo = foo
42 return obj
43 def pickle_C(obj):
44 return (C, (obj.foo,))
45 x = C(42)
46 self.assertRaises(TypeError, copy.copy, x)
47 copy_reg.pickle(C, pickle_C, C)
48 y = copy.copy(x)
50 def test_copy_reduce_ex(self):
51 class C(object):
52 def __reduce_ex__(self, proto):
53 return ""
54 def __reduce__(self):
55 raise test_support.TestFailed, "shouldn't call this"
56 x = C()
57 y = copy.copy(x)
58 self.assertTrue(y is x)
60 def test_copy_reduce(self):
61 class C(object):
62 def __reduce__(self):
63 return ""
64 x = C()
65 y = copy.copy(x)
66 self.assertTrue(y is x)
68 def test_copy_cant(self):
69 class C(object):
70 def __getattribute__(self, name):
71 if name.startswith("__reduce"):
72 raise AttributeError, name
73 return object.__getattribute__(self, name)
74 x = C()
75 self.assertRaises(copy.Error, copy.copy, x)
77 # Type-specific _copy_xxx() methods
79 def test_copy_atomic(self):
80 class Classic:
81 pass
82 class NewStyle(object):
83 pass
84 def f():
85 pass
86 tests = [None, 42, 2L**100, 3.14, True, False, 1j,
87 "hello", u"hello\u1234", f.func_code,
88 NewStyle, xrange(10), Classic, max]
89 for x in tests:
90 self.assertTrue(copy.copy(x) is x, repr(x))
92 def test_copy_list(self):
93 x = [1, 2, 3]
94 self.assertEqual(copy.copy(x), x)
96 def test_copy_tuple(self):
97 x = (1, 2, 3)
98 self.assertEqual(copy.copy(x), x)
100 def test_copy_dict(self):
101 x = {"foo": 1, "bar": 2}
102 self.assertEqual(copy.copy(x), x)
104 def test_copy_inst_vanilla(self):
105 class C:
106 def __init__(self, foo):
107 self.foo = foo
108 def __cmp__(self, other):
109 return cmp(self.foo, other.foo)
110 x = C(42)
111 self.assertEqual(copy.copy(x), x)
113 def test_copy_inst_copy(self):
114 class C:
115 def __init__(self, foo):
116 self.foo = foo
117 def __copy__(self):
118 return C(self.foo)
119 def __cmp__(self, other):
120 return cmp(self.foo, other.foo)
121 x = C(42)
122 self.assertEqual(copy.copy(x), x)
124 def test_copy_inst_getinitargs(self):
125 class C:
126 def __init__(self, foo):
127 self.foo = foo
128 def __getinitargs__(self):
129 return (self.foo,)
130 def __cmp__(self, other):
131 return cmp(self.foo, other.foo)
132 x = C(42)
133 self.assertEqual(copy.copy(x), x)
135 def test_copy_inst_getstate(self):
136 class C:
137 def __init__(self, foo):
138 self.foo = foo
139 def __getstate__(self):
140 return {"foo": self.foo}
141 def __cmp__(self, other):
142 return cmp(self.foo, other.foo)
143 x = C(42)
144 self.assertEqual(copy.copy(x), x)
146 def test_copy_inst_setstate(self):
147 class C:
148 def __init__(self, foo):
149 self.foo = foo
150 def __setstate__(self, state):
151 self.foo = state["foo"]
152 def __cmp__(self, other):
153 return cmp(self.foo, other.foo)
154 x = C(42)
155 self.assertEqual(copy.copy(x), x)
157 def test_copy_inst_getstate_setstate(self):
158 class C:
159 def __init__(self, foo):
160 self.foo = foo
161 def __getstate__(self):
162 return self.foo
163 def __setstate__(self, state):
164 self.foo = state
165 def __cmp__(self, other):
166 return cmp(self.foo, other.foo)
167 x = C(42)
168 self.assertEqual(copy.copy(x), x)
170 # The deepcopy() method
172 def test_deepcopy_basic(self):
173 x = 42
174 y = copy.deepcopy(x)
175 self.assertEqual(y, x)
177 def test_deepcopy_memo(self):
178 # Tests of reflexive objects are under type-specific sections below.
179 # This tests only repetitions of objects.
180 x = []
181 x = [x, x]
182 y = copy.deepcopy(x)
183 self.assertEqual(y, x)
184 self.assertTrue(y is not x)
185 self.assertTrue(y[0] is not x[0])
186 self.assertTrue(y[0] is y[1])
188 def test_deepcopy_issubclass(self):
189 # XXX Note: there's no way to test the TypeError coming out of
190 # issubclass() -- this can only happen when an extension
191 # module defines a "type" that doesn't formally inherit from
192 # type.
193 class Meta(type):
194 pass
195 class C:
196 __metaclass__ = Meta
197 self.assertEqual(copy.deepcopy(C), C)
199 def test_deepcopy_deepcopy(self):
200 class C(object):
201 def __init__(self, foo):
202 self.foo = foo
203 def __deepcopy__(self, memo=None):
204 return C(self.foo)
205 x = C(42)
206 y = copy.deepcopy(x)
207 self.assertEqual(y.__class__, x.__class__)
208 self.assertEqual(y.foo, x.foo)
210 def test_deepcopy_registry(self):
211 class C(object):
212 def __new__(cls, foo):
213 obj = object.__new__(cls)
214 obj.foo = foo
215 return obj
216 def pickle_C(obj):
217 return (C, (obj.foo,))
218 x = C(42)
219 self.assertRaises(TypeError, copy.deepcopy, x)
220 copy_reg.pickle(C, pickle_C, C)
221 y = copy.deepcopy(x)
223 def test_deepcopy_reduce_ex(self):
224 class C(object):
225 def __reduce_ex__(self, proto):
226 return ""
227 def __reduce__(self):
228 raise test_support.TestFailed, "shouldn't call this"
229 x = C()
230 y = copy.deepcopy(x)
231 self.assertTrue(y is x)
233 def test_deepcopy_reduce(self):
234 class C(object):
235 def __reduce__(self):
236 return ""
237 x = C()
238 y = copy.deepcopy(x)
239 self.assertTrue(y is x)
241 def test_deepcopy_cant(self):
242 class C(object):
243 def __getattribute__(self, name):
244 if name.startswith("__reduce"):
245 raise AttributeError, name
246 return object.__getattribute__(self, name)
247 x = C()
248 self.assertRaises(copy.Error, copy.deepcopy, x)
250 # Type-specific _deepcopy_xxx() methods
252 def test_deepcopy_atomic(self):
253 class Classic:
254 pass
255 class NewStyle(object):
256 pass
257 def f():
258 pass
259 tests = [None, 42, 2L**100, 3.14, True, False, 1j,
260 "hello", u"hello\u1234", f.func_code,
261 NewStyle, xrange(10), Classic, max]
262 for x in tests:
263 self.assertTrue(copy.deepcopy(x) is x, repr(x))
265 def test_deepcopy_list(self):
266 x = [[1, 2], 3]
267 y = copy.deepcopy(x)
268 self.assertEqual(y, x)
269 self.assertTrue(x is not y)
270 self.assertTrue(x[0] is not y[0])
272 def test_deepcopy_reflexive_list(self):
273 x = []
274 x.append(x)
275 y = copy.deepcopy(x)
276 self.assertRaises(RuntimeError, cmp, y, x)
277 self.assertTrue(y is not x)
278 self.assertTrue(y[0] is y)
279 self.assertEqual(len(y), 1)
281 def test_deepcopy_tuple(self):
282 x = ([1, 2], 3)
283 y = copy.deepcopy(x)
284 self.assertEqual(y, x)
285 self.assertTrue(x is not y)
286 self.assertTrue(x[0] is not y[0])
288 def test_deepcopy_reflexive_tuple(self):
289 x = ([],)
290 x[0].append(x)
291 y = copy.deepcopy(x)
292 self.assertRaises(RuntimeError, cmp, y, x)
293 self.assertTrue(y is not x)
294 self.assertTrue(y[0] is not x[0])
295 self.assertTrue(y[0][0] is y)
297 def test_deepcopy_dict(self):
298 x = {"foo": [1, 2], "bar": 3}
299 y = copy.deepcopy(x)
300 self.assertEqual(y, x)
301 self.assertTrue(x is not y)
302 self.assertTrue(x["foo"] is not y["foo"])
304 def test_deepcopy_reflexive_dict(self):
305 x = {}
306 x['foo'] = x
307 y = copy.deepcopy(x)
308 self.assertRaises(RuntimeError, cmp, y, x)
309 self.assertTrue(y is not x)
310 self.assertTrue(y['foo'] is y)
311 self.assertEqual(len(y), 1)
313 def test_deepcopy_keepalive(self):
314 memo = {}
315 x = 42
316 y = copy.deepcopy(x, memo)
317 self.assertTrue(memo[id(x)] is x)
319 def test_deepcopy_inst_vanilla(self):
320 class C:
321 def __init__(self, foo):
322 self.foo = foo
323 def __cmp__(self, other):
324 return cmp(self.foo, other.foo)
325 x = C([42])
326 y = copy.deepcopy(x)
327 self.assertEqual(y, x)
328 self.assertTrue(y.foo is not x.foo)
330 def test_deepcopy_inst_deepcopy(self):
331 class C:
332 def __init__(self, foo):
333 self.foo = foo
334 def __deepcopy__(self, memo):
335 return C(copy.deepcopy(self.foo, memo))
336 def __cmp__(self, other):
337 return cmp(self.foo, other.foo)
338 x = C([42])
339 y = copy.deepcopy(x)
340 self.assertEqual(y, x)
341 self.assertTrue(y is not x)
342 self.assertTrue(y.foo is not x.foo)
344 def test_deepcopy_inst_getinitargs(self):
345 class C:
346 def __init__(self, foo):
347 self.foo = foo
348 def __getinitargs__(self):
349 return (self.foo,)
350 def __cmp__(self, other):
351 return cmp(self.foo, other.foo)
352 x = C([42])
353 y = copy.deepcopy(x)
354 self.assertEqual(y, x)
355 self.assertTrue(y is not x)
356 self.assertTrue(y.foo is not x.foo)
358 def test_deepcopy_inst_getstate(self):
359 class C:
360 def __init__(self, foo):
361 self.foo = foo
362 def __getstate__(self):
363 return {"foo": self.foo}
364 def __cmp__(self, other):
365 return cmp(self.foo, other.foo)
366 x = C([42])
367 y = copy.deepcopy(x)
368 self.assertEqual(y, x)
369 self.assertTrue(y is not x)
370 self.assertTrue(y.foo is not x.foo)
372 def test_deepcopy_inst_setstate(self):
373 class C:
374 def __init__(self, foo):
375 self.foo = foo
376 def __setstate__(self, state):
377 self.foo = state["foo"]
378 def __cmp__(self, other):
379 return cmp(self.foo, other.foo)
380 x = C([42])
381 y = copy.deepcopy(x)
382 self.assertEqual(y, x)
383 self.assertTrue(y is not x)
384 self.assertTrue(y.foo is not x.foo)
386 def test_deepcopy_inst_getstate_setstate(self):
387 class C:
388 def __init__(self, foo):
389 self.foo = foo
390 def __getstate__(self):
391 return self.foo
392 def __setstate__(self, state):
393 self.foo = state
394 def __cmp__(self, other):
395 return cmp(self.foo, other.foo)
396 x = C([42])
397 y = copy.deepcopy(x)
398 self.assertEqual(y, x)
399 self.assertTrue(y is not x)
400 self.assertTrue(y.foo is not x.foo)
402 def test_deepcopy_reflexive_inst(self):
403 class C:
404 pass
405 x = C()
406 x.foo = x
407 y = copy.deepcopy(x)
408 self.assertTrue(y is not x)
409 self.assertTrue(y.foo is y)
411 # _reconstruct()
413 def test_reconstruct_string(self):
414 class C(object):
415 def __reduce__(self):
416 return ""
417 x = C()
418 y = copy.copy(x)
419 self.assertTrue(y is x)
420 y = copy.deepcopy(x)
421 self.assertTrue(y is x)
423 def test_reconstruct_nostate(self):
424 class C(object):
425 def __reduce__(self):
426 return (C, ())
427 x = C()
428 x.foo = 42
429 y = copy.copy(x)
430 self.assertTrue(y.__class__ is x.__class__)
431 y = copy.deepcopy(x)
432 self.assertTrue(y.__class__ is x.__class__)
434 def test_reconstruct_state(self):
435 class C(object):
436 def __reduce__(self):
437 return (C, (), self.__dict__)
438 def __cmp__(self, other):
439 return cmp(self.__dict__, other.__dict__)
440 __hash__ = None # Silence Py3k warning
441 x = C()
442 x.foo = [42]
443 y = copy.copy(x)
444 self.assertEqual(y, x)
445 y = copy.deepcopy(x)
446 self.assertEqual(y, x)
447 self.assertTrue(y.foo is not x.foo)
449 def test_reconstruct_state_setstate(self):
450 class C(object):
451 def __reduce__(self):
452 return (C, (), self.__dict__)
453 def __setstate__(self, state):
454 self.__dict__.update(state)
455 def __cmp__(self, other):
456 return cmp(self.__dict__, other.__dict__)
457 __hash__ = None # Silence Py3k warning
458 x = C()
459 x.foo = [42]
460 y = copy.copy(x)
461 self.assertEqual(y, x)
462 y = copy.deepcopy(x)
463 self.assertEqual(y, x)
464 self.assertTrue(y.foo is not x.foo)
466 def test_reconstruct_reflexive(self):
467 class C(object):
468 pass
469 x = C()
470 x.foo = x
471 y = copy.deepcopy(x)
472 self.assertTrue(y is not x)
473 self.assertTrue(y.foo is y)
475 # Additions for Python 2.3 and pickle protocol 2
477 def test_reduce_4tuple(self):
478 class C(list):
479 def __reduce__(self):
480 return (C, (), self.__dict__, iter(self))
481 def __cmp__(self, other):
482 return (cmp(list(self), list(other)) or
483 cmp(self.__dict__, other.__dict__))
484 __hash__ = None # Silence Py3k warning
485 x = C([[1, 2], 3])
486 y = copy.copy(x)
487 self.assertEqual(x, y)
488 self.assertTrue(x is not y)
489 self.assertTrue(x[0] is y[0])
490 y = copy.deepcopy(x)
491 self.assertEqual(x, y)
492 self.assertTrue(x is not y)
493 self.assertTrue(x[0] is not y[0])
495 def test_reduce_5tuple(self):
496 class C(dict):
497 def __reduce__(self):
498 return (C, (), self.__dict__, None, self.iteritems())
499 def __cmp__(self, other):
500 return (cmp(dict(self), list(dict)) or
501 cmp(self.__dict__, other.__dict__))
502 __hash__ = None # Silence Py3k warning
503 x = C([("foo", [1, 2]), ("bar", 3)])
504 y = copy.copy(x)
505 self.assertEqual(x, y)
506 self.assertTrue(x is not y)
507 self.assertTrue(x["foo"] is y["foo"])
508 y = copy.deepcopy(x)
509 self.assertEqual(x, y)
510 self.assertTrue(x is not y)
511 self.assertTrue(x["foo"] is not y["foo"])
513 def test_copy_slots(self):
514 class C(object):
515 __slots__ = ["foo"]
516 x = C()
517 x.foo = [42]
518 y = copy.copy(x)
519 self.assertTrue(x.foo is y.foo)
521 def test_deepcopy_slots(self):
522 class C(object):
523 __slots__ = ["foo"]
524 x = C()
525 x.foo = [42]
526 y = copy.deepcopy(x)
527 self.assertEqual(x.foo, y.foo)
528 self.assertTrue(x.foo is not y.foo)
530 def test_copy_list_subclass(self):
531 class C(list):
532 pass
533 x = C([[1, 2], 3])
534 x.foo = [4, 5]
535 y = copy.copy(x)
536 self.assertEqual(list(x), list(y))
537 self.assertEqual(x.foo, y.foo)
538 self.assertTrue(x[0] is y[0])
539 self.assertTrue(x.foo is y.foo)
541 def test_deepcopy_list_subclass(self):
542 class C(list):
543 pass
544 x = C([[1, 2], 3])
545 x.foo = [4, 5]
546 y = copy.deepcopy(x)
547 self.assertEqual(list(x), list(y))
548 self.assertEqual(x.foo, y.foo)
549 self.assertTrue(x[0] is not y[0])
550 self.assertTrue(x.foo is not y.foo)
552 def test_copy_tuple_subclass(self):
553 class C(tuple):
554 pass
555 x = C([1, 2, 3])
556 self.assertEqual(tuple(x), (1, 2, 3))
557 y = copy.copy(x)
558 self.assertEqual(tuple(y), (1, 2, 3))
560 def test_deepcopy_tuple_subclass(self):
561 class C(tuple):
562 pass
563 x = C([[1, 2], 3])
564 self.assertEqual(tuple(x), ([1, 2], 3))
565 y = copy.deepcopy(x)
566 self.assertEqual(tuple(y), ([1, 2], 3))
567 self.assertTrue(x is not y)
568 self.assertTrue(x[0] is not y[0])
570 def test_getstate_exc(self):
571 class EvilState(object):
572 def __getstate__(self):
573 raise ValueError, "ain't got no stickin' state"
574 self.assertRaises(ValueError, copy.copy, EvilState())
576 def test_copy_function(self):
577 self.assertEqual(copy.copy(global_foo), global_foo)
578 def foo(x, y): return x+y
579 self.assertEqual(copy.copy(foo), foo)
580 bar = lambda: None
581 self.assertEqual(copy.copy(bar), bar)
583 def test_deepcopy_function(self):
584 self.assertEqual(copy.deepcopy(global_foo), global_foo)
585 def foo(x, y): return x+y
586 self.assertEqual(copy.deepcopy(foo), foo)
587 bar = lambda: None
588 self.assertEqual(copy.deepcopy(bar), bar)
590 def _check_weakref(self, _copy):
591 class C(object):
592 pass
593 obj = C()
594 x = weakref.ref(obj)
595 y = _copy(x)
596 self.assertTrue(y is x)
597 del obj
598 y = _copy(x)
599 self.assertTrue(y is x)
601 def test_copy_weakref(self):
602 self._check_weakref(copy.copy)
604 def test_deepcopy_weakref(self):
605 self._check_weakref(copy.deepcopy)
607 def _check_copy_weakdict(self, _dicttype):
608 class C(object):
609 pass
610 a, b, c, d = [C() for i in xrange(4)]
611 u = _dicttype()
612 u[a] = b
613 u[c] = d
614 v = copy.copy(u)
615 self.assertFalse(v is u)
616 self.assertEqual(v, u)
617 self.assertEqual(v[a], b)
618 self.assertEqual(v[c], d)
619 self.assertEqual(len(v), 2)
620 del c, d
621 self.assertEqual(len(v), 1)
622 x, y = C(), C()
623 # The underlying containers are decoupled
624 v[x] = y
625 self.assertFalse(x in u)
627 def test_copy_weakkeydict(self):
628 self._check_copy_weakdict(weakref.WeakKeyDictionary)
630 def test_copy_weakvaluedict(self):
631 self._check_copy_weakdict(weakref.WeakValueDictionary)
633 def test_deepcopy_weakkeydict(self):
634 class C(object):
635 def __init__(self, i):
636 self.i = i
637 a, b, c, d = [C(i) for i in xrange(4)]
638 u = weakref.WeakKeyDictionary()
639 u[a] = b
640 u[c] = d
641 # Keys aren't copied, values are
642 v = copy.deepcopy(u)
643 self.assertNotEqual(v, u)
644 self.assertEqual(len(v), 2)
645 self.assertFalse(v[a] is b)
646 self.assertFalse(v[c] is d)
647 self.assertEqual(v[a].i, b.i)
648 self.assertEqual(v[c].i, d.i)
649 del c
650 self.assertEqual(len(v), 1)
652 def test_deepcopy_weakvaluedict(self):
653 class C(object):
654 def __init__(self, i):
655 self.i = i
656 a, b, c, d = [C(i) for i in xrange(4)]
657 u = weakref.WeakValueDictionary()
658 u[a] = b
659 u[c] = d
660 # Keys are copied, values aren't
661 v = copy.deepcopy(u)
662 self.assertNotEqual(v, u)
663 self.assertEqual(len(v), 2)
664 (x, y), (z, t) = sorted(v.items(), key=lambda (k, v): k.i)
665 self.assertFalse(x is a)
666 self.assertEqual(x.i, a.i)
667 self.assertTrue(y is b)
668 self.assertFalse(z is c)
669 self.assertEqual(z.i, c.i)
670 self.assertTrue(t is d)
671 del x, y, z, t
672 del d
673 self.assertEqual(len(v), 1)
676 def global_foo(x, y): return x+y
678 def test_main():
679 test_support.run_unittest(TestCopy)
681 if __name__ == "__main__":
682 test_main()