1 / 8 · Book 15 · Your First SELECT -- Reading the Source of Truth · drill: interview Q&A⊞ allnext →Get the book →
1.10Using DictCursor for Readable Assertions
Positional access (row[0], row[1]) is fragile and hard to read. Use DictCursor instead:
from psycopg2.extras import DictCursor
def test_user_fields(db):
cursor = db.cursor(cursor_factory=DictCursor)
cursor.execute(
"SELECT * FROM users WHERE email = %s",
("alice@test.com",)
)
user = cursor.fetchone()
assert user["name"] == "Alice"
assert user["role"] == "viewer"
assert user["created_at"] is not None
def test_all_active_users_have_email(db):
cursor = db.cursor(cursor_factory=DictCursor)
cursor.execute("SELECT id, email FROM users WHERE active = true")
users = cursor.fetchall()
for user in users:
assert user["email"] is not None, f"User {user['id']} has no email"
assert "@" in user["email"], f"User {user['id']} has invalid email"