Last active
January 25, 2019 08:01
-
-
Save worldmind/86e07b4a5e44befb9560460d9317c079 to your computer and use it in GitHub Desktop.
Python unittest: Testing an exception is not raised
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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