Skip to content

Python · testing

kwarg-heavy-construction-in-test

python:kwarg-heavy-construction-in-test

Object built with many keywords inline in a test — extract a helper with defaults.

Code
SARJ045
Default
error
Fix
none
Languages
python

Why

Repeated construction boilerplate hides the field each test changes and makes schema changes noisy.

Fix

Extract a test builder with sensible defaults and override only values relevant to each case.

Before / after

Executed by this rule’s unit tests.

Before

Tests repeat every constructor argument

tests/test_call.py · focus
def test_first():
    assert Call(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9)

def test_second():
    assert Call(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9)

After

Tests override builder defaults

tests/test_call.py · focus
def build_call(**overrides):
    return Call(**overrides)

def test_first():
    assert build_call(a=1)

Limits

  • Only repeated calls with more than eight named arguments directly inside test functions are reported.
  • Mapping construction, mock assertions, fixtures, and local helper calls are allowed.