Skip to content

Commit

Permalink
Add PT011 and PT012 docs (#6362)
Browse files Browse the repository at this point in the history
  • Loading branch information
harupy authored Aug 7, 2023
1 parent 61532e8 commit 9c3fbcd
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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,
Expand Down

0 comments on commit 9c3fbcd

Please sign in to comment.