# Testing

# Testing

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [docs/ai/dal-testing.md](docs/ai/dal-testing.md)
- [test/helpers/setup.ts](test/helpers/setup.ts)

</details>



This section provides a high-level overview of the testing strategy and infrastructure for the `@primebrick/dal-pg` package. The test suite is designed to ensure correctness, performance, and type safety across all layers of the DAL, using real PostgreSQL instances to validate behavior.

## Test Strategy and Infrastructure

The DAL uses **Vitest** as its primary test runner [docs/ai/dal-testing.md:7-9](). The testing philosophy rejects mocks in favor of integration tests against a live database to ensure that SQL generation and type coercion match PostgreSQL's actual behavior [docs/ai/dal-testing.md:8-8]().

### Core Infrastructure Components
The test environment relies on several key utilities and configurations:
*   **Environment Configuration**: Tests require a `DATABASE_URL` environment variable, typically loaded via `dotenv` from a `.env` file [docs/ai/dal-testing.md:13-19]().
*   **Shared Connection Pool**: The `getTestPool()` helper manages a singleton `pg.Pool` instance for the test process [test/helpers/setup.ts:28-38]().
*   **Idempotent Schema Setup**: The `setupTestSchema()` function uses `CREATE TABLE IF NOT EXISTS` to prepare the database without destructive changes [test/helpers/setup.ts:52-152]().
*   **Test Isolation**: Isolation is maintained via `truncateTestTables()`, which executes `TRUNCATE ... RESTART IDENTITY CASCADE` before every test case [test/helpers/setup.ts:158-163]().

For details on the setup and entity definitions, see **[Test Infrastructure and Entities](#7.1)**.

### Testing Architecture Diagram
The following diagram illustrates the relationship between the test runner, the helper utilities, and the database.

**Test Execution Flow**
```mermaid
graph TD
    subgraph "Vitest Runner"
        A["Test File (*.test.ts)"]
    end

    subgraph "Setup Helpers"
        B["getTestPool()"]
        C["setupTestSchema()"]
        D["truncateTestTables()"]
    end

    subgraph "External"
        E[(".env (DATABASE_URL)")]
        F[("PostgreSQL DB")]
    end

    A --> B
    B --> E
    A --> C
    A --> D
    C --> F
    D --> F
    A -- "Execute SQL" --> F
```
Sources: [docs/ai/dal-testing.md:5-34](), [test/helpers/setup.ts:1-46]()

## Test Suite Coverage

The test suite is divided into specialized files targeting specific functionality of the `Repository` and `Dal` classes.

### Functional Areas
*   **CRUD and Finders**: Validates standard operations like `add`, `findById`, and `update` [docs/ai/dal-testing.md:114-114]().
*   **Bulk Operations**: Tests high-volume writes using the `TEMP TABLE` strategy and batched inserts [docs/ai/dal-testing.md:115-115]().
*   **Type Mapping**: Verifies the matrix of JS ↔ PG types, including native `bigint` and `numeric` precision handling [docs/ai/dal-testing.md:116-116]().
*   **Streaming**: Ensures `AsyncIterable` results work correctly for large datasets via `pg-query-stream` [docs/ai/dal-testing.md:117-117]().
*   **Negative Paths**: Confirms that the system throws appropriate errors like `NotFoundError` or `ValidationError` instead of failing silently [docs/ai/dal-testing.md:118-118]().
*   **Performance**: Benchmarks operations at scales of 100 to 1M rows [docs/ai/dal-testing.md:119-119]().

For a detailed breakdown of specific test files and their coverage, see **[Test Suite Coverage](#7.2)**.

### Code-to-Test Mapping
The following diagram maps core DAL classes to their corresponding test suites.

**DAL Entity to Test Suite Mapping**
```mermaid
graph LR
    subgraph "Code Entity Space"
        DAL["Dal Class"]
        REPO["Repository Class"]
        QUERY["QueryStream"]
    end

    subgraph "Test Suite Space"
        T_DAL["dal.test.ts<br/>dal-timeout.test.ts"]
        T_REPO["repository-crud.test.ts<br/>repository-bulk.test.ts<br/>repository-types.test.ts"]
        T_STR["repository-streaming.test.ts"]
        T_NEG["repository-negative.test.ts"]
    end

    DAL --> T_DAL
    REPO --> T_REPO
    REPO --> T_NEG
    QUERY --> T_STR
```
Sources: [docs/ai/dal-testing.md:112-120](), [test/helpers/setup.ts:52-152]()

## Test Entities

The infrastructure uses four primary entities to cover different database scenarios:

| Entity Name | Code Identifier | Purpose |
| :--- | :--- | :--- |
| **Simple Test** | `SimpleTestEntity` | Basic CRUD and audit field validation [docs/ai/dal-testing.md:37-46](). |
| **Type Matrix** | `TypeTestEntity` | Comprehensive PG type mapping (JSONB, Timestamps, etc.) [docs/ai/dal-testing.md:47-61](). |
| **Simple Bench** | `BenchSimpleEntity` | High-speed bulk operation benchmarks [test/helpers/setup.ts:102-117](). |
| **Primitive Bench** | `BenchPrimitivesEntity` | Wide-row performance testing with 20+ columns [test/helpers/setup.ts:121-151](). |

For the full property definitions and mapping matrix, see **[Test Infrastructure and Entities](#7.1)**.

Sources: [docs/ai/dal-testing.md:35-61](), [test/helpers/setup.ts:52-152]()

---
