39 / 80 · 12 Programming for QA · Functional Patterns for Testing← prev⊞ allnext →☰ Read as one page
5.5Immutability
Functional programming favors immutable data — data that is not modified after creation. This prevents subtle bugs where shared test data is accidentally modified.
# BAD: mutable default — all tests share the same list
def create_order(items=[]): # list is created once and shared!
items.append("new_item")
return items
# GOOD: immutable approach
def create_order(items=None):
items = list(items or []) # create a new list each time
items.append("new_item")
return items
# BEST: use frozen dataclass for test data
from dataclasses import dataclass
@dataclass(frozen=True)
class TestUser:
email: str
password: str
role: str = "viewer"
admin = TestUser("admin@test.com", "pass123", "admin")
# admin.role = "viewer" # This raises FrozenInstanceError