Packages

A Gleam test runner for Erlang and Node.js with rich assertions, terminal and HTML coverage, and cross-target comparison.

Current section

Files

Jump to
penlight README.md
Raw

README.md

<p align="center">
  <img src="https://raw.githubusercontent.com/altenwald/penlight/main/assets/logo.png" alt="Penlight Logo" width="160">
</p>

# Penlight

**Run tests. Illuminate coverage.**

A Gleam test runner for Erlang/OTP and JavaScript on Node.js, with the same typed assertions, interactive terminal coverage explorer, and multipage HTML report on both targets.

## Installation

Once published to Hex, add Penlight as a development dependency:

```sh
gleam add --dev penlight
```

Until then, use a local checkout:

```toml
[dev_dependencies]
penlight = { path = "../penlight" }
```

Adding the dependency alone does **not** enable coverage. In your project's
`test/<package_name>_test.gleam`, replace the existing test runner's `main`
(for example, `gleeunit.main()`) with:

```gleam
import penlight

pub fn main() {
  penlight.main()
}
```

Now `gleam test` runs the suite through Penlight, prints terminal coverage and
writes `coverage/index.html`. It runs only the selected target; use `--compare`
to run both backends. For JavaScript, also enable source maps as shown below.

Write public, zero-argument functions ending in `_test` anywhere under `test/`:

```gleam
import penlight
import penlight/should

pub fn main() { penlight.main() }

pub fn greeting_test() {
  "Hello, Gleam!" |> should.contains("Gleam")
  should.close_to(0.1 +. 0.2, 0.3, 0.00001)
}
```

```sh
gleam test
# Or run directly, including in projects using another test entry point:
gleam run -m penlight
gleam run -m penlight -- --tui
gleam run -m penlight -- --filter greeting --min-coverage 80
gleam run -m penlight -- --timeout 3000 --html coverage/index.html --no-color
```

Open `coverage/index.html` in a browser. The overview links to one page per module with Gleam syntax highlighting, execution counts and an uncovered-lines filter. Test results are paginated at 100 tests per page. The interface follows Gleam HexDocs: pink header, white background, Karla and Ubuntu Mono.

Shared CSS, JavaScript, fonts and the other pages live in `coverage/index.html_files/`. Keep that folder beside the index when copying or sharing the report. A custom `--html path/report.html` creates `path/report.html_files/`. The index contains no source bodies; module pages load only the selected file. No CDN, external requests or web server is needed. Font licences are included with the report.

The terminal displays test timings, failure diagnostics, coverage bars and uncovered line numbers. `--tui` adds a paginated source browser: select a file number, then `n`/`p` for pages, `m` to toggle uncovered lines and `b` to return. `q` exits the file view or the explorer. `NO_COLOR` disables ANSI colors.

## Configure coverage for one or both targets

All three setups use Penlight as a development dependency and the same test
entry point in `test/<package_name>_test.gleam`:

```gleam
import penlight

pub fn main() {
  penlight.main()
}
```

Keep your public zero-argument `_test` functions in `test/`. The dependency
alone does not replace an existing runner such as `gleeunit.main()`.

### Erlang coverage only

Install Gleam 1.19+ and Erlang/OTP 29 (the verified OTP version). Set the default
target in the consumer project's `gleam.toml`, before any `[section]`:

```toml
target = "erlang"
```

```sh
gleam test
# Explicitly select Erlang regardless of the default target:
gleam test --target erlang
# Optional interactive coverage explorer:
gleam run --target erlang -m penlight -- --tui
```

No Node.js installation or JavaScript source maps are required. Each command
runs Erlang tests and produces Erlang line coverage in the terminal and
`coverage/index.html`.

### Node.js coverage only

Install Gleam 1.19+ and Node.js 22+. Configure the consumer project's
`gleam.toml` (merge these settings into existing sections if present):

```toml
target = "javascript"

[javascript]
runtime = "node"
source_maps = true
```

```sh
gleam test
# Explicitly select JavaScript regardless of the default target:
gleam test --target javascript
# Optional interactive coverage explorer:
gleam run --target javascript -m penlight -- --tui
```

Erlang is not required. Source maps must be enabled in the **consumer project**;
Penlight's own settings do not enable them for your code. They map coverage and
failure locations back to `.gleam` files. Each command writes terminal coverage
and `coverage/index.html` for Node.js.

### Coverage and comparison for both targets

Install Gleam 1.19+, Erlang/OTP 29 and Node.js 22+. Enable Node and source maps
in the consumer project's `gleam.toml`; either default target is valid:

```toml
target = "erlang"

[javascript]
runtime = "node"
source_maps = true
```

Tests and any foreign functions they use must compile for both targets. Keep
the same test entry point shown above, then run:

```sh
gleam run -m penlight -- --compare
# Optional interactive comparison explorer:
gleam run -m penlight -- --compare --tui
```

