How To Test Exceptions In Python With Pytest And With Statement
Oct 1, 2021
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:
- import
pytest
- pass
pytest.raises(Exception)
intowith
statement - in the block, call the function that is expected to fail
- assert exception type with
e.type == <exception_type>
, e.g.assert e.type == ValueError
- if needed, assert an error message
assert "<error_msg>" in str(e.value)
, e.g.