55 / 80 · 12 Programming for QA · Regex and Parsing← prev⊞ allnext →☰ Read as one page
7.4Regex in Test Assertions
# Validate response format
import re
def test_user_id_format(api_response):
"""User IDs should be UUIDs."""
user_id = api_response.json()["id"]
uuid_pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
assert re.match(uuid_pattern, user_id), f"Invalid UUID format: {user_id}"
def test_email_format(api_response):
"""Email should be valid format."""
email = api_response.json()["email"]
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
assert re.match(email_pattern, email), f"Invalid email format: {email}"
def test_error_message_no_stack_trace(error_response):
"""Error messages should not contain internal stack traces."""
body = error_response.text
assert not re.search(r'at .*\(.*:\d+:\d+\)', body), "Stack trace exposed in error"
assert not re.search(r'Traceback \(most recent call last\)', body), "Python traceback exposed"
assert not re.search(r'/usr/src/app', body), "Internal file paths exposed"
TypeScript Regex
test("API response contains valid ISO date", () => {
const createdAt = response.data.created_at;
const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
expect(createdAt).toMatch(isoDatePattern);
});
test("Error response does not leak internals", () => {
const body = JSON.stringify(errorResponse.data);
expect(body).not.toMatch(/at .*\(.*:\d+:\d+\)/);
expect(body).not.toMatch(/node_modules/);
});