Designing Playwright Tests for Distributed Microservice State Contention
说明与用途
使用 tenant‑scoped isolation、原子 Lua 事务和每个测试后清理,消除分布式微服务中共享 Redis 的状态竞争。
问题
Worker isolation in Playwright does not isolate external shared state such as Redis, leading to race conditions where multiple workers can concurrently modify the same inventory or session data.
结果
Achieved deterministic test execution on a distributed grid by isolating external state per test tenant, ensuring atomic operations, and guaranteeing cleanup.
工作流
- Derive a unique tenant string from project name, worker index, and test ID.
- Extend Playwright test fixture to provide the tenant to each test.
- Before each test, seed Redis with stock for the tenant via a PUT request.
- After each test (always), delete the tenant’s data via a DELETE request.
- In test code, send X‑Test‑Namespace header to scope service calls to the tenant.
- Use a single Lua transaction in the service to DECR stock and SET session NX atomically.
- Retry the reservation call if the Lua transaction fails, ensuring only one worker succeeds.
- Verify that the first reservation returns true and the second returns false.
- Cleanup guarantees no leftover state for subsequent tests.
证据
Two Playwright workers bought the last item—and one failed randomly.
Derive project + workerIndex + testId as a unique tenant.
Seed before each test; delete only that tenant with afterEach.always.
- 记录日期: 2026-09-21T13:45:26.255Z