Application Management Domain - Fixtures, Sample Datasets, and Regression Coverage

Overview

This section documents the fixture data and regression tests that keep the housing application flows stable in local debugging and in CI. The main contract is the application record lifecycle: create, list, inspect, archive, and update review status, plus the phone-only application path used by the lighter /api/phone-applications flow.

The repository uses two layers of protection for this domain. Interface tests in backend/tests/interface/test_application_endpoint.py and backend/tests/interface/test_phone_application_endpoint.py lock down HTTP behavior, including validation, content negotiation, sorting, and authorization. Infra tests in backend/tests/infra/test_housing_application_repository.py and backend/tests/test_schema_migrations.py lock down persistence behavior such as ordering, deletion, and schema compatibility.

Architecture Overview

flowchart TD
    subgraph Fixtures [Fixtures and Sample Datasets]
        SampleData[data applications sample json]
        LiveData[data applications json]
        BuildPayload[build_payload helper]
        BuildApplication[_build_application helper]
    end

    subgraph Contracts [API Contract Regression]
        AppTests[test_application_endpoint.py]
        PhoneTests[test_phone_application_endpoint.py]
    end

    subgraph Invariants [Repository and Schema Invariants]
        RepoTests[test_housing_application_repository.py]
        SchemaTests[test_schema_migrations.py]
    end

    subgraph Runtime [Application Runtime]
        CreateApp[POST api v1 applications]
        ListApps[GET api v1 applications]
        DetailApp[GET api v1 applications id]
        ArchiveApp[POST api v1 applications id archive]
        DecideApp[POST api v1 applications id decision]
        DeleteApps[DELETE api v1 applications]
        PhoneCreate[POST api phone-applications]
        PhoneList[GET api phone-applications]
        StreamApps[GET api v1 applications stream]
        Repo[SQLAlchemyHousingApplicationRepository]
        Events[application_events]
    end

    SampleData --> BuildPayload
    LiveData --> BuildPayload
    BuildPayload --> AppTests
    BuildApplication --> RepoTests
    AppTests --> CreateApp
    AppTests --> ListApps
    AppTests --> DetailApp
    AppTests --> ArchiveApp
    AppTests --> DecideApp
    PhoneTests --> PhoneCreate
    PhoneTests --> PhoneList
    RepoTests --> Repo
    SchemaTests --> Repo
    CreateApp --> Repo
    ListApps --> Repo
    DetailApp --> Repo
    ArchiveApp --> Repo
    DecideApp --> Repo
    DeleteApps --> Repo
    PhoneCreate --> Repo
    PhoneList --> Repo
    CreateApp --> Events
    Events --> StreamApps

Fixtures and Sample Datasets

Canonical application payload

backend/tests/interface/test_application_endpoint.py

The build_payload() helper defines the smallest successful housing application submission used across the interface tests. It is the model to mirror when seeding data/applications.sample.json and data/applications.json.

Field Example value Notes
email [email protected] Required by the create endpoint
phone +1 555 123 4567 Used for phone search and duplicate handling
country Japan Stored on the application record
property_type Condo Stored on the application record
purchase_intent buy Stored on the application record
budget_range ¥100–200M Stored on the application record
savings ¥10M Stored on the application record
income 120000 Stored on the application record
income_currency USD Stored on the application record
employment_status Full-time Stored on the application record
financing_consent yes Stored on the application record
full_name Jane Doe Required by the create endpoint
agree_policy true Required consent gate
receive_updates false Stored boolean flag
connected_accounts {"personal":[{"id":"acc_1","name":"Primary checking"}]} Preserved in the response and used for enrichment

Canonical persisted application fixture

backend/tests/infra/test_housing_application_repository.py

The _build_application(index) helper creates a full HousingApplication object for repository tests. This is the best reference for what a seed row should look like after persistence.

Field Example value
id None
email [email protected]
phone +15550001
country US
property_type apartment
purchase_intent rent
budget_range 1000-1500
savings 10000
income 50000
income_currency USD
employment_status employed
financing_consent yes
full_name Test User 1
agree_policy true
receive_updates false
connected_accounts {}
created_at None

Phone application payload

backend/tests/interface/test_phone_application_endpoint.py

The phone-only flow uses a smaller payload.

