20 / 80 · 12 Programming for QA · Data Structures for QA← prev⊞ allnext →☰ Read as one page
3.2Lists and Arrays
Lists (Python) and arrays (JavaScript) are the most common data structure in test automation. API responses contain lists of items. Test results are lists of pass/fail records. Log files are lists of lines.
Python Lists
# Filtering test results
results = [
{"name": "test_login", "status": "PASS", "duration": 1.2},
{"name": "test_signup", "status": "FAIL", "duration": 3.5},
{"name": "test_logout", "status": "PASS", "duration": 0.8},
{"name": "test_profile", "status": "FAIL", "duration": 2.1},
]
# List comprehension: filter failed tests
failed = [t for t in results if t["status"] == "FAIL"]
assert len(failed) == 2
# Sort by duration (slowest first)
slowest = sorted(results, key=lambda t: t["duration"], reverse=True)
assert slowest[0]["name"] == "test_signup"
# Extract just the names
names = [t["name"] for t in results]
assert "test_login" in names
# Check all tests passed (returns False if any failed)
all_passed = all(t["status"] == "PASS" for t in results)
assert not all_passed
# Check at least one test passed
any_passed = any(t["status"] == "PASS" for t in results)
assert any_passed
JavaScript/TypeScript Arrays
const results = [
{ name: "test_login", status: "PASS", duration: 1.2 },
{ name: "test_signup", status: "FAIL", duration: 3.5 },
{ name: "test_logout", status: "PASS", duration: 0.8 },
{ name: "test_profile", status: "FAIL", duration: 2.1 },
];
// Filter failed tests
const failed = results.filter(t => t.status === "FAIL");
expect(failed).toHaveLength(2);
// Sort by duration (slowest first) — note: sort mutates the array
const slowest = [...results].sort((a, b) => b.duration - a.duration);
expect(slowest[0].name).toBe("test_signup");
// Extract just the names
const names = results.map(t => t.name);
expect(names).toContain("test_login");
// Check all/any
const allPassed = results.every(t => t.status === "PASS");
const anyPassed = results.some(t => t.status === "PASS");
Common List Operations in Testing
| Operation | Python | JavaScript |
|---|---|---|
| Filter | [x for x in list if cond] or filter() |
array.filter(fn) |
| Transform | [fn(x) for x in list] or map() |
array.map(fn) |
| Sort | sorted(list, key=fn) |
[...array].sort(fn) |
| Find first | next((x for x in list if cond), None) |
array.find(fn) |
| Check all | all(cond for x in list) |
array.every(fn) |
| Check any | any(cond for x in list) |
array.some(fn) |
| Flatten | [item for sub in nested for item in sub] |
array.flat() |
| Unique | list(set(list)) |
[...new Set(array)] |