Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
26 changes: 26 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_pytest_style/PT014.py

@harupy harupy Aug 15, 2023

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flake8_pytest_style result:

> flake8 crates/ruff/resources/test/fixtures/flake8_pytest_style/PT014.py
crates/ruff/resources/test/fixtures/flake8_pytest_style/PT014.py:4:2: PT014 found duplicate test cases (1, 2) in @pytest.mark.parametrize
crates/ruff/resources/test/fixtures/flake8_pytest_style/PT014.py:14:2: PT014 found duplicate test cases (1, 2) in @pytest.mark.parametrize
crates/ruff/resources/test/fixtures/flake8_pytest_style/PT014.py:14:2: PT014 found duplicate test cases (3, 4) in @pytest.mark.parametrize
crates/ruff/resources/test/fixtures/flake8_pytest_style/PT014.py:19:2: PT014 found duplicate test cases (1, 2) in @pytest.mark.parametrize

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import pytest


@pytest.mark.parametrize("x", [1, 1, 2])
def test_error_literal(x):
...


a = 1
b = 2
c = 3


@pytest.mark.parametrize("x", [a, a, b, b, c])
def test_error_expr_simple(x):
...


@pytest.mark.parametrize("x", [(a, b), (a, b), (b, c)])
def test_error_expr_complex(x):
...


@pytest.mark.parametrize("x", [1, 2])
def test_ok(x):
...
1 change: 1 addition & 0 deletions crates/ruff/src/checkers/ast/analyze/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
if checker.any_enabled(&[
Rule::PytestParametrizeNamesWrongType,
Rule::PytestParametrizeValuesWrongType,
Rule::PytestDuplicateParametrizeTestCases,
]) {
flake8_pytest_style::rules::parametrize(checker, decorator_list);
}
Expand Down
1 change: 1 addition & 0 deletions crates/ruff/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Flake8PytestStyle, "011") => (RuleGroup::Unspecified, rules::flake8_pytest_style::rules::PytestRaisesTooBroad),
(Flake8PytestStyle, "012") => (RuleGroup::Unspecified, rules::flake8_pytest_style::rules::PytestRaisesWithMultipleStatements),
(Flake8PytestStyle, "013") => (RuleGroup::Unspecified, rules::flake8_pytest_style::rules::PytestIncorrectPytestImport),
(Flake8PytestStyle, "014") => (RuleGroup::Unspecified, rules::flake8_pytest_style::rules::PytestDuplicateParametrizeTestCases),
(Flake8PytestStyle, "015") => (RuleGroup::Unspecified, rules::flake8_pytest_style::rules::PytestAssertAlwaysFalse),
(Flake8PytestStyle, "016") => (RuleGroup::Unspecified, rules::flake8_pytest_style::rules::PytestFailWithoutMessage),
(Flake8PytestStyle, "017") => (RuleGroup::Unspecified, rules::flake8_pytest_style::rules::PytestAssertInExcept),
Expand Down
6 changes: 6 additions & 0 deletions crates/ruff/src/rules/flake8_pytest_style/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,12 @@ mod tests {
Settings::default(),
"PT013"
)]
#[test_case(
Rule::PytestDuplicateParametrizeTestCases,
Path::new("PT014.py"),
Settings::default(),
"PT014"
)]
#[test_case(
Rule::PytestAssertAlwaysFalse,
Path::new("PT015.py"),
Expand Down
86 changes: 86 additions & 0 deletions crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use itertools::Itertools;

use ruff_python_ast::{
self as ast, Arguments, Constant, Decorator, Expr, ExprContext, PySourceType, Ranged,
};
Expand All @@ -6,6 +8,7 @@ use ruff_text_size::TextRange;

use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_codegen::Generator;
use ruff_source_file::Locator;

Expand Down Expand Up @@ -166,6 +169,58 @@ impl Violation for PytestParametrizeValuesWrongType {
}
}

