# Testing Policy

> Type: Policy. Requirements for testability, structure and naming of tests.

## Contents

- [Purpose](#назначение)
- [Mandatory tests](#обязательность-тестов)
- [Which usually does not require a separate test](#что-обычно-не-требует-отдельного-теста)
- [Test requirements](#требования-к-тестам)
- [Insulation](#изоляция)
- [Current test circuit](#текущий-тестовый-контур)
- [Test data](#тестовые-данные)
- [Naming test case](#именование-test-case)
- [Preferred behavior verbs](#предпочтительные-behavior-verbs)
- [Public behavior instead of private implementation](#публичное-поведение-вместо-private-implementation)
- [Error cases and boundary cases](#error-cases-и-boundary-cases)
- [Regression tests](#regression-tests)
- [Current contract instead of project history](#актуальный-контракт-вместо-истории-проекта)
- [Comments in tests](#комментарии-в-тестах)
- [Communication with change policy](#связь-с-политикой-изменений)
- [Good practices](#хорошие-практики)

## Purpose

A test helps establish that a change preserves the required behavior and covers important boundary cases. The expected result relates to a contract relied on by users or other parts of the program. Describing the check this way keeps it useful when the internal implementation changes.

## Mandatory tests

All reusable code must have tests. This includes shared modules, boundaries between layers and processing of external data.

Tests cover:

* shared modules and reusable application services;
* reusable domain logic: calculations, condition checks, rules and data conversions;
* adapters and infrastructure code, including filesystem access and external services;
* parsing configuration, command-line arguments and environment variables;
* input validation and normalization, and mapping external errors to application errors;
* pipelines, as well as orchestration that contains branching or decisions about the next action;
* code paths with multiple valid or error scenarios;
* boundary cases that could silently corrupt data;
* scenarios that have already failed or have a high risk of regression.

## Which usually does not require a separate test

Usually there is no need to separate the following:

* one-time merging of calls inside bootstrap, if it is not reused;
* trivial passthrough without its own logic;
* simple argument passing without branching, normalization or contract mapping;
* private helper if its behavior is fully verifiable through the public API;
* framework boilerplate without its own project-specific logic.

The absence of a test is only acceptable if the code actually does not contain its own behavior. If branching, normalization, fallback, mapping errors or a non-standard edge case appear, the test becomes mandatory.

## Test requirements

Tests should be:

* isolated;
* deterministic; The
* readable;
* minimal, but sufficient;
* focused on one behavior;
* focused on the observable result, and not on internal implementation.

One test should check one behavior.

It is acceptable to have several assertions in one test if they describe the same contract. If assertions test different reasons for behavior change, they need to be separated into separate tests.

## Insulation

The test should minimize dependence on:

* of the real file system, if it is not filesystem behavior that is checked;
* network;
* current time;
* order of running tests;
* external processes;
* global mutable state;
* stale build artifacts.

If dependency on an external resource is the essence of a test, it must be clearly visible from the test name, suite or fixture.

## Current test circuit

Commands and boundaries of unit, integration and end-to-end checks are defined in the documentation and configuration of a specific project. Fast Loop does not use the network, external services, or other external infrastructure. It prohibits hidden conditionals `skip` that depend on environment variables or service availability.

A successful unit check does not confirm real integration or end-to-end behavior. The unavailability of the desired environment is reported explicitly and does not translate into a successful check.

## Test data

Test data should be minimal but sufficient for the scenario.

Synthetic test documents and fixtures should only use test-owned identities and explicitly created test dependencies. They must not import, read, or reference production configurations, configured defaults, and deployment-specific identities by name or path. If the parser or resolver being tested needs a catalog, loader, or other owner dependency, the test must pass its synthetic implementation explicitly. Changing operational configuration not related to a test should not break such a test.

An exception is allowed only for a separate conformance test, the subject of which is the production artifact itself. This dependency must be explicitly specified in the name of the test suite or test case; production artifact is read unchanged and is not used as a general fixture to test other behavior.

Arrange should be visible in the test itself. You should not transfer test data, setting up the environment or playing production orchestration into common `*.fixture.ts`, `test-utils` and similar modules. Such abstractions hide the essential conditions of the script, create implicit dependencies between test suites and begin to require testing themselves.

A local auxiliary construct is valid when it represents a stateful test double, controls the lifecycle of a temporary resource, or expresses a repeatable boundary structure that cannot be shortened without losing readability. Parameters that affect the behavior being tested must remain explicit within `test()`. One-time wrapper functions and factories with random values ​​or current times are not allowed.

There is no need to create a realistic dataset if one object with three fields is enough for testing.

Good:

```ts
test('returns false for invalid FIGI length', () => {
  assert.equal(isFigi('BBG004730N8'), false);
});
```

Bad:

```ts
test('validates instrument', () => {
  const instrument = {
    figi: 'BBG004730N8',
    ticker: 'SBER',
    name: 'Sberbank',
    currency: 'rub',
    exchange: 'MOEX',
    lot: 10,
  };

  assert.equal(isFigi(instrument.figi), false);
});
```

Extra fields hide the reason for the test and increase the cost of support.

Conventions for grouping tests with `describe()` are in [Languages and platforms](./languages-and-platforms.md#группировка-тестов).

## Naming test case

`test()` calls only expected behavior.

The test name must not repeat the subject or method name if they are already specified in `describe()`.

Good:

- `BufferedTextFileWriter`
  - `#close`
    - `flushes buffered chunks before closing stream`
    - `keeps repeated close safe`

Bad:

- `BufferedTextFileWriter`
  - `#close`
    - `BufferedTextFileWriter close flushes buffered chunks`

Repeating subject makes the name noisy and impairs the readability of test output.

If a test is hard to name, it likely checks too much or lacks a clear contract.

## Preferred behavior verbs

Preferred verbs for `test()`:

| Name opening | Behavior described |
| --- | --- |
| `returns ...` | The returned result |
| `throws ...` | An exception thrown during an operation |
| `rejects ...` | An asynchronous operation completing with an error |
| `parses ...` | Parsing input data |
| `formats ...` | Formatting the result |
| `writes ...` | Writing data |
| `reads ...` | Reading data |
| `keeps ...` | Keeping a state or property unchanged |
| `skips ...` | Skipping an action under specified conditions |
| `uses ...` | Selecting and using data or a dependency |
| `does not ...` | The absence of an action or unwanted effect |
| `handles ...` | Handling a particular case |
| `preserves ...` | Preserving data or a guaranteed property |
| `computes ...` | The result of a calculation |
| `maps ...` | Converting one data representation into another |
| `normalizes ...` | Bringing data into a consistent form |
| `ignores ...` | Ignoring data or an event under specified conditions |

Good:

- `returns empty result for empty ranges`
- `throws when FIGI has invalid format`
- `does not start trainer when all ranges are skipped by warmup`

Bad:

- `works correctly`
- `test invalid input`
- `should process data`

`should` is not technically prohibited, but the preferred style is a direct description of the observed behavior without an extra modal word.

## Public behavior instead of private implementation

Private implementation details should not normally have dedicated suite names.

Private details need to be tested through public behavior.

Good:

- `CandleRangePolicy`
  - `#split`
    - `keeps ranges within provider limit`

Bad:

- `CandleRangePolicy`
  - `#calculateInternalOffset`
    - `returns offset`

An exception is only allowed if the helper is a reusable export and itself becomes part of the module contract.

## Error cases and boundary cases

Reusable code must have tests not only for the happy path, but also for erroneous and boundary scenarios.

It is especially important to test:

* empty input;
* minimum acceptable input;
* maximum allowed input;
* invalid format;
* unsupported enum value;
* missing required field;
* duplicate input;
* out-of-order input;
* repeated call;
* idempotency;
* fallback behavior;
* error mapping;
* skipped branch.

Not every module is required to have all of these scripts. Only those that correspond to his responsibility are needed.

## Regression tests

Regression test is needed if the behavior has already broken or the risk of a repeat defect is high.

Regression test should fix the production contract, and not a specific old erroneous implementation.

Good:

- `does not start trainer when frame list is empty`

Bad:

- `fixes bug from yesterday`

The regression case context can be revealed with a comment if without it the reason for the test is not obvious.

## Current contract instead of project history

The test checks the current production contract and supported behavior. It should not depend on the sequence of changes through which the project arrived at its current state.

Prohibited:

* import timestamped migration classes and check intermediate versions of schema, order of historical SQL operations or `down()` in unit tests;
* build test fixture from the previous version of schema only for the sake of checking the migration path;
* check for the absence of a remote source file, contract file, export, alias, CLI path or environment variable;
* save the test after deleting the checked compatibility surface only as a negative assertion under the previous name.

If the current contract is closed, you need to check its positive form and the deviation of the neutral unknown input. The real historical name should not become part of the new test contract.

Removing a production path means deleting the fixtures and tests dedicated to it. Git history remains a source of information about past behavior.

## Comments in tests

The normative rules for commenting in tests are found only in [comment policy in tests](./test-comment-style.md).

## Communication with change policy

Work on tests follows the [change policy](./change-policy.md). A test for a local defect must not impose a new architecture.

Acceptable changes include:

* adding a minimal test for a new requirement;
* adding a regression test for the defect being fixed;
* renaming a test case when its current name obscures the behavior under test;
* improving a fixture locally when the test otherwise cannot express its scenario.

## Good practices

* do not use production credentials, real networks or mutable external state;
* prefer an explicit expected value over checking that execution did not fail.

## Asynchronous behavior and snapshots

The test expects a `Promise` to be tested. Instead of an arbitrary delay, a managed timer, `Promise`, or observable state is used. Modified clocks, listeners, spies, mocks and globals are cleared after the script.

If the application is protected from a late response, it checks that the old result does not overwrite the new state after a second action, reset or unmount. The check for the absence of a callback must take place at the time of its expected activation.

A snapshot is allowed for a stable output contract when targeted assertions express the intent less clearly.

Published deprecated props and aliases remain under contract as long as the project supports them. Their tests are not removed due to historical origin.

DOM, accessibility, responsive layout, and browser integration checks are covered in [Web interfaces](./languages-and-platforms.md#проверки-в-браузере).