Field Example value
phone +1 (555) 123-4567
connected_accounts {"example":"data"}

Fixture dataset files

data/applications.sample.json

data/applications.json

These files are the repository-level fixtures for local seed data. The sample file is the template engineers should copy and edit, while the non-sample file is the working dataset used during local debugging.

API Contract Coverage

Submit Housing Application

backend/tests/interface/test_application_endpoint.py

backend/src/interface/http_endpoints.py

backend/src/usecase/housing_application.py

The create flow validates consent and required fields before calling submit_housing_application. The endpoint also copies optional metadata and identifier values into the persisted application context, then strips internal storage keys from the response.

{
    "title": "Submit Housing Application",
    "description": "Creates a housing application, provisions login credentials, syncs open banking consent data, and publishes an application_created event when persistence succeeds.",
    "method": "POST",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 123 4567\",\n    \"country\": \"Japan\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"\\u00a5100\\u2013200M\",\n    \"savings\": \"\\u00a510M\",\n    \"income\": \"120000\",\n    \"income_currency\": \"USD\",\n    \"employment_status\": \"Full-time\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Jane Doe\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"identifier\": \"dashboard-profile-1\",\n    \"metadata\": {\n        \"profile_name\": \"Dashboard Profile\",\n        \"credit_score\": 742,\n        \"credit_score_scale\": \"300-850\"\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Application created",
            "body": "{\n    \"id\": 1024,\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 123 4567\",\n    \"country\": \"Japan\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"\\u00a5100\\u2013200M\",\n    \"savings\": \"\\u00a510M\",\n    \"income\": \"120000\",\n    \"income_currency\": \"USD\",\n    \"employment_status\": \"Full-time\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Jane Doe\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"created_at\": \"2024-01-15T10:30:00Z\",\n    \"archived\": false,\n    \"review_status\": \"pending\",\n    \"identifier\": \"dashboard-profile-1\",\n    \"metadata\": {\n        \"profile_name\": \"Dashboard Profile\",\n        \"credit_score\": 742,\n        \"credit_score_scale\": \"300-850\"\n    },\n    \"login_credentials\": {\n        \"role\": \"applicant\",\n        \"application_id\": 1024,\n        \"username\": \"LITA9X7K2\",\n        \"temporary_password\": \"TempPass!234\"\n    }\n}"
        },
        "400": {
            "description": "Validation failure",
            "body": "{\n    \"detail\": \"Privacy policy consent is required.\"\n}"
        }
    }
}

List Housing Applications

backend/tests/interface/test_application_endpoint.py

backend/src/interface/http_endpoints.py

The list endpoint returns the most recent applications first, accepts a phone filter, and can render HTML when the request prefers text/html over application/json. The regression suite also proves that a missing created_at value is normalized to a non-empty string in the response.

{
    "title": "List Housing Applications",
    "description": "Returns housing applications in reverse recency order. If the request Accept header prefers text/html and does not explicitly prefer application/json, the endpoint renders an HTML table instead of JSON.",
    "method": "GET",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "limit",
            "value": "50",
            "required": false
        },
        {
            "key": "phone",
            "value": "5551234567",
            "required": false
        },
        {
            "key": "residence_permit_number",
            "value": "AB12345678CD",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Application list",
            "body": "[\n    {\n        \"id\": 1024,\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1 555 123 4568\",\n        \"country\": \"Japan\",\n        \"property_type\": \"Condo\",\n        \"purchase_intent\": \"buy\",\n        \"budget_range\": \"\\u00a5100\\u2013200M\",\n        \"savings\": \"\\u00a510M\",\n        \"income\": \"120000\",\n        \"income_currency\": \"USD\",\n        \"employment_status\": \"Full-time\",\n        \"financing_consent\": \"yes\",\n        \"full_name\": \"Second Applicant\",\n        \"agree_policy\": true,\n        \"receive_updates\": false,\n        \"connected_accounts\": {\n            \"personal\": [\n                {\n                    \"id\": \"acc_1\",\n                    \"name\": \"Primary checking\"\n                }\n            ]\n        },\n        \"created_at\": \"2024-01-15T10:30:00Z\",\n        \"archived\": false,\n        \"review_status\": \"pending\",\n        \"identifier\": \"cust-123\",\n        \"metadata\": {\n            \"email\": \"[email protected]\",\n            \"phone\": \"+1 555 123 4567\",\n            \"kyc\": {\n                \"provider\": \"saltedge\"\n            }\n        }\n    }\n]"
        }
    }
}

