Skip to content

Instantly share code, notes, and snippets.

@worldmind
Last active January 25, 2019 08:01
Show Gist options
  • Save worldmind/86e07b4a5e44befb9560460d9317c079 to your computer and use it in GitHub Desktop.
Save worldmind/86e07b4a5e44befb9560460d9317c079 to your computer and use it in GitHub Desktop.
Python unittest: Testing an exception is not raised
import sys
import unittest
from contextlib import contextmanager
@contextmanager
def assert_not_raises(self, exc_type):
try:
yield None
except exc_type:
tb = sys.exc_info()[2]
msg = '{} raised'.format(exc_type.__name__)
raise self.failureException(msg).with_traceback(tb) from None
unittest.TestCase.assertNotRaises = assert_not_raises
class TestCase(unittest.TestCase):
def test_it_does_not_raise_key_error(self):
data = {}
with self.assertNotRaises(KeyError):
data['missing key']
def test_not_raise(self):
with self.assertNotRaises(Exception):
pass
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment