Skip to content

[ruff] Check for non-context-manager use of pytest.raises, pytest.warns, and pytest.deprecated_call (RUF061) #17368

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jun 16, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import warnings
import pytest


def raise_deprecation_warning(s):
warnings.warn(s, DeprecationWarning)
return s


def test_ok():
with pytest.deprecated_call():
raise_deprecation_warning("")


def test_error_trivial():
pytest.deprecated_call(raise_deprecation_warning, "deprecated")


def test_error_assign():
s = pytest.deprecated_call(raise_deprecation_warning, "deprecated")
print(s)


def test_error_lambda():
pytest.deprecated_call(lambda: warnings.warn("", DeprecationWarning))
25 changes: 25 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/ruff/RUF061_warns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import warnings
import pytest


def raise_user_warning(s):
warnings.warn(s, UserWarning)
return s


def test_ok():
with pytest.warns(UserWarning):
raise_user_warning("")


def test_error_trivial():
pytest.warns(UserWarning, raise_user_warning, "warning")


def test_error_assign():
s = pytest.warns(UserWarning, raise_user_warning, "warning")
print(s)


def test_error_lambda():
pytest.warns(UserWarning, lambda: warnings.warn("", UserWarning))
4 changes: 3 additions & 1 deletion crates/ruff_linter/src/checkers/ast/analyze/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -959,10 +959,12 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) {
if checker.any_enabled(&[
Rule::PytestRaisesWithoutException,
Rule::PytestRaisesTooBroad,
Rule::DeprecatedPytestRaisesCallableForm,
]) {
flake8_pytest_style::rules::raises_call(checker, call);
}
if checker.enabled(Rule::LegacyFormPytestRaisesWarnsDeprecatedCall) {
ruff::rules::legacy_raises_warns_deprecated_call(checker, call);
}
if checker.any_enabled(&[Rule::PytestWarnsWithoutWarning, Rule::PytestWarnsTooBroad]) {
flake8_pytest_style::rules::warns_call(checker, call);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_linter/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,6 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Flake8PytestStyle, "029") => (RuleGroup::Preview, rules::flake8_pytest_style::rules::PytestWarnsWithoutWarning),
(Flake8PytestStyle, "030") => (RuleGroup::Preview, rules::flake8_pytest_style::rules::PytestWarnsTooBroad),
(Flake8PytestStyle, "031") => (RuleGroup::Preview, rules::flake8_pytest_style::rules::PytestWarnsWithMultipleStatements),
(Flake8PytestStyle, "032") => (RuleGroup::Preview, rules::flake8_pytest_style::rules::DeprecatedPytestRaisesCallableForm),

// flake8-pie
(Flake8Pie, "790") => (RuleGroup::Stable, rules::flake8_pie::rules::UnnecessaryPlaceholder),
Expand Down Expand Up @@ -1015,6 +1014,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Ruff, "057") => (RuleGroup::Preview, rules::ruff::rules::UnnecessaryRound),
(Ruff, "058") => (RuleGroup::Preview, rules::ruff::rules::StarmapZip),
(Ruff, "059") => (RuleGroup::Preview, rules::ruff::rules::UnusedUnpackedVariable),
(Ruff, "061") => (RuleGroup::Preview, rules::ruff::rules::LegacyFormPytestRaisesWarnsDeprecatedCall),
(Ruff, "100") => (RuleGroup::Stable, rules::ruff::rules::UnusedNOQA),
(Ruff, "101") => (RuleGroup::Stable, rules::ruff::rules::RedirectedNOQA),
(Ruff, "102") => (RuleGroup::Preview, rules::ruff::rules::InvalidRuleCode),
Expand Down
6 changes: 0 additions & 6 deletions crates/ruff_linter/src/rules/flake8_pytest_style/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,12 +341,6 @@ mod tests {
Settings::default(),
"PT031"
)]
#[test_case(
Rule::DeprecatedPytestRaisesCallableForm,
Path::new("PT032.py"),
Settings::default(),
"PT032"
)]
fn test_pytest_style(
rule_code: Rule,
path: &Path,
Expand Down
188 changes: 3 additions & 185 deletions crates/ruff_linter/src/rules/flake8_pytest_style/rules/raises.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
use itertools::{Either, Itertools};
use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, ViolationMetadata};
use ruff_python_ast::helpers::is_compound_statement;
use ruff_python_ast::{self as ast, Expr, Stmt, StmtExpr, StmtWith, WithItem};
use ruff_python_ast::{self as ast, Expr, Stmt, WithItem};
use ruff_python_semantic::SemanticModel;
use ruff_python_trivia::{has_leading_content, has_trailing_content, leading_indentation};
use ruff_source_file::UniversalNewlines;
use ruff_text_size::{Ranged, TextRange};
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;
use crate::registry::Rule;
Expand Down Expand Up @@ -159,47 +156,6 @@ impl Violation for PytestRaisesWithoutException {
}
}

/// ## What it does
/// Checks for non-contextmanager use of `pytest.raises`.
///
/// ## Why is this bad?
/// The context-manager form is more readable, easier to extend, and supports additional kwargs.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// excinfo = pytest.raises(ValueError, int, "hello")
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// with pytest.raises(ValueError) as excinfo:
/// int("hello")
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)
#[derive(ViolationMetadata)]
pub(crate) struct DeprecatedPytestRaisesCallableForm;

impl Violation for DeprecatedPytestRaisesCallableForm {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;

#[derive_message_formats]
fn message(&self) -> String {
"Use context-manager form of `pytest.raises()`".to_string()
}

fn fix_title(&self) -> Option<String> {
Some("Use `pytest.raises()` as a context-manager".to_string())
}
}

