Python – Expect an exception using pytest

When you want to add a test to verify that an exception is raised, you can use pytest.raises() like this:

with pytest.raises(Exception): code.Execute()
Code language: Python (python)

When the code doesn’t raise an exception, you’ll see a test failed message like this:

Failed: DID NOT RAISE <class 'Exception'>
Code language: plaintext (plaintext)

Example – Expect WordCounter to raise an exception

I’m implementing the following WordCounter class using a test-driven approach. The first thing I want to test is that it raises an exception when it’s passed invalid input.

class WordCounter: def __init__(self): pass def count_words(self, sentence): pass
Code language: Python (python)

I want WordCounter to raise the following custom exception:

class InvalidSentenceException(Exception): pass
Code language: Python (python)

Here is my test that verifies WordCounter.count_words() raises InvalidSentenceException when given an undefined sentence:

import pytest from word_utils import WordCounter, InvalidSentenceException def test_whensentencenone_throwsexception(): #arrange wc = WordCounter() sentence = None #act and assert with pytest.raises(InvalidSentenceException): wc.count_words(sentence)
Code language: Python (python)

When I run this test with the follow command:

python -m pytest
Code language: Bash (bash)

It fails with the following output:

1 failed in 0.11s FAILED tests/test_word_utils.py::test_whensentencenone_throwsexception - Failed: DID NOT RAISE <class 'word_utils.exceptions.InvalidSentenceException'>
Code language: plaintext (plaintext)

I need to write code that makes the test pass:

from .exceptions import InvalidSentenceException class WordCounter: def __init__(self): pass def count_words(self, sentence): if sentence is None: raise InvalidSentenceException() pass
Code language: Python (python)

Now when I run the test, it passes.

Leave a Comment