Get Housing Application

backend/tests/interface/test_application_endpoint.py

backend/src/interface/http_endpoints.py

The detail endpoint fetches a single application by ID and merges embedded metadata with external enrichment. The tests verify that the response preserves identifier and metadata, and that 404 is returned for missing records.

{
    "title": "Get Housing Application",
    "description": "Fetches a single housing application by application_id and merges any resolved metadata into the response.",
    "method": "GET",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/api/v1/applications/1024",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "application_id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Application details",
            "body": "{\n    \"id\": 1024,\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 123 4567\",\n    \"country\": \"Japan\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"\\u00a5100\\u2013200M\",\n    \"savings\": \"\\u00a510M\",\n    \"income\": \"120000\",\n    \"income_currency\": \"USD\",\n    \"employment_status\": \"Full-time\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Jane Doe\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"created_at\": \"2024-01-15T10:30:00Z\",\n    \"archived\": false,\n    \"review_status\": \"pending\",\n    \"identifier\": \"dashboard-profile-1\",\n    \"metadata\": {\n        \"profile_name\": \"Dashboard Profile\",\n        \"credit_score\": 742,\n        \"credit_score_scale\": \"300-850\"\n    }\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found.\"\n}"
        }
    }
}

Archive Housing Application

backend/tests/interface/test_application_endpoint.py

backend/src/interface/http_endpoints.py

Archiving marks the record archived and removes it from subsequent listings. A missing record returns 404.

{
    "title": "Archive Housing Application",
    "description": "Archives a housing application so it disappears from the application listing.",
    "method": "POST",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/api/v1/applications/1024/archive",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "application_id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Archive successful",
            "body": "{\n    \"archived\": true\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found.\"\n}"
        }
    }
}

Decide Housing Application

backend/tests/interface/test_application_endpoint.py

backend/src/interface/http_endpoints.py

The decision endpoint is role-gated. The tests prove that an applicant token receives 403, while the admin-authenticated client can update the review status to approved.

{
    "title": "Decide Housing Application",
    "description": "Updates the application review status. The endpoint rejects unauthorized applicant tokens and accepts privileged reviewer or admin requests.",
    "method": "POST",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/api/v1/applications/1024/decision",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "application_id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"status\": \"approved\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Decision accepted",
            "body": "{\n    \"id\": 1024,\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 123 4567\",\n    \"country\": \"Japan\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"\\u00a5100\\u2013200M\",\n    \"savings\": \"\\u00a510M\",\n    \"income\": \"120000\",\n    \"income_currency\": \"USD\",\n    \"employment_status\": \"Full-time\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Jane Doe\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"created_at\": \"2024-01-15T10:30:00Z\",\n    \"archived\": false,\n    \"review_status\": \"approved\",\n    \"identifier\": \"dashboard-profile-1\",\n    \"metadata\": {\n        \"profile_name\": \"Dashboard Profile\",\n        \"credit_score\": 742,\n        \"credit_score_scale\": \"300-850\"\n    }\n}"
        },
        "403": {
            "description": "Applicant token rejected",
            "body": "{\n    \"detail\": \"You do not have permission to perform this action.\"\n}"
        }
    }
}

Delete All Housing Applications

backend/src/interface/http_endpoints.py

backend/tests/interface/test_application_endpoint.py

The frontend’s bulk-delete action uses this endpoint, and the repository tests verify that deletion counts are accurate. This is the safest reset path for an application table in a local database.

{
    "title": "Delete All Housing Applications",
    "description": "Deletes all stored housing applications and returns the number of deleted rows.",
    "method": "DELETE",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Applications deleted",
            "body": "{\n    \"deleted\": 2\n}"
        }
    }
}

Search Applications by Phone

backend/tests/interface/test_application_endpoint.py

backend/src/interface/http_endpoints.py

The tests cover both exact digit-only search and partial phone matching, and they assert that archived records are excluded from results.

