# Test Infrastructure and Entities

# Test Infrastructure and Entities

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

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

- [test/benchmark.vitest.config.ts](test/benchmark.vitest.config.ts)
- [test/entities/bench-primitives.entity.ts](test/entities/bench-primitives.entity.ts)
- [test/entities/bench-simple.entity.ts](test/entities/bench-simple.entity.ts)
- [test/entities/simple-test-entity.ts](test/entities/simple-test-entity.ts)
- [test/entities/type-test-entity.ts](test/entities/type-test-entity.ts)
- [test/helpers/setup.ts](test/helpers/setup.ts)
- [vitest.config.ts](vitest.config.ts)

</details>



This page documents the testing infrastructure for `@primebrick/dal-pg`. The testing strategy relies on **Vitest** for execution, a shared PostgreSQL connection pool for performance, and a set of specialized test entities that exercise the full range of DAL features, from basic CRUD to complex type coercion and high-volume benchmarks.

## Vitest Configuration

The codebase uses two distinct Vitest configurations to separate standard functional tests from long-running benchmarks. Both configurations disable `fileParallelism` to prevent race conditions during schema setup and table truncation [vitest.config.ts:11-11](), [test/benchmark.vitest.config.ts:10-10]().

| Config File | Purpose | Timeout | Included Paths |
|:---|:---|:---|:---|
| `vitest.config.ts` | Unit and Integration tests | 30s | `test/**/*.test.ts` (excl. benchmarks) |
| `test/benchmark.vitest.config.ts` | Performance/Load tests | 600s (10m) | `test/benchmark/**/*.test.ts` |

**Sources:** [vitest.config.ts:3-13](), [test/benchmark.vitest.config.ts:3-12]()

## Test Setup and Lifecycle

The `test/helpers/setup.ts` file provides the foundation for all database-connected tests. It manages the connection lifecycle, configures global type parsers, and ensures the database schema is ready.

### Environment Requirements
Tests require a `DATABASE_URL` environment variable, typically provided via a `.env` file in the repository root [test/helpers/setup.ts:30-35]().

### Connection Management
*   **`getTestPool()`**: Initializes a singleton `pg.Pool` with a maximum of 5 connections [test/helpers/setup.ts:28-38]().
*   **`closeTestPool()`**: Gracefully shuts down the pool, typically called in a Vitest `afterAll` hook [test/helpers/setup.ts:41-46]().

### Type Parser Configuration
To ensure tests accurately reflect JavaScript types, the setup helper configures global `pg` type parsers:
1.  **`INT8` (BigInt)**: Configured to return native JS `bigint` instead of strings [test/helpers/setup.ts:15-15]().
2.  **`NUMERIC`**: Returns a `number` if the value is within `Number.MAX_SAFE_INTEGER` and has no decimal loss; otherwise, it returns a `string` to prevent precision overflow [test/helpers/setup.ts:18-23]().

### DDL and Data Isolation
*   **`setupTestSchema()`**: Performs idempotent DDL execution using `CREATE TABLE IF NOT EXISTS` for all test entities [test/helpers/setup.ts:52-152]().
*   **`truncateTestTables()`**: Ensures test isolation by running `TRUNCATE ... RESTART IDENTITY CASCADE` on all test tables. This is usually called in `beforeEach` [test/helpers/setup.ts:158-163]().

**Sources:** [test/helpers/setup.ts:1-177]()

## Test Entity Definitions

The infrastructure includes four primary entities used to verify different aspects of the DAL. All entities utilize `@AuditTrail()` to test the automated audit stamping system.

### Functional Test Entities

#### 1. `SimpleTestEntity`
Used for basic CRUD, finder methods, and soft-delete verification. It represents a standard, minimal auditable table.
*   **Table**: `dal_test_simple`
*   **Key Fields**: `id` (PK), `uuid` (Unique), `name`, `description`.
*   **Sources**: [test/entities/simple-test-entity.ts:19-54]()

#### 2. `TypeTestEntity`
Designed to verify the **PG ↔ JS Type Mapping Matrix**. It covers 77 test cases for coercion and hydration.
*   **Table**: `dal_test_types`
*   **Sources**: [test/entities/type-test-entity.ts:30-97]()

### Benchmark Entities

#### 3. `BenchSimpleEntity`
A narrow 5-column table used to measure raw throughput of bulk operations (e.g., `addMany`, `updateMany`) without the overhead of complex types.
*   **Table**: `test_bench_simple`
*   **Sources**: [test/entities/bench-simple.entity.ts:19-57]()

#### 4. `BenchPrimitivesEntity`
A wide 20+ column table covering every supported PostgreSQL primitive type. Used to measure performance impact when handling diverse data types in bulk.
*   **Table**: `test_bench_primitives`
*   **Sources**: [test/entities/bench-primitives.entity.ts:19-113]()

## PG ↔ JS Type Mapping Matrix

The following table describes how `TypeTestEntity` maps PostgreSQL types to TypeScript/JavaScript types, as verified by the test suite.

| PostgreSQL Type | TS Property Type | Implementation Detail |
|:---|:---|:---|
| `integer` | `number` | Standard 32-bit int [test/entities/type-test-entity.ts:41-41]() |
| `bigint` | `bigint` | Handled via `INT8_OID` parser [test/entities/type-test-entity.ts:44-44]() |
| `boolean` | `boolean` | [test/entities/type-test-entity.ts:47-47]() |
| `varchar(N)` | `string` | [test/entities/type-test-entity.ts:50-50]() |
| `text` | `string` | [test/entities/type-test-entity.ts:53-53]() |
| `numeric(15,2)` | `number` | Safe for standard currency/math [test/entities/type-test-entity.ts:57-57]() |
| `numeric(38,0)` | `string` | Coerced to string to avoid overflow [test/entities/type-test-entity.ts:60-60]() |
| `timestamptz` | `Date` | [test/entities/type-test-entity.ts:67-67]() |
| `date` | `Date` | [test/entities/type-test-entity.ts:70-70]() |
| `jsonb` | `Record<string, unknown>` | Auto-serialized/parsed [test/entities/type-test-entity.ts:74-74]() |
| `text[]` | `string[]` | [test/entities/bench-primitives.entity.ts:83-83]() |

**Sources:** [test/entities/type-test-entity.ts:39-75](), [test/helpers/setup.ts:14-23]()

## Infrastructure Diagrams

### Data Flow: Test Setup and Execution

The following diagram illustrates how the test infrastructure initializes the environment before Vitest runs the test suites.

```mermaid
graph TD
    subgraph "Initialization Phase"
        ENV[".env / DATABASE_URL"] --> GTP["getTestPool()"]
        GTP --> POOL["pg.Pool (max: 5)"]
        POOL --> STP["setTypeParser(INT8 / NUMERIC)"]
        STP --> STS["setupTestSchema()"]
    end

    subgraph "Schema Setup (DDL)"
        STS --> D1["CREATE TABLE dal_test_simple"]
        STS --> D2["CREATE TABLE dal_test_types"]
        STS --> D3["CREATE TABLE test_bench_simple"]
        STS --> D4["CREATE TABLE test_bench_primitives"]
    end

    subgraph "Test Execution Loop"
        TTT["truncateTestTables()"] --> TEST["Run Vitest Test"]
        TEST --> TTT
    end

    D4 --> TTT
```
**Sources:** [test/helpers/setup.ts:28-163](), [vitest.config.ts:3-13]()

### Code Entity Association: Test Helpers to Operations

This diagram maps the utility functions in `setup.ts` to the database operations they perform.

```mermaid
graph LR
    subgraph "setup.ts"
        direction LR
        fn_getPool["getTestPool()"]
        fn_setup["setupTestSchema()"]
        fn_trunc["truncateTestTables()"]
        fn_close["closeTestPool()"]
    end

    subgraph "PostgreSQL Actions"
        act_conn["Connect to DATABASE_URL"]
        act_ddl["CREATE TABLE IF NOT EXISTS..."]
        act_clear["TRUNCATE ... RESTART IDENTITY"]
        act_end["pool.end()"]
    end

    fn_getPool -- "initializes" --> act_conn
    fn_setup -- "executes" --> act_ddl
    fn_trunc -- "executes" --> act_clear
    fn_close -- "calls" --> act_end
```
**Sources:** [test/helpers/setup.ts:28-176]()

---
