Remove parentheses when rewriting assert calls to statements (#7464)

This commit is contained in:
Charlie Marsh 2023-09-17 11:18:56 -04:00 committed by GitHub
parent 64b929bc29
commit 12acd191e1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 1 deletions

View File

@ -92,3 +92,9 @@ class Test(unittest.TestCase):
def test_fail_if_equal(self):
self.failIfEqual(1, 2) # Error
# Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1722459517
(self.assertTrue(
"piAx_piAy_beta[r][x][y] = {17}".format(
self.model.piAx_piAy_beta[r][x][y])))

View File

@ -10,6 +10,7 @@ use libcst_native::{
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::Truthiness;
use ruff_python_ast::parenthesize::parenthesized_range;
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{
self as ast, Arguments, BoolOp, ExceptHandler, Expr, Keyword, Stmt, UnaryOp,
@ -293,7 +294,13 @@ pub(crate) fn unittest_assertion(
if let Ok(stmt) = unittest_assert.generate_assert(args, keywords) {
diagnostic.set_fix(Fix::suggested(Edit::range_replacement(
checker.generator().stmt(&stmt),
expr.range(),
parenthesized_range(
expr.into(),
checker.semantic().current_statement().into(),
checker.indexer().comment_ranges(),
checker.locator().contents(),
)
.unwrap_or(expr.range()),
)));
}
}

View File

@ -637,5 +637,27 @@ PT009.py:94:9: PT009 [*] Use a regular `assert` instead of unittest-style `failI
93 93 | def test_fail_if_equal(self):
94 |- self.failIfEqual(1, 2) # Error
94 |+ assert 1 != 2 # Error
95 95 |
96 96 |
97 97 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1722459517
PT009.py:98:2: PT009 [*] Use a regular `assert` instead of unittest-style `assertTrue`
|
97 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1722459517
98 | (self.assertTrue(
| ^^^^^^^^^^^^^^^ PT009
99 | "piAx_piAy_beta[r][x][y] = {17}".format(
100 | self.model.piAx_piAy_beta[r][x][y])))
|
= help: Replace `assertTrue(...)` with `assert ...`
Suggested fix
95 95 |
96 96 |
97 97 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1722459517
98 |-(self.assertTrue(
99 |- "piAx_piAy_beta[r][x][y] = {17}".format(
100 |- self.model.piAx_piAy_beta[r][x][y])))
98 |+assert "piAx_piAy_beta[r][x][y] = {17}".format(self.model.piAx_piAy_beta[r][x][y])