This runs the suite on Erlang and then Node.js and writes a combined report to
`coverage/index.html`, with both backends' test results, coverage and source-line
comparisons. Individual reports remain available through links in that report.
`gleam test` still runs **only one target**, even when both runtimes are installed;
the explicit `--compare` command selects the two-target workflow.

By default, subsequent runs replace the report at `coverage/index.html`. To
keep separate reports without comparing them, choose different output paths:

```sh
gleam run --target erlang -m penlight -- --html coverage/erlang.html
gleam run --target javascript -m penlight -- --html coverage/node.html
```

## JavaScript / Node.js

Use Gleam 1.19 or newer (tested with 1.19.2) and Node.js 22 or newer (tested with 26.12.1). Enable compiler source maps in the consumer project's `gleam.toml`:

```toml
target = "javascript"

[javascript]
runtime = "node"
source_maps = true
```

```sh
gleam test --target javascript
gleam run --target javascript -m penlight -- --tui
gleam run --target javascript -m penlight -- --filter greeting --min-coverage 80
```

All 34 `penlight/should` functions keep their Gleam signatures. Tests and assertions are unchanged between targets. The Node backend needs no Erlang runtime, npm packages, or JavaScript test framework. It uses Node's inspector coverage and the compiler's source maps. Missing maps are an explicit error with configuration instructions.

Each test runs in a fresh Node process and is terminated on timeout, including synchronous infinite loops. Timeout includes process startup and module loading. The runner also awaits a Promise returned by an external test function; `raises` and `raises_containing` assert synchronous exceptions.

V8 ranges are mapped to executable Gleam source lines. Imports, comments and generated function declarations do not count; unimported project modules and uncalled functions contribute uncovered lines. Multiple mapping points on the same line use their maximum count per test, then counts are summed across tests. A line is covered if at least one mapped point executes; this is not branch coverage. Compiler transformations mean exact totals can differ from OTP. Coverage from forcibly terminated processes cannot be collected; reports explicitly identify that partial counts are excluded.

Node and Erlang share report CSS, browser JavaScript, fonts and licences. The Node report is generated locally, with one page per module and 100 tests per results page. Error locations show the original `.gleam` test call site, including helper calls, with the expected/actual values and source snippet.

## Compare Erlang and Node with one command

```sh
gleam run -m penlight -- --compare
# Interactive comparison, or a filtered run:
gleam run -m penlight -- --compare --tui
gleam run -m penlight -- --compare --filter greeting --min-coverage 80
```

The same command also works when your project's default target is JavaScript.
Both runtimes must be installed, tests must compile for both targets, and the
project must enable `javascript.source_maps = true`.

Penlight executes Erlang and then Node with the same filter, timeout and coverage
threshold. A failing test or backend does not prevent the other backend from
running. The report at `coverage/index.html` compares:

- Passed, failed or missing tests, their durations and failure diagnostics.
- Coverage percentages with each backend's own executable-line denominator.
- Per-module and per-line counts in columns labelled OTP and Node.
- Covered/uncovered differences separately from instrumentation differences.
- Links to both complete backend reports, including their original diagnostics.

`0` means an instrumented line that was not executed. `—` means that backend did
not instrument the line. Different executable-line totals and call counts are
expected because the compilers transform code differently. Coverage and timing
differences alone do not fail a run. Test failures, missing tests, or either
backend missing the coverage threshold return status 1; compilation/runtime/report
errors return status 2. A successful pair returns 0. If sources change between
runs, that module's line comparison is disabled and explicitly marked.

The comparison TUI accepts a module number, `n`/`p` for pages, `d` to show only
coverage/instrumentation differences, `b` to return and `q` to leave.

Results are also saved under `coverage/index.html_files/`: `comparison.json`,
`erlang/results.json` and `javascript/results.json`. `--json path.json` exports
structured results for a single backend or the full combined result with
`--compare`. All report files must be kept together when sharing.

## Assertions

Import `penlight/should`. Arguments are **actual first, expected second**; assertions return `Nil`, except unwrap helpers.

| Group | Functions |
| --- | --- |
| Equality | `equal`, `not_equal` |
| Boolean / predicates | `is_true`, `is_false`, `satisfies`, `check`, `fail` |
| Results / options | `ok`, `error`, `some` (unwrap), `none` |
| Numbers | `greater_than`, `at_least`, `less_than`, `at_most`, `in_range`, `close_to` |
| Strings | `contains`, `not_contains`, `starts_with`, `ends_with`, `matches` (runtime regex) |
| Lists | `has_length`, `is_empty`, `is_not_empty`, `includes`, `excludes`, `all`, `any`, `same_members` |
| Dictionaries | `has_key`, `has_entry` |
| Exceptions | `raises`, `raises_containing` |

`same_members` ignores order but preserves multiplicity. Integer ranges are inclusive. `close_to` uses absolute tolerance and rejects a negative tolerance. Exceptions include Gleam panics/asserts and the target runtime’s exceptions. `matches` uses Erlang regexes on OTP and JavaScript Unicode regexes on Node; use their common syntax for portable patterns. Failing assertions display the Gleam test file and call-site line, the source expression, and distinct expected/actual values. Test calls preserve source locations across Erlang tail-call optimisation; internal Erlang stacks are omitted from the report. Native Gleam assertions and existing zero-argument gleeunit tests also work.

