Testing that an Exception is Raised

This is part of a series of posts on Python unit testing.

Previously we tested that the validate_url() function returns the given URL if it’s a valid URL. If the given URL is not valid then validate_url() is supposed to raise a ValueError exception. To test this we need to use pytest.raises(). Here is a test that expects validate_url() to raise a ValueError:

def test_validate_url_rejects_urls_without_domains():
    with pytest.raises(ValueError):
        validate_url('http:///path')

This test will fail if the block of code inside the with statement doesn’t raise ValueError, otherwise the test will pass.

There’s also pytest.warns(), for testing that code raises a warning in the same way.

In the next post we’ll look at the arrange, act, assert recipe for writing a good test.

Sean Hammond,