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:

def test_start_tasks_db_raises():
    """Make sure unsupported db raises an exception."""
    with pytest.raises(ValueError):
        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:

def test_start_tasks_db_raises():
    """Make sure unsupported db raises an exception."""
    with pytest.raises(ValueError) as excinfo:
        tasks.start_tasks_db('some/great/path', 'mysql')
    exception_msg = excinfo.value.args[0]
    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.

Related Posts

  • How to test if __name__ == "__main__"
  • Making a unique list in Python preserving the order
  • Annotate Querysets to Fetch Specific Values
  • Assert vs require in testify
  • Optimize Database Calls with Prefetch Related and Select Related