diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs index dae4157ab7421..c8c824648b72b 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs @@ -11,6 +11,35 @@ use crate::registry::Rule; use super::helpers::is_empty_or_null_string; +/// ## What it does +/// Checks for `pytest.raises` context managers with multiple statements. +/// +/// ## Why is this bad? +/// When a `pytest.raises` is used as a context manager and contains multiple +/// statements, it can lead to the test passing when it actually should fail. +/// To avoid this, a `pytest.raises` context manager should only contain +/// a single simple statement that raises the expected exception. +/// +/// ## Example +/// ```python +/// def test_foo(): +/// with pytest.raises(MyError): +/// setup() # may raise `MyError` +/// func_to_test() +/// assert foo() # not executed +/// ``` +/// +/// Use instead: +/// ```python +/// def test_foo(): +/// setup() +/// with pytest.raises(MyException): +/// func_to_test() +/// assert foo() +/// ``` +/// +/// ## References +/// - [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises) #[violation] pub struct PytestRaisesWithMultipleStatements; @@ -21,6 +50,41 @@ impl Violation for PytestRaisesWithMultipleStatements { } } +/// ## What it does +/// Checks for `pytest.raises` calls without a `match` parameter. +/// +/// ## Why is this bad? +/// `pytest.raises(Error)` will catch any `Error` and may catch errors that are +/// unrelated to the code under test. To avoid this, `pytest.raises` should be +/// called with a `match` parameter. The exception names that require a `match` +/// parameter can be configured via the +/// `flake8-pytest-style.raises-require-match-for` and +/// `flake8-pytest-style.raises-extend-require-match-for` settings. +/// +/// ## Example +/// ```python +/// def test_foo(): +/// with pytest.raises(ValueError): +/// ... +/// +/// # empty string is also an error +/// with pytest.raises(ValueError, match=""): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// def test_foo(): +/// with pytest.raises(ValueError, match="expected message"): +/// ... +/// ``` +/// +/// ## Options +/// - `flake8-pytest-style.raises-require-match-for` +/// - `flake8-pytest-style.raises-extend-require-match-for` +/// +/// ## References +/// - [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises) #[violation] pub struct PytestRaisesTooBroad { exception: String,