Skip to content

Python · testing

duplicate-test-body

python:duplicate-test-body

Similar test bodies should be represented as one named parameterized case table.

Code
SARJ066
Default
error
Fix
none
Languages
python

Why

Copy-pasted tests drift independently and obscure the input dimension that changes behavior.

Fix

Collapse the copies into `pytest.mark.parametrize` cases with descriptive `ids`.

Before / after

Executed by this rule’s unit tests.

Before

Two tests differ only in input literals

tests/test_permissions.py · focus
def test_admin():
    user = make_user("admin")
    allowed = can_delete(user)
    assert allowed

def test_editor():
    user = make_user("editor")
    allowed = can_delete(user)
    assert allowed

After

Inputs share one parameterized test

tests/test_permissions.py · focus
import pytest

@pytest.mark.parametrize("role", ["admin", "editor"], ids=["admin", "editor"])
def test_can_delete(role):
    user = make_user(role)
    allowed = can_delete(user)
    assert allowed

Limits

  • Only substantial sibling test bodies in one non-generated module are compared.
  • Meaningful docstring or comment differences keep tests distinct.