How To Test Exceptions In Python With Pytest And With Statement

The aim of this page📝 is to demonstrate the syntax for python unit tests (pytest) that pass if an exception is thrown as expected. I have a function validate_and_capitalize where I pass a section_name and section_folders and I need to test if when an improper value is passed, the ValueError with the given message is raised.

Rubberduck of the 👆 function:

  1. import pytest
  2. pass pytest.raises(Exception) into with statement
  3. in the block, call the function that is expected to fail
  4. assert exception type with e.type == <exception_type>, e.g. assert e.type == ValueError
  5. if needed, assert an error message assert "<error_msg>" in str(e.value), e.g.