|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +from fastapi.testclient import TestClient |
| 6 | +from sqlmodel import Session, SQLModel, create_engine, select |
| 7 | + |
| 8 | +from example_app.database import get_session |
| 9 | +from example_app.main import app |
| 10 | +from example_app.models import Customer |
| 11 | +from sqlmodel_encrypted_fields import configure_keysets |
| 12 | + |
| 13 | + |
| 14 | +def _project_root() -> Path: |
| 15 | + return Path(__file__).resolve().parents[2] |
| 16 | + |
| 17 | + |
| 18 | +def _configure_keysets() -> None: |
| 19 | + root = _project_root() |
| 20 | + configure_keysets( |
| 21 | + { |
| 22 | + "default": {"path": str(root / "tests" / "fixtures" / "aead_keyset.json"), "cleartext": True}, |
| 23 | + "deterministic": {"path": str(root / "tests" / "fixtures" / "daead_keyset.json"), "cleartext": True}, |
| 24 | + } |
| 25 | + ) |
| 26 | + |
| 27 | + |
| 28 | +def _test_engine(tmp_path: Path): |
| 29 | + return create_engine(f"sqlite:///{tmp_path / 'test.db'}", echo=False) |
| 30 | + |
| 31 | + |
| 32 | +def test_customer_create_and_lookup(tmp_path: Path) -> None: |
| 33 | + _configure_keysets() |
| 34 | + |
| 35 | + engine = _test_engine(tmp_path) |
| 36 | + SQLModel.metadata.create_all(engine) |
| 37 | + |
| 38 | + def _session_override(): |
| 39 | + with Session(engine) as session: |
| 40 | + yield session |
| 41 | + |
| 42 | + app.dependency_overrides[get_session] = _session_override |
| 43 | + client = TestClient(app) |
| 44 | + |
| 45 | + payload = {"email": "alice@example.com", "email_lookup": "alice@example.com"} |
| 46 | + response = client.post("/customers", json=payload) |
| 47 | + assert response.status_code == 200 |
| 48 | + customer_id = response.json()["id"] |
| 49 | + |
| 50 | + response = client.get(f"/customers/{customer_id}") |
| 51 | + assert response.status_code == 200 |
| 52 | + assert response.json()["email"] == payload["email"] |
| 53 | + |
| 54 | + response = client.get(f"/customers/by-email/{payload['email']}") |
| 55 | + assert response.status_code == 200 |
| 56 | + assert response.json()["id"] == customer_id |
| 57 | + |
| 58 | + with engine.connect() as connection: |
| 59 | + raw = connection.exec_driver_sql( |
| 60 | + "select email from customer where id = ?", |
| 61 | + (customer_id,), |
| 62 | + ).fetchone()[0] |
| 63 | + assert isinstance(raw, (bytes, memoryview)) |
| 64 | + raw_bytes = raw.tobytes() if isinstance(raw, memoryview) else raw |
| 65 | + assert payload["email"].encode("utf-8") not in raw_bytes |
| 66 | + |
| 67 | + with Session(engine) as session: |
| 68 | + statement = select(Customer).where(Customer.email_lookup == payload["email"]) |
| 69 | + customer = session.exec(statement).first() |
| 70 | + assert customer is not None |
| 71 | + |
| 72 | + app.dependency_overrides.clear() |
0 commit comments