# Testing an application without Db2

`db2kit/testing` replaces ibm_db in the tests of an application: a scripted fake driver for unit tests, and the recording and replay of what a real subsystem answered, for scenarios that run without it. Pass the driver to `createDb2(config, { driver })` or `Db2Module.forRoot({ config, driver })`: ibm_db is then never loaded, and no server, VPN or Db2 client is needed.

| Tool              | For                                               | Answers                                                |
| :---------------- | :------------------------------------------------ | :----------------------------------------------------- |
| `FakeDriver`      | unit tests, error and failure scenarios           | what each test declares                                |
| `recordingDriver` | a run of scenarios against a test subsystem, once | what the real subsystem answers, written to a cassette |
| `replayDriver`    | the same scenarios in CI or on a laptop           | the cassette, never an invented answer                 |

The fake driver is the one db2kit's own tests use. It answers in the exact form ibm_db 4.0.1 gives: rows as arrays with column metadata, OUT and INOUT values in catalog order, `CHAR` and `GRAPHIC` padded with blanks, `DECIMAL` as text, errors as `{ message, sqlcode, sqlstate }`. So the application meets the same conversions, checks and errors as against Db2.

## Unit tests with the fake driver

```ts
import { createDb2, sql } from 'db2kit';
import { db2Error, FakeDriver, resultSet } from 'db2kit/testing';

const driver = new FakeDriver();
driver.on(
  'FROM MYSCHEMA.CONTRACT',
  resultSet([{ ID: 1, CODE: 'A  ' }], { ID: 'INTEGER', CODE: 'CHAR' }),
);
driver.on('INSERT INTO MYSCHEMA.CONTRACT', { error: db2Error('DUPLICATE_KEY') });

const db = createDb2(config, { driver });
await db.query(sql`SELECT ID, CODE FROM MYSCHEMA.CONTRACT`); // [{ ID: 1, CODE: 'A' }]
await db.execute(sql`INSERT INTO MYSCHEMA.CONTRACT (ID) VALUES (1)`); // Db2QueryError, code DUPLICATE_KEY
driver.calls; // every statement sent, with its parameters
```

| Method or property                                  | Effect                                                                                                                                                                                                                                                                                                                                                           |
| :-------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `on(match, answer)`                                 | Answers the statements whose text matches (a regular expression, tried from the start of each statement whatever its flags, or a text found anywhere, ignoring case). The last rule added wins. `answer` is a result set (`resultSet(...)`), an answer `{ resultSets, affectedRows, outParams, error, delayMs }`, or a function of `(sql, params)` returning one |
| `onCall(procedure, answer)`                         | Answers the `CALL` of a procedure by property name (below)                                                                                                                                                                                                                                                                                                       |
| `calls`                                             | Every statement executed: `sql`, `params`, `connectionId`, `autocommit`                                                                                                                                                                                                                                                                                          |
| `openError`                                         | Every login fails with this error, or a function of the connection string returning one: `db2Error('AUTHENTICATION_FAILED')`, `db2Error('CONNECTION_LOST')`                                                                                                                                                                                                      |
| `openDelayMs`, `delayMs` of an answer               | A slow login, a slow statement. Without them, the fake sets no timer: it works under the fake timers of a test runner                                                                                                                                                                                                                                            |
| `cutNetwork()`                                      | Silent network cut: open connections still look usable, their next statement fails with SQL30081N                                                                                                                                                                                                                                                                |
| `transactionErrors`                                 | The next `begin`, `commit` or `rollback` fails with this error, once                                                                                                                                                                                                                                                                                             |
| `counters`, `connectionStrings`, `transactionCalls` | Connections opened and closed, login attempts, transaction steps                                                                                                                                                                                                                                                                                                 |

`db2Error(code)` builds the error ibm_db reports for a stable code of db2kit: its SQLCODE, SQLSTATE and message, which db2kit classifies back to that code (`DUPLICATE_KEY`, `NULL_NOT_ALLOWED`, `DEADLOCK_OR_TIMEOUT`, `CONNECTION_LOST`, `AUTHENTICATION_FAILED`...). `resultSet(rows, types)` builds a result set from row objects; a column takes the Db2 type given in `types`, `VARCHAR` otherwise.

## Procedures by property name

A test calls a procedure as the service does, through the `...WithOutcome` export of its rule, so that the rule is tested with the program's answers. `db.call` refuses the descriptor alone in tests too; a test of what a program returns before its rule exists calls it through `unchecked(myProc, 'unit test')` ([procedures.md](procedures.md#in-tests)).

