Python Unit Test Dictionary Assert KeyError
<p>I wasn't sure how to create a Python unittest to check if a dictionary returned a KeyError. I thought the unit test would call the dictionary key so it would look like this:</p>

<pre><code>def test_dict_keyerror_should_appear(self):
    my_dict = {'hey': 'world'}
    self.assertRaises(KeyError, my_dict['some_key'])
</code></pre>

<p>However, my test would just error out with a <strong>KeyError</strong> instead of asserting that a KeyError occurred.</p>

<p>Another option would be to use <a href="https://docs.python.org/3/library/operator.html#operator.getitem" rel="nofollow"><code>operator.getitem</code></a>:</p>

<pre><code>from operator import getitem

self.assertRaises(KeyError, getitem, my_dict, 'some_key')
</code></pre>

python python-unittest