/// ## What it does
/// Checks for duplicate test cases in `pytest.mark.parametrize`.
///
/// ## Why is this bad?
/// Duplicate test cases are redundant and should be removed.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.mark.parametrize(
/// ("param1", "param2"),
/// [
/// (1, 2),
/// (1, 2),
/// ],
/// )
/// def test_foo(param1, param2):
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.mark.parametrize(
/// ("param1", "param2"),
/// [
/// (1, 2),
/// ],
/// )
/// def test_foo(param1, param2):
/// ...
/// ```
///
/// ## References
/// - [`pytest` documentation: How to parametrize fixtures and test functions](https://docs.pytest.org/en/latest/how-to/parametrize.html#pytest-mark-parametrize)
#[violation]
pub struct PytestDuplicateParametrizeTestCases {
pub indices: (usize, usize),
}

impl Violation for PytestDuplicateParametrizeTestCases {
#[derive_message_formats]
fn message(&self) -> String {
let PytestDuplicateParametrizeTestCases { indices } = self;
format!("Found duplicate test cases {indices:?} in `@pytest.mark.parametrize`")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we say "at indices ..."? I wasn't sure what the message meant at first.

@harupy harupy Aug 15, 2023

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we raise PT014 against items that should be removed?

# Example

[1, 1, 2]
    ^ PT014 ...

This allows us to remove indices.

@charliermarsh charliermarsh Aug 15, 2023

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it makes sense to use the range of the duplicated item, so that we underline the duplicated item specifically

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

# Example

[100, 100, 100, 200]
      ^^^  ^^^

If we have multiple duplicated items, we underline them?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we support highlighting multiple ranges. In that case, they'd each need to be a new violation which seems okay.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think in the duplicate value rule, we just highlight the second value (i.e., the one that is a duplicate). That seems reasonable to me. (We could also mention the index of which it's a duplicate in the message.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

# Example

[100, 100, 100, 200]
      ^^^ PT014: duplicate of item at {0}

so it should look like this?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, and the same for the next 100 -- one violation for each duplicate (but no violation for the first 100), would be my suggestion.

}
}

fn elts_to_csv(elts: &[Expr], generator: Generator) -> Option<String> {
let all_literals = elts.iter().all(|expr| {
matches!(
Expand Down Expand Up @@ -472,6 +527,7 @@ fn check_values(checker: &mut Checker, names: &Expr, values: &Expr) {
values.range(),
));
}

if is_multi_named {
handle_value_rows(checker, elts, values_type, values_row_type);
}
Expand All @@ -494,6 +550,31 @@ fn check_values(checker: &mut Checker, names: &Expr, values: &Expr) {
}
}

fn find_duplicates(elts: &[Expr]) -> Vec<(usize, usize)> {
let mut duplicates: Vec<(usize, usize)> = Vec::new();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we use a SmallVec since it's unlikely for there to be many duplicates?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tend to prefer Vec unless we can demonstrate that SmallVec has better performance. In this case, we probably don't expect any duplicates in general, in which case this will never allocate anyway, so seems okay in my opinion.

for ((idx1, elt1), (idx2, elt2)) in elts.iter().enumerate().tuple_combinations() {
if ComparableExpr::from(elt1) == ComparableExpr::from(elt2) {
duplicates.push((idx1 + 1, idx2 + 1));
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'd suggest using an FxHashSet or FxHashMap here... As-is, this is quadratic, since we're checking every value against every other value. It's sometimes better to use a vector if you know the number of items is really small, but this also means we're re-computing the hash many times over.

duplicates
}

/// PT014
fn check_duplicates(checker: &mut Checker, values: &Expr) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it feasible to factor this so the type of values is more meaningful/narrow?

match values {
Expr::List(ast::ExprList { elts, .. }) | Expr::Tuple(ast::ExprTuple { elts, .. }) => {
for indices in find_duplicates(elts) {
checker.diagnostics.push(Diagnostic::new(
PytestDuplicateParametrizeTestCases { indices },
values.range(),
));
}
}
_ => {}
}
}

fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) {
let mut diagnostic = Diagnostic::new(
PytestParametrizeNamesWrongType {
Expand Down Expand Up @@ -567,6 +648,11 @@ pub(crate) fn parametrize(checker: &mut Checker, decorators: &[Decorator]) {
}
}
}
if checker.enabled(Rule::PytestDuplicateParametrizeTestCases) {
if let [_, values, ..] = &args[..] {
check_duplicates(checker, values);
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
source: crates/ruff/src/rules/flake8_pytest_style/mod.rs
---
PT014.py:4:31: PT014 Found duplicate test cases (1, 2) in `@pytest.mark.parametrize`
|
4 | @pytest.mark.parametrize("x", [1, 1, 2])
| ^^^^^^^^^ PT014
5 | def test_error_literal(x):
6 | ...
|

PT014.py:14:31: PT014 Found duplicate test cases (1, 2) in `@pytest.mark.parametrize`
|
14 | @pytest.mark.parametrize("x", [a, a, b, b, c])
| ^^^^^^^^^^^^^^^ PT014
15 | def test_error_expr_simple(x):
16 | ...
|

PT014.py:14:31: PT014 Found duplicate test cases (3, 4) in `@pytest.mark.parametrize`
|
14 | @pytest.mark.parametrize("x", [a, a, b, b, c])
| ^^^^^^^^^^^^^^^ PT014
15 | def test_error_expr_simple(x):
16 | ...
|

PT014.py:19:31: PT014 Found duplicate test cases (1, 2) in `@pytest.mark.parametrize`
|
19 | @pytest.mark.parametrize("x", [(a, b), (a, b), (b, c)])
| ^^^^^^^^^^^^^^^^^^^^^^^^ PT014
20 | def test_error_expr_complex(x):
21 | ...
|


1 change: 1 addition & 0 deletions ruff.schema.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.