Hide irrelevant test data


Python clean test tip:

You should hide irrelevant data for the test.

Such information just increases the cognitive mental load, resulting in bloated tests.

Example:

import uuid
from dataclasses import dataclass
from enum import Enum
from uuid import UUID
import pytest


class ProductCategory(str, Enum):
    BOOK = "BOOK"
    ELECTRONIC = "ELECTRONIC"


@dataclass
class Product:
    id: UUID
    price: int
    name: str
    category: ProductCategory


class ShoppingCart:
    def __init__(self):
        self._products = []

    def add(self, product):
        self._products.append(product)

    def calculate_total_price(self):
        return sum(product.price for product in self._products)


# BAD - category, id, and name are irrelevant for this test
def test_given_products_with_total_price_50_when_calculate_total_price_then_total_price_is_50_():
    shopping_cart = ShoppingCart()
    shopping_cart.add(Product(uuid.uuid4(), 10, "Mobile phone case", ProductCategory.ELECTRONIC))
    shopping_cart.add(Product(uuid.uuid4(), 20, "Never enough", ProductCategory.BOOK))
    shopping_cart.add(Product(uuid.uuid4(), 20, "Mobile phone charger", ProductCategory.ELECTRONIC))

    assert shopping_cart.calculate_total_price() == 50


# GOOD
@pytest.fixture
def product_with_price():
    def _product_with_price(price):
        return Product(uuid.uuid4(), price, "Mobile phone case", ProductCategory.ELECTRONIC)
    return _product_with_price


def test_given_products_with_total_price_50_when_calculate_total_price_then_total_price_is_50(product_with_price):
    shopping_cart = ShoppingCart()
    shopping_cart.add(product_with_price(10))
    shopping_cart.add(product_with_price(20))
    shopping_cart.add(product_with_price(20))

    assert shopping_cart.calculate_total_price() == 50