{
    "title": "Search Applications by Phone",
    "description": "Returns application records filtered by phone. The test suite proves digit-only matching, partial matching, and exclusion of archived records.",
    "method": "GET",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/api/applicants",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "phone",
            "value": "5551234567",
            "required": false
        },
        {
            "key": "limit",
            "value": "2",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Matching applications",
            "body": "[\n    {\n        \"id\": 1024,\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1 555 123 4567\",\n        \"country\": \"Japan\",\n        \"property_type\": \"Condo\",\n        \"purchase_intent\": \"buy\",\n        \"budget_range\": \"\\u00a5100\\u2013200M\",\n        \"savings\": \"\\u00a510M\",\n        \"income\": \"120000\",\n        \"income_currency\": \"USD\",\n        \"employment_status\": \"Full-time\",\n        \"financing_consent\": \"yes\",\n        \"full_name\": \"Jane Doe\",\n        \"agree_policy\": true,\n        \"receive_updates\": false,\n        \"connected_accounts\": {\n            \"personal\": [\n                {\n                    \"id\": \"acc_1\",\n                    \"name\": \"Primary checking\"\n                }\n            ]\n        },\n        \"created_at\": \"2024-01-15T10:30:00Z\",\n        \"archived\": false,\n        \"review_status\": \"pending\"\n    }\n]"
        }
    }
}

Stream Housing Application Events

backend/src/interface/http_endpoints.py

frontend/app/applicants/page.tsx

The stream endpoint exposes server-sent events for application updates. The frontend connects with EventSource, retries after disconnects, and falls back to polling every 30 seconds.

{
    "title": "Stream Housing Application Events",
    "description": "Provides a Server-Sent Events stream for housing application updates. The frontend listens for application-created and refresh events to keep the applicants list current.",
    "method": "GET",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/api/v1/applications/stream",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Server-Sent Events stream",
            "body": "{\n    \"type\": \"application_created\",\n    \"application\": {\n        \"id\": 1024,\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1 555 123 4567\",\n        \"created_at\": \"2024-01-15T10:30:00Z\",\n        \"archived\": false,\n        \"review_status\": \"pending\"\n    }\n}"
        }
    }
}

Submit Phone Application

backend/tests/interface/test_phone_application_endpoint.py

The phone-only path accepts a compact payload and returns the persisted record with its database metadata. The test suite also covers invalid phone validation.

{
    "title": "Submit Phone Application",
    "description": "Creates a phone-only application record.",
    "method": "POST",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/api/phone-applications",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"phone\": \"+1 (555) 123-4567\",\n    \"connected_accounts\": {\n        \"example\": \"data\"\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Phone application created",
            "body": "{\n    \"id\": 88,\n    \"phone\": \"+1 (555) 123-4567\",\n    \"connected_accounts\": {\n        \"example\": \"data\"\n    },\n    \"created_at\": \"2024-01-15T10:30:00Z\"\n}"
        },
        "400": {
            "description": "Invalid phone number",
            "body": "{\n    \"detail\": \"Enter a valid phone number.\"\n}"
        }
    }
}

List Phone Applications

backend/tests/interface/test_phone_application_endpoint.py

The list endpoint returns phone applications in recency order. The regression test confirms that the most recent record appears first.

{
    "title": "List Phone Applications",
    "description": "Returns phone-only application records in reverse creation order.",
    "method": "GET",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/api/phone-applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Phone application list",
            "body": "[\n    {\n        \"id\": 89,\n        \"phone\": \"+1 555 123 4501\",\n        \"connected_accounts\": {\n            \"account\": [\n                1\n            ]\n        },\n        \"created_at\": \"2024-01-15T10:31:00Z\"\n    }\n]"
        }
    }
}

Regression Coverage Matrix

Interface contract tests

backend/tests/interface/test_application_endpoint.py

