When you use pytest, you sometimes need to cover code which might raise a specific exception. This can be done with the pytest.raises
helper function:
1def test_start_tasks_db_raises():
2 """Make sure unsupported db raises an exception."""
3 with pytest.raises(ValueError):
4 tasks.start_tasks_db('some/great/path', 'mysql')
However, in a lot of cases, testing the fact that an exception is raised is only half of the test. You probably want to check what exception message is thrown as well.
To do so, you can change your code to:
1def test_start_tasks_db_raises():
2 """Make sure unsupported db raises an exception."""
3 with pytest.raises(ValueError) as excinfo:
4 tasks.start_tasks_db('some/great/path', 'mysql')
5 exception_msg = excinfo.value.args[0]
6 assert exception_msg == "db_type must be a 'tiny' or 'mongo'"
When you store the exception, you can use value.args
to get to the actual exception message.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.