test_copy.py 27 KB

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