Test Scope What it protects
test_submit_application_success Create contract Required fields persist, created_at is set, archived is false, review_status is pending
test_submit_application_returns_login_credentials Create contract Response includes login_credentials with role, application_id, username, and temporary_password
test_submit_application_requires_consent Validation agree_policy=false returns 400 with the consent error
test_submit_application_requires_email_and_name Validation Blank email is rejected before blank name
test_submit_application_updates_existing_record Upsert behavior Duplicate submission reuses the original record and updates mutable fields
test_submit_application_persists_embedded_dashboard_metadata Metadata handling identifier and metadata are preserved, while internal keys do not leak into connected_accounts
test_application_response_merges_embedded_and_enriched_metadata Metadata merge Embedded metadata is merged with external enrichment in the final response
test_get_application_by_id Detail contract Fetch by ID returns the created application
test_get_application_by_id_returns_404_for_missing_record Detail contract Missing records return 404
test_archive_application_removes_from_listing Archive contract Archived records vanish from list results
test_archive_application_returns_404_for_missing_record Archive contract Missing archive target returns 404
test_admin_can_update_application_status Decision contract Authorized user can move a record to approved
test_applicant_cannot_update_application_status Authorization Applicant token is rejected with 403
test_list_applications_returns_recent_records Ordering Most recent application appears first
test_list_applications_returns_all_without_limit Pagination behavior Omitted limit does not truncate the list
test_list_applications_handles_missing_created_at Data normalization Missing created_at is rendered as a non-empty string
test_list_applications_falls_back_without_review_status_column Legacy compatibility Missing review_status column still yields pending
test_list_applications_includes_metadata_when_available Enrichment External customer metadata is attached when available
test_list_applications_renders_html_when_requested Content negotiation Accept: text/html returns an HTML table
test_search_applications_by_phone Search contract Digits-only and partial phone matching both work; archived records are excluded
test_list_applicants_honours_limit_parameter Search contract The /api/applicants alias honors the query limit

Phone application contract tests

backend/tests/interface/test_phone_application_endpoint.py

Test Scope What it protects
test_submit_phone_application_success Create contract Phone-only records persist and return created_at
test_submit_phone_application_invalid_phone Validation Short or malformed phone values are rejected
test_list_phone_applications Ordering The most recently created phone application appears first

Repository invariant tests

backend/tests/infra/test_housing_application_repository.py

backend/tests/test_schema_migrations.py

Test Scope What it protects
test_get_by_id_returns_application_when_present Repository lookup Persisted application can be fetched by primary key
test_get_by_id_returns_none_when_missing Repository lookup Missing IDs return None instead of raising
test_delete_all_removes_every_application Repository reset Bulk delete removes all rows and leaves list_recent() empty
test_delete_all_on_empty_table_is_a_noop Repository reset Bulk delete on an empty table returns 0
test_repository_ensures_archived_column_when_missing Schema migration Legacy tables gain the archived column and default archived=False is applied

Test harness helpers

backend/tests/test_applicants.py

Helper Purpose
_get_test_engine Builds a shared in-memory SQLite engine with foreign keys enabled
_create_session Drops and recreates all tables for isolated tests
_create_customer Inserts a customer and returns the plaintext API key
_create_app Builds a FastAPI app for the applicant API tests and registers an AuthError handler

Repository Invariants

Application repository behavior

backend/tests/infra/test_housing_application_repository.py

SQLAlchemyHousingApplicationRepository is treated as the persistence boundary for housing application state. The tests prove four invariants: records can be fetched by ID, missing IDs return None, delete_all() removes every row and returns the count, and the repository tolerates an empty table without error.

Legacy schema compatibility

backend/tests/test_schema_migrations.py

The repository also protects older databases. When the applications table is missing the archived column, the repository ensures the column exists and backfills archived=False for existing rows.

Safe Local Debugging

Seed a test application from the command line

backend/src/scripts/create_test_application.py

The script creates one application, fetches it back, and prints the application ID, credit score, login credentials, and detail URL. It defaults to http://localhost:8000/api and uses APPLICATIONS_API_TOKEN when provided.

python backend/src/scripts/create_test_application.py \
  --base-url http://localhost:8000/api \
  --email [email protected] \
  --full-name Test Applicant
Script behavior Implementation detail
Build payload _default_payload mirrors the successful create payload used in the tests
Build headers _build_headers always sends Content-Type: application/json and adds Authorization when APPLICATIONS_API_TOKEN is set
Send request _request_json performs the POST and GET calls and raises on HTTP or JSON errors
Print output main prints a compact JSON summary for the created application

Clear local application data safely

There are two safe reset paths in the repository:

Path Use case Evidence
DELETE /api/v1/applications Application bulk clear in the live app Frontend bulk-delete action uses it
SQLAlchemyHousingApplicationRepository.delete_all() Test or local DB reset from Python Covered by test_delete_all_removes_every_application
Base.metadata.drop_all and Base.metadata.create_all Isolated test database rebuilds Used by _create_session() in backend/tests/test_applicants.py

