MCPcopy Index your code
hub / github.com/python/cpython / test_missing

Method test_missing

Lib/test/test_dict.py:829–870  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

827 self.assertEqual({2} | {1:1}.items(), {(1,1), 2})
828
829 def test_missing(self):
830 # Make sure dict doesn't have a __missing__ method
831 self.assertNotHasAttr(dict, "__missing__")
832 self.assertNotHasAttr({}, "__missing__")
833 # Test several cases:
834 # (D) subclass defines __missing__ method returning a value
835 # (E) subclass defines __missing__ method raising RuntimeError
836 # (F) subclass sets __missing__ instance variable (no effect)
837 # (G) subclass doesn't define __missing__ at all
838 class D(dict):
839 def __missing__(self, key):
840 return 42
841 d = D({1: 2, 3: 4})
842 self.assertEqual(d[1], 2)
843 self.assertEqual(d[3], 4)
844 self.assertNotIn(2, d)
845 self.assertNotIn(2, d.keys())
846 self.assertEqual(d[2], 42)
847
848 class E(dict):
849 def __missing__(self, key):
850 raise RuntimeError(key)
851 e = E()
852 with self.assertRaises(RuntimeError) as c:
853 e[42]
854 self.assertEqual(c.exception.args, (42,))
855
856 class F(dict):
857 def __init__(self):
858 # An instance variable __missing__ should have no effect
859 self.__missing__ = lambda key: None
860 f = F()
861 with self.assertRaises(KeyError) as c:
862 f[42]
863 self.assertEqual(c.exception.args, (42,))
864
865 class G(dict):
866 pass
867 g = G()
868 with self.assertRaises(KeyError) as c:
869 g[42]
870 self.assertEqual(c.exception.args, (42,))
871
872 def test_tuple_keyerror(self):
873 # SF #1576657

Callers

nothing calls this directly

Calls 9

keysMethod · 0.95
assertNotHasAttrMethod · 0.80
assertNotInMethod · 0.80
DClass · 0.70
EClass · 0.70
FClass · 0.70
GClass · 0.70
assertEqualMethod · 0.45
assertRaisesMethod · 0.45

Tested by

no test coverage detected