## Execution and coverage semantics

- Tests run sequentially in separate monitored Erlang processes or Node child processes, with a per-test timeout (default 5000 ms). A failure does not stop subsequent tests.
- Discovery uses source files under the current project's `test/` and exported `_test` functions. Framework-specific generators and fixtures are not interpreted.
- Coverage instruments only the current project's `src/**/*.gleam`, including modules not called by any test. Dependencies, tests and foreign implementations are excluded.
- OTP `cover` and mapped V8 coverage measure executable **lines**, not branch coverage. Non-executable lines do not enter the denominator. A module without executable lines reports 100%.
- Coverage retains compiler source annotations. Generated/inlined FFI wrappers may appear uncovered even when the underlying foreign function executes.
- Gleam 1.19 abstract artifacts are compiled with debug information for OTP instrumentation. Older BEAM artifact layouts have a fallback, but are not yet verified.
- Test output is streamed to the terminal. Child processes spawned by tests are the test author's responsibility; use cleanup for background work. This is process isolation, not a security sandbox.
- Exit status: **0** success, **1** test failure/timeout or unmet coverage threshold, **2** configuration, compilation, discovery or report error. An empty test selection is an error.
- HTML is generated even when tests fail or coverage misses the threshold. Report write errors fail the command.

## Develop

Verified with Gleam 1.19.2, Erlang/OTP 29 and Node.js 26.12.1.

```sh
gleam format --check
gleam build --warnings-as-errors
gleam test
python3 test/integration/run.py
gleam test --target javascript
PENLIGHT_TARGET=javascript python3 test/integration/run.py
python3 test/integration/node_coverage.py
python3 test/integration/compare.py
python3 test/integration/highlight.py
```

After changing the Erlang report's shared CSS, scripts or fonts, regenerate the Node asset module:

```sh
python3 scripts/export_report_assets.py
```

Integration checks create an independent consumer project and verify uncovered source lines, failed assertions, escaped HTML, syntax highlighting, shared assets, module isolation, pagination with 205 tests, custom paths, timeouts, coverage thresholds, invalid arguments, empty selections, and TUI navigation.

Penlight is an initial local release. It is not published to Hex. HTML styling and the TUI use only the runtime and standard library; the project has one Gleam dependency (`gleam_stdlib`).

## Preview a failed test

`examples/report_demo` contains two passing tests and one deliberately incorrect
expectation (25 instead of 30). It is separate from Penlight's own test suite.

```sh
cd examples/report_demo
gleam run -m penlight
# Or the same example on Node.js:
gleam run --target javascript -m penlight
```

The command exits with status 1 and generates `coverage/index.html`. Passed tests
are plain rows. Failed tests expose an expandable diagnostic, open by default.

`examples/compare_demo` intentionally chooses different discount policies in the
foreign backends. Run `gleam run -m penlight -- --compare` there to see a Node-only
failure and different covered branches, while the other tests pass on both.

## Coverage in GitHub Actions

The workflow in `.github/workflows/test.yml` runs on pushes to `main` or
`master`, pull requests, and manual runs via **Actions → test → Run workflow**.
A pull request is not required.

Each run compares Erlang and Node.js. Its **Summary** shows passing/failing tests,
line coverage for each target, and coverage by module.

**[Browse the coverage report and test results](https://altenwald.github.io/penlight/)**

Pushes and manual runs on `main` publish the report to GitHub Pages. The website
includes both targets, source highlighting, failure diagnostics, full test output,
the tested commit, and a link to the Actions run. No download or PR is required.
The site shows the latest deployed main run. Pull requests generate an Actions
summary but do not replace the public site.

Available reports are published even when tests fail. If setup fails before a
report can be generated, the previous site remains available; check its commit
and Actions link for freshness.

## Publishing

The first release is prepared as `0.1.0`. The configured source repository is
`https://github.com/altenwald/penlight`; ensure it exists and contains the release
sources and `assets/logo.png` on its `main` branch before publishing. The README
uses the hosted logo so it also renders on HexDocs. No release has been uploaded by these instructions.

```sh
gleam format --check
gleam build --warnings-as-errors
gleam test
gleam test --target javascript
gleam docs build
gleam export hex-tarball
# Review the archive, then authenticate with your Hex account and publish:
gleam publish
```

The exported archive is a local packaging check, not an upload. The release
requires Gleam 1.19+, Erlang/OTP 29 for the verified Erlang backend, and Node.js
22+ for JavaScript. Only the runtimes you run need to be installed.

## License

Copyright 2026 Manuel Rubio. Licensed under Apache-2.0; see [LICENSE](LICENSE).
Bundled Karla and Ubuntu fonts retain their own licences in `licences/`, also
included in generated reports.