Skip to content

Python · testing

prefer-real-store-in-tests

python:prefer-real-store-in-tests

Tests should exercise the real persistence implementation instead of an in-memory reimplementation.

Code
SARJ058
Default
error
Fix
none
Languages
python

Why

Container-backed store doubles omit database constraints, transactions, ordering, and concurrency semantics.

Fix

Run the real store against a test database and subclass it only when a test must inject a failure.

Before / after

Executed by this rule’s unit tests.

Before

Test reimplements a store with a dictionary

tests/fakes/user_store.py · focus
class FakeUserStore(UserStore):
    def __init__(self):
        self.rows = {}

    def add(self, user):
        self.rows[user.id] = user

    def get(self, user_id):
        return self.rows.get(user_id)

After

Test subclasses the real store to inject a failure

tests/fakes/user_store.py · focus
class FailingUserStore(PsqlUserStore):
    def add(self, user):
        raise OSError("database unavailable")

Limits

  • Only test and shared-double paths are analyzed.
  • The class must resemble a relational persistence double backed by a mutable container or hollow methods.