```ts
driver.onCall(myProcWithOutcome, ({ input }) => ({
  outputs: {
    returnCode: '000',
    remainingAmount: 37.5,
    amountStatus: Number(input.amountIn) > 15000 ? 'E' : ' ',
  },
}));
```

- `input` holds the IN and INOUT values as db2kit sends them: after default inputs and input codecs. An amount coded with `codecs.digits({ scale: 2 })` arrives as `'0000001250'`: the test sees what the program would receive.
- `outputs` are given by property and come back to db2kit as ibm_db returns them: `CHAR` and `GRAPHIC` padded, `DECIMAL` as text with its scale. db2kit then normalizes them and applies the outcome rule, as for the real program. A missing output comes back as `null`.
- An output the procedure does not have, a text longer than its parameter or a number with more decimals than its scale is refused: Db2 could not return it.
- `resultSets`, `error` and `delayMs` work as in `on`.

The fake answers what the test declares. It does not know the rules of the program: a scenario that checks the rules themselves needs the program, which is what recording is for.

## Recording and replay

A suite of scenarios runs once against a test subsystem with `recordingDriver`, which wraps the real driver and writes down every statement with what it returned. The cassette is a JSON file, kept with the tests. `replayDriver` then answers the same statements from it, without any server.

```ts
import { createDb2, ibmDbDriver } from 'db2kit';
import { procedureMask, recordingDriver, replayDriver } from 'db2kit/testing';

// Once, against the test subsystem (VPN, real credentials).
const recorder = recordingDriver(ibmDbDriver(), {
  mask: procedureMask(myProc, { inputs: ['personIdIn'], outputs: ['personIdOut'] }),
});
const db = createDb2(config, { driver: recorder });
await runScenarios(db);
recorder.save('test/cassettes/encoding.json');

// In CI, without the subsystem.
const replayed = createDb2(config, { driver: replayDriver('test/cassettes/encoding.json') });
await runScenarios(replayed);
```

- **What is recorded**: the statement text, the inputs (OUT placeholders and buffer sizes left out), the columns and rows db2kit read, the affected rows, the OUT and INOUT values, or the error with its SQLCODE and SQLSTATE.
- **Matching**: a statement is answered by the recording of the same text and the same inputs. Several recordings of the same statement and inputs are answered in the order recorded, then the last one again (`repeat: 'sequence'`, the default), or always the first (`repeat: 'first'`).
- **Never an invented answer**: a statement never recorded fails with an error that names the input positions differing from the closest recording, never their values. Record that case.
- **Masking**: the cassette lives in the repository of the application. A test subsystem often holds a copy of production data, so keep identifiers of real people out of it. `procedureMask(procedure, { inputs, outputs })` masks parameters by property name:
  - a masked input is never written and matches any value at replay;
  - a masked output is written as a value db2kit still reads at replay: `X`s of the same length for text, `0` for a number, `'0'` for numeric text (DECIMAL, BIGINT, a float INOUT). Null stays null, and any other value is written as null;
  - an INOUT parameter named in either list is masked both ways, since the value it brings back is often the one it was given;
  - a name in the wrong list is refused (an IN parameter in `outputs`, an OUT parameter in `inputs`): it would mask nothing.

  `procedureMask` covers parameters only. The rows of a result set and the message of a Db2 error are written as returned. For columns and other statements, a mask is `{ parameter(sql, index), value(value, { sql, output, column }) }`. Better still, run the scenarios with invented people that exist only on the test subsystem.

- **When the program changes**: run the suite against the subsystem again. The difference between the two cassettes shows what changed in the answers.

A procedure with a control-only mode, which checks every field without writing, suits recording: the scenarios stay reproducible, since nothing changes on the subsystem between two runs.

## Scenarios from a table of rules

When the rules of a program are values in a table (minimums, maximums, counts per type), the cases at their limits can be generated from that table rather than written by hand: the value just below a minimum and at it, the amount at a remaining limit and one cent above. Their expected answers come from the program, through recording: a rewrite of the rules in JavaScript would differ exactly at those limits (bound included or not, the date a value is computed at, the period a limit covers). The recorded answers then document the rules as the program applies them. The generator belongs to the application: it holds business rules, db2kit does not.

## Limits

- The fake driver runs no SQL: a read answers what its rule declares, whatever the `WHERE`. Logic in SQL (filters, joins, paging order) is checked by the integration tests of db2kit against a real subsystem ([integration-tests.md](integration-tests.md), in the repository of db2kit).
- A replay answers only what was recorded, with the data of the subsystem at that time.
- The catalog commands of the CLI (`generate`, `check`, `describe`, `doctor`) need a real subsystem.
