# Test comment policy

> Type: Policy. Rules for comments in tests; complement [testing policy](./testing-policy.md).

## Contents

- [Purpose](#назначение)
- [General rule](#общее-правило)
- [When a comment is needed in a test](#когда-комментарий-в-тесте-нужен)
- [When a comment is not needed in the test](#когда-комментарий-в-тесте-не-нужен)
- [Test script block](#блок-тестового-сценария)
- [Comment inside the test](#комментарий-внутри-теста)
- [Regression-comments](#regression-комментарии)
- [Comments on expected value](#комментарии-к-expected-value)
- [Comments on test fixtures](#комментарии-к-test-fixtures)
- [Comments on mock/stub/fake](#комментарии-к-mockstubfake)
- [Comments to snapshot / golden tests](#комментарии-к-snapshot--golden-tests)
- [Given / When / Then blocks](#блоки-given--when--then)
- [Comments on intentional omissions](#комментарии-к-intentional-omissions)
- [Comments and test names](#комментарии-и-имена-тестов)
- [Commentary language](#язык-комментариев)
- [Prohibited comments](#запрещенные-комментарии)

## Purpose

A test comment helps explain a risk, the behavior being checked, or an unusual setup. This is especially useful for a regression: the next reader can understand which property the check protects. The test name and actions already show the ordinary scenario; the explanation adds important context.

## General rule

Start with clear names for `describe()` and `test()`. If a better test name can replace a comment, improve the name. A comment adds important context that the name and test actions do not explain; these cases are listed below.

## When a comment is needed in a test

A comment is needed if it explains:

* a risk to the running application or one of its invariants;
* regression case;
* is a historically fragile place;
* non-obvious data preparation;
* the reason for the strange expected value;
* external API limitation;
* difference between mock/stub and real behavior;
* why exactly this behavior is checked;
* why the test does not intentionally check for adjacent liability;
* which contract captures snapshot or golden output.

## When a comment is not needed in the test

Comments that repeat code, language syntax or the test name are not allowed. An explanation is also unnecessary when the expected value and purpose of the check are clear from the input, test name and assertion. Labeling obvious preparation, execution and verification steps merely repeats the code’s structure.

Bad:

> Arrange · Act · Assert

```ts
test('returns empty result for empty ranges', () => {
  const ranges = [];

  const result = buildResult(ranges);

  assert.deepEqual(result, []);
});
```

Better:

```ts
test('returns empty result for empty ranges', () => {
  const result = buildResult([]);

  assert.deepEqual(result, []);
});
```

## Test script block

If a group of tests protects an important production contract, a separate script block is allowed before it.

Template:

> The scenario describes [behavior under test].
>
> - First protected invariant — [invariant 1].
> - Second protected invariant — [invariant 2].
>
> [Adjacent responsibility] has its own tests.

Good:

> This scenario checks explicit completion of writes through `BufferedTextFileWriter`.
>
> - Buffered chunks are flushed before the stream closes.
> - The last line is preserved.
> - Calling `close()` again is safe.
>
> File-system permissions and the behavior of Node.js streams are tested separately.

- `BufferedTextFileWriter`
  - `#close`

Bad:

> BufferedTextFileWriter tests.

- `BufferedTextFileWriter`

This comment does not add any meaning: subject is already visible from the name `describe()`.

## Comment inside the test

A local test comment is needed when the reason for preparing data, choosing an expected result or making an unusual check would otherwise be unclear. Place it next to what it explains. After refactoring, remove it if the meaning has become clear from the code. Do not add a comment to every assertion automatically.

Good:

> The last line deliberately omits `\n`. It was previously lost when the stream closed without an explicit flush.

```ts
test('flushes last line when file is closed without trailing newline', async () => {
  await writer.writeLine('last');

  await writer.close();

  assert.equal(await readFile(path, 'utf8'), 'last');
});
```

Bad:

> Write line · Close writer · Check result

```ts
test('writes line and closes file', async () => {
  await writer.writeLine('last');

  await writer.close();

  assert.equal(await readFile(path, 'utf8'), 'last');
});
```

## Regression-comments

Regression comment is needed if without it it is not clear why the test captures exactly this scenario.

Good:

> An empty frame list contains no training data. Starting Python in this case wastes time on an external process.

```ts
test('does not start trainer when frame list is empty', async () => {
  const result = await useCase.execute(emptyRequest);

  assert.equal(result.predictedRows, 0);
  assert.equal(trainer.started, false);
});
```

Bad:

> Bugfix test

```ts
test('does not start trainer when frame list is empty', async () => {
  const result = await useCase.execute(emptyRequest);

  assert.equal(result.predictedRows, 0);
  assert.equal(trainer.started, false);
});
```

Regression comment should explain the production risk, and not refer to the fact of the existence of an old bugfix.

## Comments on expected value

A comment to expected value is needed if the value looks like a magic number, but is actually part of the contract.

Good:

> The expected row count of `51` follows from the warmup rules. With `lookback` set to 60 and `seqLen` set to 10, the first complete sequence appears after warmup.

```ts
test('creates rows only after sequence warmup is complete', () => {
  const rows = buildRows({ lookback: 60, seqLen: 10 });

  assert.equal(rows.length, 51);
});
```

Bad:

> Check rows length

```ts
test('creates rows only after sequence warmup is complete', () => {
  const rows = buildRows({ lookback: 60, seqLen: 10 });

  assert.equal(rows.length, 51);
});
```

If the expected value is obvious from the input data, no comment is needed.

## Comments on test fixtures

Fixture comment is needed if the test data looks strange, but was chosen intentionally.

Good:

> Zero volume is deliberate. Some historical candles arrive without trades, and price features still need to be computed from OHLC.

```ts
const candle = {
  open: 100,
  high: 101,
  low: 99,
  close: 100.5,
  volume: 0,
};
```

Bad:

> Test candle

```ts
const candle = {
  open: 100,
  high: 101,
  low: 99,
  close: 100.5,
  volume: 0,
};
```

The comment should explain the reason for the fixture, not its type.

## Comments on mock/stub/fake

Mock, stub or fake should only be commented if its behavior is intentionally different from real behavior and it is important to the boundaries of the test.

Good:

> The stub models an external provider error so the test can check its mapping in the application layer. Provider retries belong to a separate scenario.

```ts
const marketData = new FailingMarketDataStub();
```

Bad:

> Create mock

```ts
const marketData = new FailingMarketDataStub();
```

If fake is completely obvious from the class name and setup, no comment is needed.

## Comments to snapshot / golden tests

Snapshot or golden test should explain which contract is being recorded.

Good:

> The golden output pins the CLI response format. Shell scripts read `stdout`, so changing the order of fields is an explicit breaking change.

```ts
test('prints stable CLI summary', () => {
  const output = renderNetworkTestSummary(result);

  assert.equal(output, expectedOutput);
});
```

Bad:

> Compare output

```ts
test('prints stable CLI summary', () => {
  const output = renderNetworkTestSummary(result);

  assert.equal(output, expectedOutput);
});
```

Golden test without contract reason often fixes random formatting and complicates refactoring.

## Given / When / Then blocks

Comments `Given`, `When`, `Then` are only valid in long tests where they actually improve readability.

They are not a required style and should not appear in short tests.

Acceptable:

> Given. Python receives a positional matrix without column names, making indicator order part of the production contract.

```ts
test('preserves feature order from profile registry', () => {
  const profile = getMarketFeatureProfile('default');

  const names = profile.indicators.map(getIndicatorName);

  assert.deepEqual(names, [
    'CloseLocationValue',
    'SignedStreak',
    'VolRatio',
  ]);
});
```

Not necessary:

> Given · When · Then

```ts
test('returns true for valid FIGI', () => {
  const figi = 'BBG004730N88';

  const result = isFigi(figi);

  assert.equal(result, true);
});
```

For short tests, the structure should be obvious from the code itself.

## Comments on intentional omissions

If the test intentionally does not check adjacent responsibility, this can be indicated by a comment at the scenario level or next to the setup.

Good:

> This scenario checks normalization of network fit arguments.
>
> - Mapping `argv` to an application request.
> - Default runtime options.
>
> Use-case execution, the Python trainer, and file-system side effects have separate tests.

- `parseNetworkFitArgs`

Bad:

> Test the CLI.

- `parseNetworkFitArgs`

Intentional omission is useful where the test boundary may be incorrectly extended by future changes.

## Comments and test names

The comment should not compensate for a bad test name.

Bad:

> Check that the trainer stays idle when all ranges are skipped during warmup.

- `works correctly`

Good:

> The Python runtime starts lazily. The application layer calls it when training data is available.

- `does not start trainer when all ranges are skipped by warmup`

Even better if the comment is not needed:

```ts
test('does not start trainer when all ranges are skipped by warmup', async () => {
  const result = await useCase.execute(requestWithOnlySkippedRanges);

  assert.equal(result.predictedRows, 0);
  assert.equal(trainer.started, false);
});
```

## Commentary language

The natural text of comments in tests must be written in Russian, just like the production comments of the project.

It is acceptable to use technical English terms if they are part of a sustainable vocabulary project:

* regression;
* fixture;
* mock;
* stub;
* fake;
* snapshot;
* golden output;
* runtime;
* contract;
* mapping;
* fallback.

There is no need to artificially translate such terms if the translation makes the comment less accurate.

## Prohibited comments

Comments that:

* describe the temporary history of change without production meaning;
* contain TODO without reference to issue, decision or owner decision;
* justify fragile test instead of fixing test structure;
* mask too large test case.

Bad:

> TODO: improve test later

Bad:

> This test is complicated because the code is complicated

If a test requires such a comment, you first need to simplify the test setup or split the test case.
