| name | qa-test-data-management |
| description | Управление test data — fixtures генерируются из real schemas (TS типы, DB schema, OpenAPI), PII hygiene (faker/factory_boy для синтетики), prod-like masking при копировании prod данных, environment isolation (testcontainers, transactional rollback, tempdir), fixture lifecycle. Защита от Mode 1 (mock obsession) — fixture не дрейфует от реальности. |
| type | discretionary |
| domain | development |
| owners | ["tester"] |
| gates | ["TEST"] |
| tech | ["docker","faker","factory_boy"] |
| topic | ["qa"] |
| triggers | ["test data management","test fixtures","PII в тестах","faker","factory_boy","testcontainers","prod data masking","fixture drift","environment isolation"] |
| related | ["qa-test-plan","qa-regression-baseline","qa-mutation-testing","tests-quality-review"] |
| budget_lines | 250 |
| schema_version | 1 |
Skill: QA Test Data Management
Управление тестовыми данными так, чтобы fixtures не дрейфовали от реальности, не содержали PII, и не загрязняли среду между прогонами. Защита от Mode 1 Test Integrity Defense (mock obsession) — потому что mock obsession часто начинается с "придуманного руками" fixture которое расходится с реальной схемой.
Разделы:
- Когда применять
- Fixture derivation from real schemas
- PII hygiene
- Prod-like data masking
- Environment isolation
- Fixture lifecycle
- Anti-patterns
- Output template
- DoD
1. Когда применять
Триггеры:
- Первый интеграционный тест на новый модуль / новую DB таблицу / новый API endpoint
- Security alert: PII обнаружено в test fixtures (auto-scan, см.
$qa-test-integrity-audit)
- DB schema migration — fixtures всех затронутых тестов нужно re-generate
- Stabilization sprint включает audit test data quality
Outputs:
- Fixture generation скрипт / decorator / factory class
- Mask config для prod-data clone (если применимо)
- Cleanup hooks для testcontainers / tempdir
- PII audit report
2. Fixture derivation from real schemas
Правило: fixture генерируется из source-of-truth схемы, не "придуман руками".
JS/TS — из TypeScript типов через faker:
import { faker } from "@faker-js/faker";
import type { User } from "@/types/user";
export function makeUser(overrides?: Partial<User>): User {
return {
id: faker.string.uuid(),
email: faker.internet.email(),
name: faker.person.fullName(),
role: "user",
createdAt: faker.date.recent(),
...overrides,
};
}
Python — из dataclass через factory_boy:
import factory
from app.models import User
class UserFactory(factory.Factory):
class Meta:
model = User
id = factory.Faker("uuid4")
email = factory.Faker("email")
name = factory.Faker("name")
role = "user"
Из OpenAPI / JSON Schema: используй openapi-typescript-codegen (TS) или datamodel-code-generator (Python) для type derivation, затем factory как выше.
Зачем: schema меняется — type meняется — factory падает на компиляции — тесты переписаны под новую схему. Без этого fixture тихо устаревает, тесты зелёные, prod падает.
3. PII hygiene
Что НЕ должно попадать в test fixtures (никогда):
- Real emails / phones / addresses (даже свои)
- Real payment data (CC numbers, IBAN, SWIFT)
- Real names of real people
- Real API keys / tokens / passwords
- Real customer IDs from prod
Что использовать вместо:
- faker (JS/TS):
faker.internet.email(), faker.phone.number(), faker.location.streetAddress()
- factory_boy + faker (Python):
factory.Faker("email"), factory.Faker("phone_number")
Detection: ESLint rule no-restricted-syntax + custom regex на email/phone patterns в test files. Pre-commit hook block если найдено что-то похожее на real PII (см. $qa-test-integrity-audit §1).
Если случайно закоммитили PII:
- Rotate compromised credentials немедленно
- Filter git history (
git filter-repo) — НЕ rebase, чтобы оригинальные commits были недоступны
- Notify owners если real customer data была
- Document incident в security-baseline-dev runbook
4. Prod-like data masking
Иногда нужно тестировать на realistic distribution (volume, edge cases) — копируем prod data в staging/test, но маскируем PII.
Masking rules:
- Emails: replace local part с hash, keep domain category (
user-a3f9@example.com)
- Names: replace с faker.person.fullName() seeded by hash of original (consistent within run)
- Phones: randomize last 4 digits keeping country code
- Dates: shift by random Δ ±30 days (preserve weekday patterns)
- IDs: preserve referential integrity through deterministic mapping (
user_123 → user_anon_xyz consistently)
- Payment: zeroize CC, randomize amounts within ±20% range
Tools: pgmasq (Postgres), Faker.unique + custom transformers, в-house masking script. Run AS PART OF prod→staging sync, не в test runtime.
Audit: после mask sample 100 rows, manual check on no leakage. Document mask config in repo so reviewer audits.
5. Environment isolation
Каждый прогон тестов должен начинаться с clean state и не оставлять артефактов следующему.
DB isolation patterns:
- Testcontainers (Docker-based fresh DB per test suite):
@testcontainers/postgresql (JS), testcontainers (Python). Spin up real Postgres/MongoDB в Docker container, teardown after.
- Transactional rollback (быстрее testcontainers): wrap test в transaction, rollback at end. Works for SQL DBs, не работает для MongoDB.
- In-memory adapters (быстрее всех, но менее real): SQLite for Postgres-like, mongo-memory-server.
File system isolation:
tmp директории per test (os.tmpdir() + uuid)
- Cleanup в
afterEach / pytest fixture teardown
- НЕ использовать shared
tests/fixtures/output/ директорию
Network isolation:
- MSW (JS) / responses (Python) для mock external HTTP at boundary
- Никогда не hit реальный API в тесте — flaky + slow + cost
State между тестами:
- Module-level state НЕ shared (avoid singletons в production code или wipe в
beforeEach)
- DB indexes/sequences reset between suites
6. Fixture lifecycle
Create:
- Generation через factory (не hardcode)
- Minimum data needed for test (no "kitchen sink" fixtures)
- Specific test → specific fixture builder
Use:
- Один тест → один fixture instance (не shared)
- Если нужны связанные entities — factory composition (
UserFactory.subFactory(OrderFactory))
- Overrides только для test-specific вариаций
Cleanup:
- Testcontainers — auto-teardown on suite exit
- DB transactional rollback — auto on test exit
- File system —
afterEach cleanup hook
- Tempdir — registered for OS cleanup
Storage convention:
- Factory definitions:
tests/factories/ (JS) или tests/conftest.py + factory module (Python)
- Test data files: НЕ commit large fixture JSON files в git; generate on demand
- Snapshot files OK в git (Playwright traces, vitest snapshots) — но без PII
7. Anti-patterns
- 🔴 Hardcoded real PII —
expect(user.email).toBe("user@example.com") — security leak + flaky когда пользователь меняет email.
- 🔴 Shared mutable fixture —
beforeAll(() => fixture = makeUser()) + tests mutate fixture — order dependence, flaky.
- 🔴 Fixture drift — handcrafted
{id: 1, name: "test"} который не использует TS type / schema. Schema меняется, fixture не падает, prod падает.
- 🟠 No cleanup — testcontainers вы стартанули, забыли teardown — CI runner забит зомби-контейнерами через час.
- 🟠 Kitchen sink fixture —
makeUserWithEverything() возвращает user + orders + payments + sessions — каждый тест получает больше чем нужно, обновление ломает все тесты.
- 🟡 Faker без seed — рандомность хорошо, но без seed невозможно воспроизвести failing test. Pin seed for reproducible builds (
faker.seed(42) per test).
8. Output template
Tester включает в TEST report (если применимо):
### Test Data Management
- Factories used: N (list)
- PII audit: pass / N findings
- Masking config: configured / N/A
- Environment isolation:
- testcontainers: N suites
- transactional rollback: N suites
- tempdir cleanup: configured
- Fixture seeding: seeded (reproducible) / random
- Action items: [fixture refactors / PII findings to fix]
9. DoD
См. также
$qa-test-plan — план тестирования учитывает test data requirements per flow
$qa-regression-baseline — baseline tracks fixture changes between releases
$qa-mutation-testing — mutation сильно зависит от quality fixtures
$qa-test-integrity-audit — PII detection rules + fixture drift detection
$qa-flaky-test-protocol — env isolation issues → flaky cause
$tests-quality-review — Reviewer-side audit включая test data quality
$security-baseline-dev — PII handling rules consistent с production code