test_userdict.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # Check every path through every method of UserDict
  2. from test import mapping_tests
  3. import unittest
  4. import collections
  5. d0 = {}
  6. d1 = {"one": 1}
  7. d2 = {"one": 1, "two": 2}
  8. d3 = {"one": 1, "two": 3, "three": 5}
  9. d4 = {"one": None, "two": None}
  10. d5 = {"one": 1, "two": 1}
  11. class UserDictTest(mapping_tests.TestHashMappingProtocol):
  12. type2test = collections.UserDict
  13. def test_all(self):
  14. # Test constructors
  15. u = collections.UserDict()
  16. u0 = collections.UserDict(d0)
  17. u1 = collections.UserDict(d1)
  18. u2 = collections.UserDict(d2)
  19. uu = collections.UserDict(u)
  20. uu0 = collections.UserDict(u0)
  21. uu1 = collections.UserDict(u1)
  22. uu2 = collections.UserDict(u2)
  23. # keyword arg constructor
  24. self.assertEqual(collections.UserDict(one=1, two=2), d2)
  25. # item sequence constructor
  26. self.assertEqual(collections.UserDict([('one',1), ('two',2)]), d2)
  27. self.assertEqual(collections.UserDict(dict=[('one',1), ('two',2)]),
  28. {'dict': [('one', 1), ('two', 2)]})
  29. # both together
  30. self.assertEqual(collections.UserDict([('one',1), ('two',2)], two=3, three=5), d3)
  31. # alternate constructor
  32. self.assertEqual(collections.UserDict.fromkeys('one two'.split()), d4)
  33. self.assertEqual(collections.UserDict().fromkeys('one two'.split()), d4)
  34. self.assertEqual(collections.UserDict.fromkeys('one two'.split(), 1), d5)
  35. self.assertEqual(collections.UserDict().fromkeys('one two'.split(), 1), d5)
  36. self.assertTrue(u1.fromkeys('one two'.split()) is not u1)
  37. self.assertIsInstance(u1.fromkeys('one two'.split()), collections.UserDict)
  38. self.assertIsInstance(u2.fromkeys('one two'.split()), collections.UserDict)
  39. # Test __repr__
  40. self.assertEqual(str(u0), str(d0))
  41. self.assertEqual(repr(u1), repr(d1))
  42. self.assertIn(repr(u2), ("{'one': 1, 'two': 2}",
  43. "{'two': 2, 'one': 1}"))
  44. # Test rich comparison and __len__
  45. all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2]
  46. for a in all:
  47. for b in all:
  48. self.assertEqual(a == b, len(a) == len(b))
  49. # Test __getitem__
  50. self.assertEqual(u2["one"], 1)
  51. self.assertRaises(KeyError, u1.__getitem__, "two")
  52. # Test __setitem__
  53. u3 = collections.UserDict(u2)
  54. u3["two"] = 2
  55. u3["three"] = 3
  56. # Test __delitem__
  57. del u3["three"]
  58. self.assertRaises(KeyError, u3.__delitem__, "three")
  59. # Test clear
  60. u3.clear()
  61. self.assertEqual(u3, {})
  62. # Test copy()
  63. u2a = u2.copy()
  64. self.assertEqual(u2a, u2)
  65. u2b = collections.UserDict(x=42, y=23)
  66. u2c = u2b.copy() # making a copy of a UserDict is special cased
  67. self.assertEqual(u2b, u2c)
  68. class MyUserDict(collections.UserDict):
  69. def display(self): print(self)
  70. m2 = MyUserDict(u2)
  71. m2a = m2.copy()
  72. self.assertEqual(m2a, m2)
  73. # SF bug #476616 -- copy() of UserDict subclass shared data
  74. m2['foo'] = 'bar'
  75. self.assertNotEqual(m2a, m2)
  76. # Test keys, items, values
  77. self.assertEqual(sorted(u2.keys()), sorted(d2.keys()))
  78. self.assertEqual(sorted(u2.items()), sorted(d2.items()))
  79. self.assertEqual(sorted(u2.values()), sorted(d2.values()))
  80. # Test "in".
  81. for i in u2.keys():
  82. self.assertIn(i, u2)
  83. self.assertEqual(i in u1, i in d1)
  84. self.assertEqual(i in u0, i in d0)
  85. # Test update
  86. t = collections.UserDict()
  87. t.update(u2)
  88. self.assertEqual(t, u2)
  89. # Test get
  90. for i in u2.keys():
  91. self.assertEqual(u2.get(i), u2[i])
  92. self.assertEqual(u1.get(i), d1.get(i))
  93. self.assertEqual(u0.get(i), d0.get(i))
  94. # Test "in" iteration.
  95. for i in range(20):
  96. u2[i] = str(i)
  97. ikeys = []
  98. for k in u2:
  99. ikeys.append(k)
  100. keys = u2.keys()
  101. self.assertEqual(set(ikeys), set(keys))
  102. # Test setdefault
  103. t = collections.UserDict()
  104. self.assertEqual(t.setdefault("x", 42), 42)
  105. self.assertIn("x", t)
  106. self.assertEqual(t.setdefault("x", 23), 42)
  107. # Test pop
  108. t = collections.UserDict(x=42)
  109. self.assertEqual(t.pop("x"), 42)
  110. self.assertRaises(KeyError, t.pop, "x")
  111. self.assertEqual(t.pop("x", 1), 1)
  112. t["x"] = 42
  113. self.assertEqual(t.pop("x", 1), 42)
  114. # Test popitem
  115. t = collections.UserDict(x=42)
  116. self.assertEqual(t.popitem(), ("x", 42))
  117. self.assertRaises(KeyError, t.popitem)
  118. def test_init(self):
  119. for kw in 'self', 'other', 'iterable':
  120. self.assertEqual(list(collections.UserDict(**{kw: 42}).items()),
  121. [(kw, 42)])
  122. self.assertEqual(list(collections.UserDict({}, dict=42).items()),
  123. [('dict', 42)])
  124. self.assertEqual(list(collections.UserDict({}, dict=None).items()),
  125. [('dict', None)])
  126. self.assertEqual(list(collections.UserDict(dict={'a': 42}).items()),
  127. [('dict', {'a': 42})])
  128. self.assertRaises(TypeError, collections.UserDict, 42)
  129. self.assertRaises(TypeError, collections.UserDict, (), ())
  130. self.assertRaises(TypeError, collections.UserDict.__init__)
  131. def test_update(self):
  132. for kw in 'self', 'dict', 'other', 'iterable':
  133. d = collections.UserDict()
  134. d.update(**{kw: 42})
  135. self.assertEqual(list(d.items()), [(kw, 42)])
  136. self.assertRaises(TypeError, collections.UserDict().update, 42)
  137. self.assertRaises(TypeError, collections.UserDict().update, {}, {})
  138. self.assertRaises(TypeError, collections.UserDict.update)
  139. def test_missing(self):
  140. # Make sure UserDict doesn't have a __missing__ method
  141. self.assertEqual(hasattr(collections.UserDict, "__missing__"), False)
  142. # Test several cases:
  143. # (D) subclass defines __missing__ method returning a value
  144. # (E) subclass defines __missing__ method raising RuntimeError
  145. # (F) subclass sets __missing__ instance variable (no effect)
  146. # (G) subclass doesn't define __missing__ at all
  147. class D(collections.UserDict):
  148. def __missing__(self, key):
  149. return 42
  150. d = D({1: 2, 3: 4})
  151. self.assertEqual(d[1], 2)
  152. self.assertEqual(d[3], 4)
  153. self.assertNotIn(2, d)
  154. self.assertNotIn(2, d.keys())
  155. self.assertEqual(d[2], 42)
  156. class E(collections.UserDict):
  157. def __missing__(self, key):
  158. raise RuntimeError(key)
  159. e = E()
  160. try:
  161. e[42]
  162. except RuntimeError as err:
  163. self.assertEqual(err.args, (42,))
  164. else:
  165. self.fail("e[42] didn't raise RuntimeError")
  166. class F(collections.UserDict):
  167. def __init__(self):
  168. # An instance variable __missing__ should have no effect
  169. self.__missing__ = lambda key: None
  170. collections.UserDict.__init__(self)
  171. f = F()
  172. try:
  173. f[42]
  174. except KeyError as err:
  175. self.assertEqual(err.args, (42,))
  176. else:
  177. self.fail("f[42] didn't raise KeyError")
  178. class G(collections.UserDict):
  179. pass
  180. g = G()
  181. try:
  182. g[42]
  183. except KeyError as err:
  184. self.assertEqual(err.args, (42,))
  185. else:
  186. self.fail("g[42] didn't raise KeyError")
  187. if __name__ == "__main__":
  188. unittest.main()