How the fixtures map to local seed files

Use the field set from build_payload() for data/applications.sample.json, and keep data/applications.json aligned with the same shape when you want local state that behaves like the regression suite. If you need a fully persisted object shape, mirror _build_application(index) and include database-managed fields such as id, created_at, archived, and review_status.

Application Events Stream

backend/src/interface/http_endpoints.py

frontend/app/applicants/page.tsx

The application create flow publishes an event only after a record has an id and created_at. The payload excludes login_credentials.temporary_password, which keeps the event stream from carrying the temporary secret. The applicants page connects with EventSource, reconnects after failures, and uses a 30-second polling fallback.

Event data flow

  1. create_application persists the housing application.
  2. The response object is serialized for the stream payload.
  3. application_events.publish emits application_created.
  4. The applicants page receives the event and refreshes the affected record.
  5. If the event payload is missing or malformed, the page falls back to a full reload.
sequenceDiagram
    participant Client as Admin Client
    participant API as create_application
    participant Repo as SQLAlchemyHousingApplicationRepository
    participant Events as application_events
    participant Stream as stream_housing_application_events
    participant Page as ApplicantsPage

    Client->>API: POST api v1 applications
    API->>Repo: create application
    Repo-->>API: persisted application
    API->>Events: publish application_created
    Events-->>Stream: SSE event
    Page->>Stream: EventSource connect
    Stream-->>Page: event payload
    Page->>Page: refresh list or single record

Error Handling

Validation and response codes

backend/tests/interface/test_application_endpoint.py

backend/tests/interface/test_phone_application_endpoint.py

Scenario Endpoint Status Message
Missing consent POST /api/v1/applications 400 Privacy policy consent is required.
Blank email POST /api/v1/applications 400 Email is required.
Blank full name POST /api/v1/applications 400 Full name is required.
Missing application GET /api/v1/applications/{id} 404 Application not found.
Missing archive target POST /api/v1/applications/{id}/archive 404 Application not found.
Applicant tries to decide POST /api/v1/applications/{id}/decision 403 You do not have permission to perform this action.
Invalid phone POST /api/phone-applications 400 Enter a valid phone number.

Repository and migration errors

backend/tests/infra/test_housing_application_repository.py

backend/tests/test_schema_migrations.py

The repository layer keeps its own invariants stable by returning None for missing IDs, preserving row counts on bulk delete, and upgrading legacy application tables to include archived.

Helper regressions

backend/tests/interface/test_application_endpoint.py

The same interface test file also protects helper behavior used during intake:

  • _download_residence_permit_file_from_url rejects non-HTTP URLs such as file:///tmp/image.png.
  • _extract_residence_permit_schema_from_document prefers form-field values over raw OCR text when both exist.

Testing Considerations

What to run for this domain

File Primary purpose
backend/tests/interface/test_application_endpoint.py HTTP contract coverage for application create, list, detail, archive, decision, phone search, and OCR helpers
backend/tests/interface/test_phone_application_endpoint.py HTTP contract coverage for phone-only application flows
backend/tests/infra/test_housing_application_repository.py Persistence invariants for housing application storage
backend/tests/test_schema_migrations.py Schema compatibility for legacy application tables

What the tests prove about fixtures

Fixture Proven behavior
build_payload() Enough to create a valid housing application
_build_application(index) Enough to seed repository-level records with database-managed fields omitted
client fixture in backend/tests/conftest.py Starts with an admin token already attached to the default headers
data/applications.sample.json Should mirror the successful request shape used by the interface tests
data/applications.json Should remain loadable as a working dataset for local debugging

Key Classes Reference

Class Responsibility
SQLAlchemyHousingApplicationRepository Persistence boundary for housing application create, list, fetch, archive, update, and reset operations in housing_application_repository.py
HousingApplication Domain object used by submit_housing_application and the repository fixture builders in housing_application.py
PhoneApplication Lightweight record type used by the phone application flow in phone_application.py
SQLAlchemyPhoneApplicationRepository Persistence boundary for phone-only application records in phone_application_repository.py
application_events Event stream publisher and SSE source used by the application create and list pages in http_endpoints.py