pub(crate) fn is_pytest_raises(func: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(func)
Expand Down Expand Up @@ -229,38 +185,6 @@ pub(crate) fn raises_call(checker: &Checker, call: &ast::ExprCall) {
}
}

if checker.enabled(Rule::DeprecatedPytestRaisesCallableForm)
&& call.arguments.find_argument("func", 1).is_some()
{
let mut diagnostic = Diagnostic::new(DeprecatedPytestRaisesCallableForm, call.range());
let stmt = checker.semantic().current_statement();
if !has_leading_content(stmt.start(), checker.source())
&& !has_trailing_content(stmt.end(), checker.source())
{
if let Some(with_stmt) = try_fix_legacy_raises(stmt, checker.semantic()) {
let generated = checker.generator().stmt(&Stmt::With(with_stmt));
let first_line = checker.locator().line_str(stmt.start());
let indentation = leading_indentation(first_line);
let mut indented = String::new();
for (idx, line) in generated.universal_newlines().enumerate() {
if idx == 0 {
indented.push_str(&line);
} else {
indented.push_str(checker.stylist().line_ending().as_str());
indented.push_str(indentation);
indented.push_str(&line);
}
}

diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
indented,
stmt.range(),
)));
}
}
checker.report_diagnostic(diagnostic);
}

if checker.enabled(Rule::PytestRaisesTooBroad) {
// Pytest.raises has two overloads
// ```py
Expand Down Expand Up @@ -348,109 +272,3 @@ fn exception_needs_match(checker: &Checker, exception: &Expr) {
));
}
}

fn try_fix_legacy_raises(stmt: &Stmt, semantic: &SemanticModel) -> Option<StmtWith> {
match stmt {
Stmt::Expr(StmtExpr { value, .. }) => {
let call = value.as_call_expr()?;

if is_pytest_raises(&call.func, semantic) {
generate_with_raises(call, None, None)
} else {
let inner_raises_call = call
.func
.as_attribute_expr()
.filter(|expr_attribute| &expr_attribute.attr == "match")
.and_then(|expr_attribute| expr_attribute.value.as_call_expr())
.filter(|inner_call| is_pytest_raises(&inner_call.func, semantic))?;
generate_with_raises(inner_raises_call, call.arguments.args.first(), None)
}
}
Stmt::Assign(ast::StmtAssign {
range: _,
targets,
value,
}) => {
let [target] = targets.as_slice() else {
return None;
};

let raises_call = value
.as_call_expr()
.filter(|call| is_pytest_raises(&call.func, semantic))?;

let optional_vars = Some(target);
let match_call = None;
generate_with_raises(raises_call, match_call, optional_vars)
}
_ => None,
}
}

fn generate_with_raises(
legacy_raises_call: &ast::ExprCall,
match_arg: Option<&Expr>,
optional_vars: Option<&Expr>,
) -> Option<StmtWith> {
let expected_exception = legacy_raises_call
.arguments
.find_argument_value("expected_exception", 0)?;

let func = legacy_raises_call
.arguments
.find_argument_value("func", 1)?;

let raises_call = ast::ExprCall {
range: TextRange::default(),
func: legacy_raises_call.func.clone(),
arguments: ast::Arguments {
range: TextRange::default(),
args: Box::new([expected_exception.clone()]),
keywords: match_arg
.map(|expr| ast::Keyword {
// Take range from the original expression so that the keyword
// argument is generated after positional arguments
range: expr.range(),
arg: Some(ast::Identifier::new("match", TextRange::default())),
value: expr.clone(),
})
.as_slice()
.into(),
},
};

let (func_args, func_keywords): (Vec<_>, Vec<_>) = legacy_raises_call
.arguments
.arguments_source_order()
.skip(2)
.partition_map(|arg_or_keyword| match arg_or_keyword {
ast::ArgOrKeyword::Arg(expr) => Either::Left(expr.clone()),
ast::ArgOrKeyword::Keyword(keyword) => Either::Right(keyword.clone()),
});
let func_args = func_args.into_boxed_slice();
let func_keywords = func_keywords.into_boxed_slice();

let func_call = ast::ExprCall {
range: TextRange::default(),
func: Box::new(func.clone()),
arguments: ast::Arguments {
range: TextRange::default(),
args: func_args,
keywords: func_keywords,
},
};

Some(StmtWith {
range: TextRange::default(),
is_async: false,
items: vec![WithItem {
range: TextRange::default(),
context_expr: raises_call.into(),
optional_vars: optional_vars.map(|var| Box::new(var.clone())),
}],
body: vec![Stmt::Expr(StmtExpr {
range: TextRange::default(),
value: Box::new(func_call.into()),
})],
})
}
12 changes: 12 additions & 0 deletions crates/ruff_linter/src/rules/ruff/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,18 @@ mod tests {
#[test_case(Rule::UnusedUnpackedVariable, Path::new("RUF059_1.py"))]
#[test_case(Rule::UnusedUnpackedVariable, Path::new("RUF059_2.py"))]
#[test_case(Rule::UnusedUnpackedVariable, Path::new("RUF059_3.py"))]
#[test_case(
Rule::LegacyFormPytestRaisesWarnsDeprecatedCall,
Path::new("RUF061_raises.py")
)]
#[test_case(
Rule::LegacyFormPytestRaisesWarnsDeprecatedCall,
Path::new("RUF061_warns.py")
)]
#[test_case(
Rule::LegacyFormPytestRaisesWarnsDeprecatedCall,
Path::new("RUF061_deprecated_call.py")
)]
#[test_case(Rule::RedirectedNOQA, Path::new("RUF101_0.py"))]
#[test_case(Rule::RedirectedNOQA, Path::new("RUF101_1.py"))]
#[test_case(Rule::InvalidRuleCode, Path::new("RUF102.py"))]
Expand Down
Loading
Loading