diff --git a/docs/usage/functions.md b/docs/usage/functions.md index c6f5e577..386ca6c6 100644 --- a/docs/usage/functions.md +++ b/docs/usage/functions.md @@ -49,3 +49,41 @@ def test_function2(): Then running `uv run karva test` will result in two test fails. You can still use `pytest.fail()` to fail tests. + +## Raises + +If you want to assert that a block of code raises a specific exception, use `karva.raises()`. + +```python title="test.py" +import karva + +def test_function(): + with karva.raises(ValueError): + raise ValueError("something went wrong") +``` + +You can optionally provide a `match` parameter to match a regex pattern against the string representation of the exception. + +```python title="test.py" +import karva + +def test_function(): + with karva.raises(ValueError, match="something"): + raise ValueError("something went wrong") +``` + +You can access the exception info by using the `as` keyword. The returned object has `type`, `value`, and `tb` properties. + +```python title="test.py" +import karva + +def test_function(): + with karva.raises(ValueError) as exc_info: + raise ValueError("something went wrong") + + assert exc_info.type is ValueError + assert str(exc_info.value) == "something went wrong" + assert exc_info.tb is not None +``` + +You can still use `pytest.raises()` to assert exceptions.