Framework Mode - Testing custom exceptions
Folder Structure
tests/ ├── test_custom_exceptions.py ├── conftest.py utils/ ├── exceptions.py ├── helpers.py pytest.ini
tests/ ├── test_custom_exceptions.py ├── conftest.py utils/ ├── exceptions.py ├── helpers.py pytest.ini
utils/exceptions.py contains user-defined exception classes.utils/helpers.py has functions that may raise custom exceptions.tests/test_custom_exceptions.py contains pytest test functions that verify the custom exceptions are raised correctly.pytest.ini for pytest settings and conftest.py for fixtures or shared test setup.pytest.raises() context manager to assert exceptions are raised as expected.pytest-html or pytest-junitxml for detailed test results.pytest.raises() context manager for clear and readable exception assertions.Exception or a relevant base and not contain complex logic.conftest.py to provide test data or objects that trigger exceptions, avoiding duplication.Where would you add a new custom exception class for handling invalid user input in this framework structure?
pytest.raises() in testing custom exceptions?pytest.raises()foo() raises a custom exception MyError using pytest?with and call the function inside the block.class MyError(Exception):
pass
def func():
raise MyError("Error happened")
def test_func():
with pytest.raises(MyError) as exc_info:
func()
assert str(exc_info.value) == "Error happened"def test_error():
with pytest.raises(ValueError):
raise TypeError("Wrong type")MyError that can be raised with different messages. How can you write a pytest test that checks the exception is raised and the message contains the word "timeout" regardless of other text?match argument to check if the exception message matches a regex or substring.with pytest.raises(MyError, match="timeout"): correctly uses the match parameter to verify the message contains "timeout". with pytest.raises(MyError) as e: followed by assert str(e.value) == "timeout" only checks for exact match, failing if there is extra text. Options C and D use invalid syntax.Pass the test and this pattern moves unknown