Debian Codegraph @

Lib/test/test_copy.py

raw
1 """Unit tests for the copy module."""
2
3 import copy
4 import copyreg
5 import weakref
6 import abc
7 from operator import le, lt, ge, gt, eq, ne, attrgetter
8
9 import unittest
10 from test import support
11
12 order_comparisons = le, lt, ge, gt
13 equality_comparisons = eq, ne
14 comparisons = order_comparisons + equality_comparisons
15
16 class TestCopy(unittest.TestCase):
17
18 # Attempt full line coverage of copy.py from top to bottom
19
20 def test_exceptions(self):
21 self.assertIs(copy.Error, copy.error)
22 self.assertIsSubclass(copy.Error, Exception)
23
24 # The copy() method
25
26 def test_copy_basic(self):
27 x = 42
28 y = copy.copy(x)
29 self.assertEqual(x, y)
30
31 def test_copy_copy(self):
32 class C(object):
33 def __init__(self, foo):
34 self.foo = foo
35 def __copy__(self):
36 return C(self.foo)
37 x = C(42)
38 y = copy.copy(x)
39 self.assertEqual(y.__class__, x.__class__)
40 self.assertEqual(y.foo, x.foo)
41
42 def test_copy_registry(self):
43 class C(object):
44 def __new__(cls, foo):
45 obj = object.__new__(cls)
46 obj.foo = foo
47 return obj
48 def pickle_C(obj):
49 return (C, (obj.foo,))
50 x = C(42)
51 self.assertRaises(TypeError, copy.copy, x)
52 copyreg.pickle(C, pickle_C, C)
53 y = copy.copy(x)
54 self.assertIsNot(x, y)
55 self.assertEqual(type(y), C)
56 self.assertEqual(y.foo, x.foo)
57
58 def test_copy_reduce_ex(self):
59 class C(object):
60 def __reduce_ex__(self, proto):
61 c.append(1)
62 return ""
63 def __reduce__(self):
64 self.fail("shouldn't call this")
65 c = []
66 x = C()
67 y = copy.copy(x)
68 self.assertIs(y, x)
69 self.assertEqual(c, [1])
70
71 def test_copy_reduce(self):
72 class C(object):
73 def __reduce__(self):
74 c.append(1)
75 return ""
76 c = []
77 x = C()
78 y = copy.copy(x)
79 self.assertIs(y, x)
80 self.assertEqual(c, [1])
81
82 def test_copy_cant(self):
83 class C(object):
84 def __getattribute__(self, name):
85 if name.startswith("__reduce"):
86 raise AttributeError(name)
87 return object.__getattribute__(self, name)
88 x = C()
89 self.assertRaises(copy.Error, copy.copy, x)
90
91 # Type-specific _copy_xxx() methods
92
93 def test_copy_atomic(self):
94 class NewStyle:
95 pass
96 def f():
97 pass
98 class WithMetaclass(metaclass=abc.ABCMeta):
99 pass
100 tests = [None, ..., NotImplemented,
101 42, 2**100, 3.14, True, False, 1j,
102 "hello", "hello\u1234", f.__code__,
103 b"world", bytes(range(256)), range(10), slice(1, 10, 2),
104 NewStyle, max, WithMetaclass, property()]
105 for x in tests:
106 self.assertIs(copy.copy(x), x)
107
108 def test_copy_list(self):
109 x = [1, 2, 3]
110 y = copy.copy(x)
111 self.assertEqual(y, x)
112 self.assertIsNot(y, x)
113 x = []
114 y = copy.copy(x)
115 self.assertEqual(y, x)
116 self.assertIsNot(y, x)
117
118 def test_copy_tuple(self):
119 x = (1, 2, 3)
120 self.assertIs(copy.copy(x), x)
121 x = ()
122 self.assertIs(copy.copy(x), x)
123 x = (1, 2, 3, [])
124 self.assertIs(copy.copy(x), x)
125
126 def test_copy_dict(self):
127 x = {"foo": 1, "bar": 2}
128 y = copy.copy(x)
129 self.assertEqual(y, x)
130 self.assertIsNot(y, x)
131 x = {}
132 y = copy.copy(x)
133 self.assertEqual(y, x)
134 self.assertIsNot(y, x)
135
136 def test_copy_set(self):
137 x = {1, 2, 3}
138 y = copy.copy(x)
139 self.assertEqual(y, x)
140 self.assertIsNot(y, x)
141 x = set()
142 y = copy.copy(x)
143 self.assertEqual(y, x)
144 self.assertIsNot(y, x)
145
146 def test_copy_frozenset(self):
147 x = frozenset({1, 2, 3})
148 self.assertIs(copy.copy(x), x)
149 x = frozenset()
150 self.assertIs(copy.copy(x), x)
151
152 def test_copy_bytearray(self):
153 x = bytearray(b'abc')
154 y = copy.copy(x)
155 self.assertEqual(y, x)
156 self.assertIsNot(y, x)
157 x = bytearray()
158 y = copy.copy(x)
159 self.assertEqual(y, x)
160 self.assertIsNot(y, x)
161
162 def test_copy_inst_vanilla(self):
163 class C:
164 def __init__(self, foo):
165 self.foo = foo
166 def __eq__(self, other):
167 return self.foo == other.foo
168 x = C(42)
169 self.assertEqual(copy.copy(x), x)
170
171 def test_copy_inst_copy(self):
172 class C:
173 def __init__(self, foo):
174 self.foo = foo
175 def __copy__(self):
176 return C(self.foo)
177 def __eq__(self, other):
178 return self.foo == other.foo
179 x = C(42)
180 self.assertEqual(copy.copy(x), x)
181
182 def test_copy_inst_getinitargs(self):
183 class C:
184 def __init__(self, foo):
185 self.foo = foo
186 def __getinitargs__(self):
187 return (self.foo,)
188 def __eq__(self, other):
189 return self.foo == other.foo
190 x = C(42)
191 self.assertEqual(copy.copy(x), x)
192
193 def test_copy_inst_getnewargs(self):
194 class C(int):
195 def __new__(cls, foo):
196 self = int.__new__(cls)
197 self.foo = foo
198 return self
199 def __getnewargs__(self):
200 return self.foo,
201 def __eq__(self, other):
202 return self.foo == other.foo
203 x = C(42)
204 y = copy.copy(x)
205 self.assertIsInstance(y, C)
206 self.assertEqual(y, x)
207 self.assertIsNot(y, x)
208 self.assertEqual(y.foo, x.foo)
209
210 def test_copy_inst_getnewargs_ex(self):
211 class C(int):
212 def __new__(cls, *, foo):
213 self = int.__new__(cls)
214 self.foo = foo
215 return self
216 def __getnewargs_ex__(self):
217 return (), {'foo': self.foo}
218 def __eq__(self, other):
219 return self.foo == other.foo
220 x = C(foo=42)
221 y = copy.copy(x)
222 self.assertIsInstance(y, C)
223 self.assertEqual(y, x)
224 self.assertIsNot(y, x)
225 self.assertEqual(y.foo, x.foo)
226
227 def test_copy_inst_getstate(self):
228 class C:
229 def __init__(self, foo):
230 self.foo = foo
231 def __getstate__(self):
232 return {"foo": self.foo}
233 def __eq__(self, other):
234 return self.foo == other.foo
235 x = C(42)
236 self.assertEqual(copy.copy(x), x)
237
238 def test_copy_inst_setstate(self):
239 class C:
240 def __init__(self, foo):
241 self.foo = foo
242 def __setstate__(self, state):
243 self.foo = state["foo"]
244 def __eq__(self, other):
245 return self.foo == other.foo
246 x = C(42)
247 self.assertEqual(copy.copy(x), x)
248
249 def test_copy_inst_getstate_setstate(self):
250 class C:
251 def __init__(self, foo):
252 self.foo = foo
253 def __getstate__(self):
254 return self.foo
255 def __setstate__(self, state):
256 self.foo = state
257 def __eq__(self, other):
258 return self.foo == other.foo
259 x = C(42)
260 self.assertEqual(copy.copy(x), x)
261 # State with boolean value is false (issue #25718)
262 x = C(0.0)
263 self.assertEqual(copy.copy(x), x)
264
265 # The deepcopy() method
266
267 def test_deepcopy_basic(self):
268 x = 42
269 y = copy.deepcopy(x)
270 self.assertEqual(y, x)
271
272 def test_deepcopy_memo(self):
273 # Tests of reflexive objects are under type-specific sections below.
274 # This tests only repetitions of objects.
275 x = []
276 x = [x, x]
277 y = copy.deepcopy(x)
278 self.assertEqual(y, x)
279 self.assertIsNot(y, x)
280 self.assertIsNot(y[0], x[0])
281 self.assertIs(y[0], y[1])
282
283 def test_deepcopy_issubclass(self):
284 # XXX Note: there's no way to test the TypeError coming out of
285 # issubclass() -- this can only happen when an extension
286 # module defines a "type" that doesn't formally inherit from
287 # type.
288 class Meta(type):
289 pass
290 class C(metaclass=Meta):
291 pass
292 self.assertEqual(copy.deepcopy(C), C)
293
294 def test_deepcopy_deepcopy(self):
295 class C(object):
296 def __init__(self, foo):
297 self.foo = foo
298 def __deepcopy__(self, memo=None):
299 return C(self.foo)
300 x = C(42)
301 y = copy.deepcopy(x)
302 self.assertEqual(y.__class__, x.__class__)
303 self.assertEqual(y.foo, x.foo)
304
305 def test_deepcopy_registry(self):
306 class C(object):
307 def __new__(cls, foo):
308 obj = object.__new__(cls)
309 obj.foo = foo
310 return obj
311 def pickle_C(obj):
312 return (C, (obj.foo,))
313 x = C(42)
314 self.assertRaises(TypeError, copy.deepcopy, x)
315 copyreg.pickle(C, pickle_C, C)
316 y = copy.deepcopy(x)
317 self.assertIsNot(x, y)
318 self.assertEqual(type(y), C)
319 self.assertEqual(y.foo, x.foo)
320
321 def test_deepcopy_reduce_ex(self):
322 class C(object):
323 def __reduce_ex__(self, proto):
324 c.append(1)
325 return ""
326 def __reduce__(self):
327 self.fail("shouldn't call this")
328 c = []
329 x = C()
330 y = copy.deepcopy(x)
331 self.assertIs(y, x)
332 self.assertEqual(c, [1])
333
334 def test_deepcopy_reduce(self):
335 class C(object):
336 def __reduce__(self):
337 c.append(1)
338 return ""
339 c = []
340 x = C()
341 y = copy.deepcopy(x)
342 self.assertIs(y, x)
343 self.assertEqual(c, [1])
344
345 def test_deepcopy_cant(self):
346 class C(object):
347 def __getattribute__(self, name):
348 if name.startswith("__reduce"):
349 raise AttributeError(name)
350 return object.__getattribute__(self, name)
351 x = C()
352 self.assertRaises(copy.Error, copy.deepcopy, x)
353
354 # Type-specific _deepcopy_xxx() methods
355
356 def test_deepcopy_atomic(self):
357 class NewStyle:
358 pass
359 def f():
360 pass
361 tests = [None, ..., NotImplemented, 42, 2**100, 3.14, True, False, 1j,
362 b"bytes", "hello", "hello\u1234", f.__code__,
363 NewStyle, range(10), max, property()]
364 for x in tests:
365 self.assertIs(copy.deepcopy(x), x)
366
367 def test_deepcopy_list(self):
368 x = [[1, 2], 3]
369 y = copy.deepcopy(x)
370 self.assertEqual(y, x)
371 self.assertIsNot(x, y)
372 self.assertIsNot(x[0], y[0])
373
374 @support.skip_emscripten_stack_overflow()
375 @support.skip_wasi_stack_overflow()
376 def test_deepcopy_reflexive_list(self):
377 x = []
378 x.append(x)
379 y = copy.deepcopy(x)
380 for op in comparisons:
381 self.assertRaises(RecursionError, op, y, x)
382 self.assertIsNot(y, x)
383 self.assertIs(y[0], y)
384 self.assertEqual(len(y), 1)
385
386 def test_deepcopy_empty_tuple(self):
387 x = ()
388 y = copy.deepcopy(x)
389 self.assertIs(x, y)
390
391 def test_deepcopy_tuple(self):
392 x = ([1, 2], 3)
393 y = copy.deepcopy(x)
394 self.assertEqual(y, x)
395 self.assertIsNot(x, y)
396 self.assertIsNot(x[0], y[0])
397
398 def test_deepcopy_tuple_of_immutables(self):
399 x = ((1, 2), 3)
400 y = copy.deepcopy(x)
401 self.assertIs(x, y)
402
403 @support.skip_emscripten_stack_overflow()
404 @support.skip_wasi_stack_overflow()
405 def test_deepcopy_reflexive_tuple(self):
406 x = ([],)
407 x[0].append(x)
408 y = copy.deepcopy(x)
409 for op in comparisons:
410 self.assertRaises(RecursionError, op, y, x)
411 self.assertIsNot(y, x)
412 self.assertIsNot(y[0], x[0])
413 self.assertIs(y[0][0], y)
414
415 def test_deepcopy_dict(self):
416 x = {"foo": [1, 2], "bar": 3}
417 y = copy.deepcopy(x)
418 self.assertEqual(y, x)
419 self.assertIsNot(x, y)
420 self.assertIsNot(x["foo"], y["foo"])
421
422 @support.skip_emscripten_stack_overflow()
423 @support.skip_wasi_stack_overflow()
424 def test_deepcopy_reflexive_dict(self):
425 x = {}
426 x['foo'] = x
427 y = copy.deepcopy(x)
428 for op in order_comparisons:
429 self.assertRaises(TypeError, op, y, x)
430 for op in equality_comparisons:
431 self.assertRaises(RecursionError, op, y, x)
432 self.assertIsNot(y, x)
433 self.assertIs(y['foo'], y)
434 self.assertEqual(len(y), 1)
435
436 def test_deepcopy_keepalive(self):
437 memo = {}
438 x = []
439 y = copy.deepcopy(x, memo)
440 self.assertIs(memo[id(memo)][0], x)
441
442 def test_deepcopy_dont_memo_immutable(self):
443 memo = {}
444 x = [1, 2, 3, 4]
445 y = copy.deepcopy(x, memo)
446 self.assertEqual(y, x)
447 # There's the entry for the new list, and the keep alive.
448 self.assertEqual(len(memo), 2)
449
450 memo = {}
451 x = [(1, 2)]
452 y = copy.deepcopy(x, memo)
453 self.assertEqual(y, x)
454 # Tuples with immutable contents are immutable for deepcopy.
455 self.assertEqual(len(memo), 2)
456
457 def test_deepcopy_inst_vanilla(self):
458 class C:
459 def __init__(self, foo):
460 self.foo = foo
461 def __eq__(self, other):
462 return self.foo == other.foo
463 x = C([42])
464 y = copy.deepcopy(x)
465 self.assertEqual(y, x)
466 self.assertIsNot(y.foo, x.foo)
467
468 def test_deepcopy_inst_deepcopy(self):
469 class C:
470 def __init__(self, foo):
471 self.foo = foo
472 def __deepcopy__(self, memo):
473 return C(copy.deepcopy(self.foo, memo))
474 def __eq__(self, other):
475 return self.foo == other.foo
476 x = C([42])
477 y = copy.deepcopy(x)
478 self.assertEqual(y, x)
479 self.assertIsNot(y, x)
480 self.assertIsNot(y.foo, x.foo)
481
482 def test_deepcopy_inst_getinitargs(self):
483 class C:
484 def __init__(self, foo):
485 self.foo = foo
486 def __getinitargs__(self):
487 return (self.foo,)
488 def __eq__(self, other):
489 return self.foo == other.foo
490 x = C([42])
491 y = copy.deepcopy(x)
492 self.assertEqual(y, x)
493 self.assertIsNot(y, x)
494 self.assertIsNot(y.foo, x.foo)
495
496 def test_deepcopy_inst_getnewargs(self):
497 class C(int):
498 def __new__(cls, foo):
499 self = int.__new__(cls)
500 self.foo = foo
501 return self
502 def __getnewargs__(self):
503 return self.foo,
504 def __eq__(self, other):
505 return self.foo == other.foo
506 x = C([42])
507 y = copy.deepcopy(x)
508 self.assertIsInstance(y, C)
509 self.assertEqual(y, x)
510 self.assertIsNot(y, x)
511 self.assertEqual(y.foo, x.foo)
512 self.assertIsNot(y.foo, x.foo)
513
514 def test_deepcopy_inst_getnewargs_ex(self):
515 class C(int):
516 def __new__(cls, *, foo):
517 self = int.__new__(cls)
518 self.foo = foo
519 return self
520 def __getnewargs_ex__(self):
521 return (), {'foo': self.foo}
522 def __eq__(self, other):
523 return self.foo == other.foo
524 x = C(foo=[42])
525 y = copy.deepcopy(x)
526 self.assertIsInstance(y, C)
527 self.assertEqual(y, x)
528 self.assertIsNot(y, x)
529 self.assertEqual(y.foo, x.foo)
530 self.assertIsNot(y.foo, x.foo)
531
532 def test_deepcopy_inst_getstate(self):
533 class C:
534 def __init__(self, foo):
535 self.foo = foo
536 def __getstate__(self):
537 return {"foo": self.foo}
538 def __eq__(self, other):
539 return self.foo == other.foo
540 x = C([42])
541 y = copy.deepcopy(x)
542 self.assertEqual(y, x)
543 self.assertIsNot(y, x)
544 self.assertIsNot(y.foo, x.foo)
545
546 def test_deepcopy_inst_setstate(self):
547 class C:
548 def __init__(self, foo):
549 self.foo = foo
550 def __setstate__(self, state):
551 self.foo = state["foo"]
552 def __eq__(self, other):
553 return self.foo == other.foo
554 x = C([42])
555 y = copy.deepcopy(x)
556 self.assertEqual(y, x)
557 self.assertIsNot(y, x)
558 self.assertIsNot(y.foo, x.foo)
559
560 def test_deepcopy_inst_getstate_setstate(self):
561 class C:
562 def __init__(self, foo):
563 self.foo = foo
564 def __getstate__(self):
565 return self.foo
566 def __setstate__(self, state):
567 self.foo = state
568 def __eq__(self, other):
569 return self.foo == other.foo
570 x = C([42])
571 y = copy.deepcopy(x)
572 self.assertEqual(y, x)
573 self.assertIsNot(y, x)
574 self.assertIsNot(y.foo, x.foo)
575 # State with boolean value is false (issue #25718)
576 x = C([])
577 y = copy.deepcopy(x)
578 self.assertEqual(y, x)
579 self.assertIsNot(y, x)
580 self.assertIsNot(y.foo, x.foo)
581
582 def test_deepcopy_reflexive_inst(self):
583 class C:
584 pass
585 x = C()
586 x.foo = x
587 y = copy.deepcopy(x)
588 self.assertIsNot(y, x)
589 self.assertIs(y.foo, y)
590
591 # _reconstruct()
592
593 def test_reconstruct_string(self):
594 class C(object):
595 def __reduce__(self):
596 return ""
597 x = C()
598 y = copy.copy(x)
599 self.assertIs(y, x)
600 y = copy.deepcopy(x)
601 self.assertIs(y, x)
602
603 def test_reconstruct_nostate(self):
604 class C(object):
605 def __reduce__(self):
606 return (C, ())
607 x = C()
608 x.foo = 42
609 y = copy.copy(x)
610 self.assertIs(y.__class__, x.__class__)
611 y = copy.deepcopy(x)
612 self.assertIs(y.__class__, x.__class__)
613
614 def test_reconstruct_state(self):
615 class C(object):
616 def __reduce__(self):
617 return (C, (), self.__dict__)
618 def __eq__(self, other):
619 return self.__dict__ == other.__dict__
620 x = C()
621 x.foo = [42]
622 y = copy.copy(x)
623 self.assertEqual(y, x)
624 y = copy.deepcopy(x)
625 self.assertEqual(y, x)
626 self.assertIsNot(y.foo, x.foo)
627
628 def test_reconstruct_state_setstate(self):
629 class C(object):
630 def __reduce__(self):
631 return (C, (), self.__dict__)
632 def __setstate__(self, state):
633 self.__dict__.update(state)
634 def __eq__(self, other):
635 return self.__dict__ == other.__dict__
636 x = C()
637 x.foo = [42]
638 y = copy.copy(x)
639 self.assertEqual(y, x)
640 y = copy.deepcopy(x)
641 self.assertEqual(y, x)
642 self.assertIsNot(y.foo, x.foo)
643
644 def test_reconstruct_reflexive(self):
645 class C(object):
646 pass
647 x = C()
648 x.foo = x
649 y = copy.deepcopy(x)
650 self.assertIsNot(y, x)
651 self.assertIs(y.foo, y)
652
653 # Additions for Python 2.3 and pickle protocol 2
654
655 def test_reduce_4tuple(self):
656 class C(list):
657 def __reduce__(self):
658 return (C, (), self.__dict__, iter(self))
659 def __eq__(self, other):
660 return (list(self) == list(other) and
661 self.__dict__ == other.__dict__)
662 x = C([[1, 2], 3])
663 y = copy.copy(x)
664 self.assertEqual(x, y)
665 self.assertIsNot(x, y)
666 self.assertIs(x[0], y[0])
667 y = copy.deepcopy(x)
668 self.assertEqual(x, y)
669 self.assertIsNot(x, y)
670 self.assertIsNot(x[0], y[0])
671
672 def test_reduce_5tuple(self):
673 class C(dict):
674 def __reduce__(self):
675 return (C, (), self.__dict__, None, iter(self.items()))
676 def __eq__(self, other):
677 return (dict(self) == dict(other) and
678 self.__dict__ == other.__dict__)
679 x = C([("foo", [1, 2]), ("bar", 3)])
680 y = copy.copy(x)
681 self.assertEqual(x, y)
682 self.assertIsNot(x, y)
683 self.assertIs(x["foo"], y["foo"])
684 y = copy.deepcopy(x)
685 self.assertEqual(x, y)
686 self.assertIsNot(x, y)
687 self.assertIsNot(x["foo"], y["foo"])
688
689 def test_reduce_6tuple(self):
690 def state_setter(*args, **kwargs):
691 self.fail("shouldn't call this")
692 class C:
693 def __reduce__(self):
694 return C, (), self.__dict__, None, None, state_setter
695 x = C()
696 with self.assertRaises(TypeError):
697 copy.copy(x)
698 with self.assertRaises(TypeError):
699 copy.deepcopy(x)
700
701 def test_reduce_6tuple_none(self):
702 class C:
703 def __reduce__(self):
704 return C, (), self.__dict__, None, None, None
705 x = C()
706 with self.assertRaises(TypeError):
707 copy.copy(x)
708 with self.assertRaises(TypeError):
709 copy.deepcopy(x)
710
711 def test_copy_slots(self):
712 class C(object):
713 __slots__ = ["foo"]
714 x = C()
715 x.foo = [42]
716 y = copy.copy(x)
717 self.assertIs(x.foo, y.foo)
718
719 def test_deepcopy_slots(self):
720 class C(object):
721 __slots__ = ["foo"]
722 x = C()
723 x.foo = [42]
724 y = copy.deepcopy(x)
725 self.assertEqual(x.foo, y.foo)
726 self.assertIsNot(x.foo, y.foo)
727
728 def test_deepcopy_dict_subclass(self):
729 class C(dict):
730 def __init__(self, d=None):
731 if not d:
732 d = {}
733 self._keys = list(d.keys())
734 super().__init__(d)
735 def __setitem__(self, key, item):
736 super().__setitem__(key, item)
737 if key not in self._keys:
738 self._keys.append(key)
739 x = C(d={'foo':0})
740 y = copy.deepcopy(x)
741 self.assertEqual(x, y)
742 self.assertEqual(x._keys, y._keys)
743 self.assertIsNot(x, y)
744 x['bar'] = 1
745 self.assertNotEqual(x, y)
746 self.assertNotEqual(x._keys, y._keys)
747
748 def test_copy_list_subclass(self):
749 class C(list):
750 pass
751 x = C([[1, 2], 3])
752 x.foo = [4, 5]
753 y = copy.copy(x)
754 self.assertEqual(list(x), list(y))
755 self.assertEqual(x.foo, y.foo)
756 self.assertIs(x[0], y[0])
757 self.assertIs(x.foo, y.foo)
758
759 def test_deepcopy_list_subclass(self):
760 class C(list):
761 pass
762 x = C([[1, 2], 3])
763 x.foo = [4, 5]
764 y = copy.deepcopy(x)
765 self.assertEqual(list(x), list(y))
766 self.assertEqual(x.foo, y.foo)
767 self.assertIsNot(x[0], y[0])
768 self.assertIsNot(x.foo, y.foo)
769
770 def test_copy_tuple_subclass(self):
771 class C(tuple):
772 pass
773 x = C([1, 2, 3])
774 self.assertEqual(tuple(x), (1, 2, 3))
775 y = copy.copy(x)
776 self.assertEqual(tuple(y), (1, 2, 3))
777
778 def test_deepcopy_tuple_subclass(self):
779 class C(tuple):
780 pass
781 x = C([[1, 2], 3])
782 self.assertEqual(tuple(x), ([1, 2], 3))
783 y = copy.deepcopy(x)
784 self.assertEqual(tuple(y), ([1, 2], 3))
785 self.assertIsNot(x, y)
786 self.assertIsNot(x[0], y[0])
787
788 def test_getstate_exc(self):
789 class EvilState(object):
790 def __getstate__(self):
791 raise ValueError("ain't got no stickin' state")
792 self.assertRaises(ValueError, copy.copy, EvilState())
793
794 def test_copy_function(self):
795 self.assertEqual(copy.copy(global_foo), global_foo)
796 def foo(x, y): return x+y
797 self.assertEqual(copy.copy(foo), foo)
798 bar = lambda: None
799 self.assertEqual(copy.copy(bar), bar)
800
801 def test_deepcopy_function(self):
802 self.assertEqual(copy.deepcopy(global_foo), global_foo)
803 def foo(x, y): return x+y
804 self.assertEqual(copy.deepcopy(foo), foo)
805 bar = lambda: None
806 self.assertEqual(copy.deepcopy(bar), bar)
807
808 def _check_weakref(self, _copy):
809 class C(object):
810 pass
811 obj = C()
812 x = weakref.ref(obj)
813 y = _copy(x)
814 self.assertIs(y, x)
815 del obj
816 y = _copy(x)
817 self.assertIs(y, x)
818
819 def test_copy_weakref(self):
820 self._check_weakref(copy.copy)
821
822 def test_deepcopy_weakref(self):
823 self._check_weakref(copy.deepcopy)
824
825 def _check_copy_weakdict(self, _dicttype):
826 class C(object):
827 pass
828 a, b, c, d = [C() for i in range(4)]
829 u = _dicttype()
830 u[a] = b
831 u[c] = d
832 v = copy.copy(u)
833 self.assertIsNot(v, u)
834 self.assertEqual(v, u)
835 self.assertEqual(v[a], b)
836 self.assertEqual(v[c], d)
837 self.assertEqual(len(v), 2)
838 del c, d
839 support.gc_collect() # For PyPy or other GCs.
840 self.assertEqual(len(v), 1)
841 x, y = C(), C()
842 # The underlying containers are decoupled
843 v[x] = y
844 self.assertNotIn(x, u)
845
846 def test_copy_weakkeydict(self):
847 self._check_copy_weakdict(weakref.WeakKeyDictionary)
848
849 def test_copy_weakvaluedict(self):
850 self._check_copy_weakdict(weakref.WeakValueDictionary)
851
852 def test_deepcopy_weakkeydict(self):
853 class C(object):
854 def __init__(self, i):
855 self.i = i
856 a, b, c, d = [C(i) for i in range(4)]
857 u = weakref.WeakKeyDictionary()
858 u[a] = b
859 u[c] = d
860 # Keys aren't copied, values are
861 v = copy.deepcopy(u)
862 self.assertNotEqual(v, u)
863 self.assertEqual(len(v), 2)
864 self.assertIsNot(v[a], b)
865 self.assertIsNot(v[c], d)
866 self.assertEqual(v[a].i, b.i)
867 self.assertEqual(v[c].i, d.i)
868 del c
869 support.gc_collect() # For PyPy or other GCs.
870 self.assertEqual(len(v), 1)
871
872 def test_deepcopy_weakvaluedict(self):
873 class C(object):
874 def __init__(self, i):
875 self.i = i
876 a, b, c, d = [C(i) for i in range(4)]
877 u = weakref.WeakValueDictionary()
878 u[a] = b
879 u[c] = d
880 # Keys are copied, values aren't
881 v = copy.deepcopy(u)
882 self.assertNotEqual(v, u)
883 self.assertEqual(len(v), 2)
884 (x, y), (z, t) = sorted(v.items(), key=lambda pair: pair[0].i)
885 self.assertIsNot(x, a)
886 self.assertEqual(x.i, a.i)
887 self.assertIs(y, b)
888 self.assertIsNot(z, c)
889 self.assertEqual(z.i, c.i)
890 self.assertIs(t, d)
891 del x, y, z, t
892 del d
893 support.gc_collect() # For PyPy or other GCs.
894 self.assertEqual(len(v), 1)
895
896 def test_deepcopy_bound_method(self):
897 class Foo(object):
898 def m(self):
899 pass
900 f = Foo()
901 f.b = f.m
902 g = copy.deepcopy(f)
903 self.assertEqual(g.m, g.b)
904 self.assertIs(g.b.__self__, g)
905 g.b()
906
907
908 class TestReplace(unittest.TestCase):
909
910 def test_unsupported(self):
911 self.assertRaises(TypeError, copy.replace, 1)
912 self.assertRaises(TypeError, copy.replace, [])
913 self.assertRaises(TypeError, copy.replace, {})
914 def f(): pass
915 self.assertRaises(TypeError, copy.replace, f)
916 class A: pass
917 self.assertRaises(TypeError, copy.replace, A)
918 self.assertRaises(TypeError, copy.replace, A())
919
920 def test_replace_method(self):
921 class A:
922 def __new__(cls, x, y=0):
923 self = object.__new__(cls)
924 self.x = x
925 self.y = y
926 return self
927
928 def __init__(self, *args, **kwargs):
929 self.z = self.x + self.y
930
931 def __replace__(self, **changes):
932 x = changes.get('x', self.x)
933 y = changes.get('y', self.y)
934 return type(self)(x, y)
935
936 attrs = attrgetter('x', 'y', 'z')
937 a = A(11, 22)
938 self.assertEqual(attrs(copy.replace(a)), (11, 22, 33))
939 self.assertEqual(attrs(copy.replace(a, x=1)), (1, 22, 23))
940 self.assertEqual(attrs(copy.replace(a, y=2)), (11, 2, 13))
941 self.assertEqual(attrs(copy.replace(a, x=1, y=2)), (1, 2, 3))
942
943 def test_namedtuple(self):
944 from collections import namedtuple
945 from typing import NamedTuple
946 PointFromCall = namedtuple('Point', 'x y', defaults=(0,))
947 class PointFromInheritance(PointFromCall):
948 pass
949 class PointFromClass(NamedTuple):
950 x: int
951 y: int = 0
952 for Point in (PointFromCall, PointFromInheritance, PointFromClass):
953 with self.subTest(Point=Point):
954 p = Point(11, 22)
955 self.assertIsInstance(p, Point)
956 self.assertEqual(copy.replace(p), (11, 22))
957 self.assertIsInstance(copy.replace(p), Point)
958 self.assertEqual(copy.replace(p, x=1), (1, 22))
959 self.assertEqual(copy.replace(p, y=2), (11, 2))
960 self.assertEqual(copy.replace(p, x=1, y=2), (1, 2))
961 with self.assertRaisesRegex(TypeError, 'unexpected field name'):
962 copy.replace(p, x=1, error=2)
963
964 def test_dataclass(self):
965 from dataclasses import dataclass
966 @dataclass
967 class C:
968 x: int
969 y: int = 0
970
971 attrs = attrgetter('x', 'y')
972 c = C(11, 22)
973 self.assertEqual(attrs(copy.replace(c)), (11, 22))
974 self.assertEqual(attrs(copy.replace(c, x=1)), (1, 22))
975 self.assertEqual(attrs(copy.replace(c, y=2)), (11, 2))
976 self.assertEqual(attrs(copy.replace(c, x=1, y=2)), (1, 2))
977 with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):
978 copy.replace(c, x=1, error=2)
979
980
981 class MiscTestCase(unittest.TestCase):
982 def test__all__(self):
983 support.check__all__(self, copy, not_exported={"dispatch_table", "error"})
984
985 def global_foo(x, y): return x+y
986
987
988 if __name__ == "__main__":
989 unittest.main()