22 / 80 · 12 Programming for QA · Data Structures for QA← prev⊞ allnext →☰ Read as one page
3.4Sets
Sets provide fast membership checks, deduplication, and set operations (union, intersection, difference). They are essential for validating response fields and detecting duplicates.
Python Sets
# Validate required fields in API response
required = {"id", "name", "email", "created_at"}
actual = set(response.json().keys())
missing = required - actual
assert not missing, f"Missing fields: {missing}"
# Check no sensitive fields are exposed
forbidden = {"password", "password_hash", "ssn", "credit_card"}
exposed = forbidden & actual # intersection
assert not exposed, f"Sensitive fields exposed: {exposed}"
# Detect duplicate IDs across paginated responses
page1_ids = {u["id"] for u in page1_response.json()["items"]}
page2_ids = {u["id"] for u in page2_response.json()["items"]}
overlap = page1_ids & page2_ids
assert not overlap, f"Duplicate IDs across pages: {overlap}"
# Verify all expected statuses are present
expected_statuses = {"pending", "processing", "completed", "failed"}
actual_statuses = {o["status"] for o in orders}
missing_statuses = expected_statuses - actual_statuses
# (This tells you which statuses are not represented in the data)
JavaScript Sets
// Deduplication
const ids = responses.map(r => r.id);
const uniqueIds = new Set(ids);
expect(uniqueIds.size).toBe(ids.length); // no duplicates
// Field validation
const required = new Set(["id", "name", "email", "created_at"]);
const actual = new Set(Object.keys(response.data));
const missing = [...required].filter(f => !actual.has(f));
expect(missing).toHaveLength(0);
Set Operations Reference
| Operation | Python | Use Case |
|---|---|---|
| Union | a | b |
All fields from two responses combined |
| Intersection | a & b |
Fields present in both responses |
| Difference | a - b |
Fields in a but not in b |
| Symmetric Diff | a ^ b |
Fields in one but not both |
| Subset check | a <= b |
Are all required fields present? |