Metadata-Version: 2.4
Name: testsuit
Version: 4.0.0
Summary: This toolbox helps preparing and analysing tests data, based on Pandas mainly.
Author: Laurent ML
License-Expression: AGPL-3.0-or-later
Project-URL: Homepage, https://github.com/laurentmldev/testsuit
Project-URL: Source, https://github.com/laurentmldev/testsuit
Project-URL: Issues, https://github.com/laurentmldev/testsuit/issues
Keywords: test data,hdf5,tdms,mdf,csv,data analysis,test campaign
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=2.2.6
Requires-Dist: pandas>=2.3.3
Requires-Dist: scipy>=1.10
Requires-Dist: psutil>=5.9
Requires-Dist: requests>=2.32.5
Requires-Dist: GitPython>=3.1
Requires-Dist: colorama>=0.4
Requires-Dist: h5py>=3.15
Requires-Dist: Unidecode>=1.4
Requires-Dist: pytest-html>=4.1
Requires-Dist: pytest-metadata>=3.1
Requires-Dist: matplotlib>=3.10
Requires-Dist: plotly>=5.24
Requires-Dist: pytest>=8
Requires-Dist: PyYAML>=6.0
Requires-Dist: ruamel.yaml>=0.18
Requires-Dist: Markdown>=3.5
Requires-Dist: python-dateutil>=2.8
Requires-Dist: pyarrow>=15
Requires-Dist: Jinja2>=3.1
Requires-Dist: pydantic>=2.5
Requires-Dist: influxdb-client>=1.40
Requires-Dist: influxdb3-python>=0.10
Requires-Dist: clickhouse-driver>=0.2
Requires-Dist: npTDMS>=1.10
Requires-Dist: asammdf>=8.7
Requires-Dist: boto3>=1.34
Requires-Dist: fastapi>=0.110
Requires-Dist: uvicorn>=0.29
Requires-Dist: httpx>=0.27
Requires-Dist: tomli>=2.0; python_version < "3.11"
Requires-Dist: PyJWT[crypto]>=2.8
Provides-Extra: dwdatareader
Requires-Dist: dwdatareader>=1.3; extra == "dwdatareader"
Provides-Extra: plotly
Provides-Extra: jupyter
Provides-Extra: file-formats
Provides-Extra: editor
Provides-Extra: test
Requires-Dist: testsuit[sequencer]; extra == "test"
Requires-Dist: moto>=5; extra == "test"
Provides-Extra: sequencer
Requires-Dist: asyncssh>=2.14; extra == "sequencer"
Requires-Dist: python-multipart>=0.0.9; extra == "sequencer"
Requires-Dist: jq>=1.6; extra == "sequencer"
Provides-Extra: dev
Requires-Dist: testsuit[test]; extra == "dev"
Requires-Dist: build>=1.3; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Dynamic: license-file

# testsuit

Toolbox for preparing and analysing test data: load measurement files (CSV, TDMS, MDF, Dewesoft DXD, UDBF, HDF5, InfluxDB, ClickHouse) into pandas, convert them to HDF5 or push them to a database, check results against YAML scenarios, and package test inputs into datapacks.

## Installation

Python 3.10 or newer is required.

```bash
git clone https://github.com/laurentmldev/testsuit.git
cd testsuit
python -m venv .venv && source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -e .
```

The plotly figures, the data file formats (InfluxDB, ClickHouse, TDMS, MDF) and the web UI (the `testsuit` command) come with
the default install. Optional features are installed as extras:

| Extra          | Adds                                                                 |
|----------------|----------------------------------------------------------------------|
| `dwdatareader` | DXD (Dewesoft) files                                                 |
| `sequencer`    | the test sequencer `tsq`/`tsqd` (the sequencer mode of the web UI)  |
| `test`         | what the test suite needs                                            |
| `dev`          | `test` plus build and lint tools                                     |

`plotly`, `file_formats`, `editor` and `jupyter` (the notebook GUIs, removed) still exist as empty extras, so older install commands keep working.

For example `pip install -e ".[sequencer,dwdatareader]"`.

The web UI is [the testsuit app](#the-testsuit-app): `testsuit`.

### Windows installer

For a Windows machine with no Python (or with another Python, or Anaconda, which it leaves alone): one
`testsuit-<version>-Windows-x86_64.exe` installs its own Python, testsuit and all its dependencies, offline, with
a **testsuit** shortcut in the Start menu and on the desktop that runs [the testsuit app](#the-testsuit-app)
(`testsuit`, as the Navigator tile below). Get it from the `conda` workflow (artifact `testsuit-<version>-Windows-x86_64.exe` of a run, the
installer itself, not zipped, on each
`v*` tag or by hand from the Actions tab). Windows 10 or later, 64-bit; no admin rights needed: it installs for the
current user in `%LOCALAPPDATA%\testsuit` by default, does not add itself to `PATH` nor register its Python as the
system's default, and is removed from Windows' *Installed apps*. An installer of a newer version installs over it
(uninstall the old one first, or pick another folder).

It also gives the user a `testsuit.toml` for a **personal local use**, `%APPDATA%\testsuit\testsuit.toml` (where
`testsuit` reads it): the exploit mode alone, its UI on `127.0.0.1:8650` and its workspaces for this machine only
(`exploit.remote = false`), no login, every other setting there commented out with its explanation (the
[sample](#the-testsuit-app)'s, [testsuit-local.toml](src/testsuit/app/samples/testsuit-local.toml)). A `testsuit.toml`
already there is kept, so an upgrade leaves the user's own settings alone; unticking *Create a testsuit
configuration...* in the installer skips it. The file is also left in the installation folder, as
`%LOCALAPPDATA%\testsuit\testsuit-local.toml`.

Plugins (entry points of the `testsuit.plugins` group) are installed with its own Python, from a terminal:

```bat
"%LOCALAPPDATA%\testsuit\python.exe" -m pip install <plugin, wheel or git URL>
```

The shortcut, and the `mxp`, `exploit_runner` and `tsqd` processes it starts, load them at each launch. Without installing it,
a plugin can also be declared in the `TESTSUIT_PLUGINS` user environment variable (`module` or `module:function`,
comma-separated), with its folder in `PYTHONPATH`. Installing a newer version of testsuit may remove the plugins
installed with pip: install them again after an upgrade.

It is built with [conda constructor](https://github.com/conda/constructor) from the conda package below
(recipe in [conda/installer/](conda/installer/construct.yaml)), on Windows:

```bash
conda install -n base constructor conda-standalone
cp LICENSE conda/installer/LICENSE.txt
TESTSUIT_VERSION=<version> TESTSUIT_CHANNEL=file:///C:/conda-channels/testsuit-conda-channel constructor conda/installer
```

### tsdata and its small Windows installer

`tsdata` is the Inspect and Extract tools of [the Tools tab](#the-tools-tab) on the command line, without the web
server or a `testsuit.toml`. It is part of every install of testsuit (`pip install testsuit`, the conda package, the
[Windows installer](#windows-installer)), and also has an installer of its own, much smaller. It runs the jobs of the
app: same loaders (CSV, HDF5, TDMS, MDF, Dewesoft, InfluxDB 3 and ClickHouse description files, and those of the
[plugins](#the-testsuit-app) found as the other commands do), same steps, same outputs.

```bat
tsdata fields  run12.csv lab\recordings                 REM the parameters: <input>::<parameter>, one per line
tsdata inspect run12.csv --match "Temp*"               REM a table: rows, gaps, rate, min, max, mean, std
tsdata inspect lab.influxdbV3.yml -p Speed --csv stats.csv
tsdata extract run12.csv lab\recordings -o out.h5      REM or out.csv; all the parameters unless -p / --match
tsdata extract run12.csv -o out.csv --from "2026-11-12 08:00" --to "2026-11-12 09:30" --step scale:1e-3 --step "downsample:method=bucket,period=1s"
```

`--match GLOB` and `--match-re REGEX` pick parameters by name (any case, repeatable), `--from`, `--to` and `--date-unit` give the time range, `--rename MATCH REPLACE` renames parameters with a regex, and
`--step` repeats the steps of the app in the order given: `toffset`, `voffset`, `scale`, `downsample` and
`lowpass` / `highpass` (Butterworth and Bessel need scipy, which the small installer leaves out; `moving-average` does
not). `tsdata --help` explains the files it reads, among them the **description files of the databases**
(`*.influxdbV3.yml` with `host`, `token`, `org`, `database`, `table`, `paramNamesKey`... and `*.clickhouse.yml` with
`host`, `database`, `table`, `user`, `password`...: `table` is a regex on the table names; a secret can be `env:<VARIABLE>` or `file:<path>`), and the CSV and HDF5
it accepts. The CSV it writes is the generic one the loaders read back: comma separated, a `Timestamps` column in
seconds since 1970, then a column per parameter, merged in time.

Instead of all the arguments, `-c FILE` reads the options from a YAML, JSON or TOML file (`inputs`, `match_re`, `from`, `to`,
`rename`, `step`, `output`, `overwrite`... the long option names, dashes or underscores). What the command line gives wins over the
file; relative paths are relative to the file; the keys a command does not use are ignored, so one file serves `fields`, `inspect`
and `extract`:

```yaml
inputs: [lab/run12.csv, lab/pressure.influxdbV3.yml]
match_re: ['Temp_(in|out)_\d+', Speed]
from: 2026-11-12 08:00:00
step: ["scale:1e-3", {type: downsample, method: bucket, period: 1s, aggregate: mean}]
output: run12.csv
```

`tsdata sample-config job.yml` writes a commented sample with every option; then `tsdata extract -c job.yml`. In the web app, the Database dialog and the parameter filter of Extract and Inspect show the same
matching rules in their contextual help.

While it runs, `tsdata` draws two lines on the console, in plain ASCII, rewritten in place (a line per parameter done
when the output is redirected; `-q` and `--no-progress` turn it off):

```
[===================>------------------------------]  38%  12/31 params  00:01:12  ETA 00:01:58
 writing lab.influxdbV3.yml::Speed_axle3  step 63%  out 48.2 MB  1 error
```

Exit status: 0 done, 1 failed, 2 wrong arguments, 3 done but some parameters failed (listed at the end), 130 stopped
(Ctrl+C: the parameters already written stay in an HDF5 file, a CSV file is not written).

**The small Windows installer**, `testsuit-data-<version>-Windows-x86_64.exe` (about 45 MB to download, 220 MB installed: the
`tsdata` command with its own Python and no web app, scipy or other database than InfluxDB 3 and ClickHouse). Get it from
the `lite-installer` workflow (artifact of a run, on each `v*` tag or by hand from the Actions tab). It installs per user in
`%LOCALAPPDATA%\Programs\testsuit-data` (no admin rights), can add the folder to the user's `PATH`, and is removed
from Windows' *Installed apps*. It leaves the full installer and any Python of the machine alone. If Windows still asks for an administrator or
blocks an unsigned `.exe` (SmartScreen, Smart App Control, an antivirus or a company policy: that comes from the system,
not from the installer), take the **portable zip** of the same run instead: `testsuit-data-<version>-Windows-x86_64-portable.zip`
needs no installation, so unzip it in any folder you can write to (your Documents, not `C:\Program Files`) and run
`testsuit-data\tsdata.cmd` there (its `python.exe` is the signed one of python.org). Plugins are installed
with its own Python: `"%LOCALAPPDATA%\Programs\testsuit-data\python.exe" -m pip install <plugin>`. It is built by
[installer/lite/build.sh](installer/lite/build.sh) (the embeddable Python of python.org, the libraries of
[requirements.txt](installer/lite/requirements.txt), Inno Setup), and the workflow installs it and runs every command
of `tsdata` on samples before keeping it.

### From Anaconda Navigator

Installed with conda, testsuit shows in Anaconda Navigator as the **testsuit** app (its tile runs [the testsuit app](#the-testsuit-app)). The package is not published to
any channel: it is installed from a local folder. Get that folder from the `conda` workflow (artifact
`testsuit-conda-channel` of a run, on each `v*` tag or by hand from the Actions tab: unzip it anywhere), or build it
yourself (recipe in [conda/](conda/meta.yaml)):

```bash
cd ui && npm ci && npm run build && cd ..
python -m build --sdist                    # dist/testsuit-<version>.tar.gz, with the web UI
TESTSUIT_VERSION=<version> TESTSUIT_SDIST=$PWD/dist/testsuit-<version>.tar.gz conda build conda -c conda-forge --output-folder testsuit-conda-channel
```

Unzip or build that folder somewhere it stays (`C:\conda-channels\testsuit-conda-channel` below), then install it
in either of two ways.

**In Navigator**: on the *Home* page, *Channels*, *Add*: `file:///C:/conda-channels/testsuit-conda-channel` (forward
slashes, also on Windows), and *Add* `conda-forge` too (the dependencies come from there); *Update channels*.
**testsuit** shows on *Home*: *Install*, then *Launch* (installing it also adds a **testsuit** shortcut to the
Start menu, which runs the same). To upgrade, unzip the new version into the same folder, then
*Update channels*: the tile offers the new version.

> **Tips for the Channels dialog.** There is no *Browse* button: the field takes a name or a URL only, so a plain
> path (`C:\...`) is refused as you type. Type or paste the folder as `file:///` (three slashes) followed by its path
> with forward slashes, then press **Enter**: Navigator checks that the folder exists, and only then enables
> *Update channels* (a tooltip says why when it refuses). The folder is the one holding `noarch\` (with
> `repodata.json` in it): a zip unzipped into a folder of its own often adds one level too many.
>
> **Anaconda installed by an administrator**: adding a channel needs no rights (it goes to your own
> `C:\Users\<you>\.condarc`), but the `base` environment (`C:\ProgramData\anaconda3`) cannot be written to. Create an
> environment of your own (*Environments*, *Create*: it goes to `C:\Users\<you>\.conda\envs`), select it in
> *Applications on* on the *Home* page, then *Install*. An administrator may also restrict the channels for everyone
> (`allowlist_channels` in the system `.condarc`): then only they can allow this one.

**In a terminal** on the environment Navigator shows (*Anaconda Prompt* on Windows), its dependencies from conda-forge:

```bash
conda install -c C:/conda-channels/testsuit-conda-channel -c conda-forge testsuit
```

then restart Navigator (or *Refresh* its *Home* page): **testsuit** is there, installed. The same command upgrades it
from a newer folder. Upgrade testsuit in that environment with conda, not `pip install -U`, which would leave conda
and Navigator on the old version.

*Launch* runs `testsuit`: with no `testsuit.toml`, the exploit mode on the folder opened last, or a folder picker the
first time; *Change folder…* in the top bar opens another one, and *Stop testsuit…* in its Configuration tab stops it
(launching it again while it runs only opens the browser on it). Plugins
(entry points of the `testsuit.plugins` group) must be installed in the same environment: `pip install` them from a
terminal on it (*Environments*, ▶, *Open Terminal* in Navigator); upgrading testsuit keeps them.

Navigator shows no console: when *Launch* seems to do nothing, open http://127.0.0.1:8650 (the server may be running
already), and read `testsuit\testsuit.log` in `%APPDATA%` (`~/.config/testsuit/testsuit.log` elsewhere), which
tells what each launch did: the configuration, the folder, the address, whether the browser opened.

## The testsuit app

`testsuit` starts the web UI: one server on one port (`127.0.0.1:8650` by default), with the tabs of the modes
turned on in `testsuit.toml`, and the underlying apps it needs:

| Mode | Tabs | What runs |
|---|---|---|
| `exploit` (default) | **Criteria** (only with the sequencer mode off: on, the criteria are edited on its **Datapacks** tab), **Exploit**, **Plot**, **Tools** (Extract, Inspect, Delete DB data, Grafana datasource) | the criteria editor, exploit_runner runs and their reports, data plotted or extracted by hand, on workspaces (folders) of this machine (in the testsuit process) |
| `sequencer` | **Runs**, **Datapacks**, **Infra** (and **Exploit** on the data of its runs, when the exploit mode is off) | `tsqd`, started by testsuit as a child process on `127.0.0.1:8640`, watched and restarted if it ends, stopped with testsuit; or a tsqd running elsewhere (`sequencer.url`) |

**Configuration** shows the versions (see below), every setting of `testsuit.toml` with where it comes from, the
state and log of tsqd (with *Restart tsqd*), its own settings (`tsq.yml`), the plugins of each process with their
version, and *Stop testsuit…*.

**Languages and color themes.** The UI is in English, French, Italian, Spanish, German or Catalan: each user
picks theirs from the flag in the top bar, kept in their browser (no user profile). Only the tool is translated, its
labels and contextual helps: what `testsuit.toml`, the lab and the test definitions name (titles, descriptions,
tags...) shows as written, the same in every language. The color theme is the lab's choice, `ui.theme` in
`testsuit.toml` (`blue`, `teal`, `forest`, `violet`, `copper` or `graphite`), the same for every user, each one in a
light and a dark variant following the system's setting.

**Versions.** They are on the Configuration tab, not in the top bar: the version of the app deployed with testsuit
(the `TESTSUIT_APP_VERSION` environment variable of the testsuit process, such as your lab's or product's release or
a container image tag; not set, the row says so), testsuit's own, the testsuit of tsqd when it differs (a tsqd
running elsewhere), the lab configuration in use (its tag or commit), and Python. `testsuit status` prints the app
version too. Each plugin shows its version: the one of the package installing it, else the `__version__` of its
module (or of its top package), for a module named in `TESTSUIT_PLUGINS` that is not installed.

```bash
testsuit                         # start (opens the browser); launched again, it opens the running one
testsuit --folder ~/tests        # the exploit mode on this folder (its default workspace)
testsuit status                  # running or not, its modes, the state of its tsqd (--json: all of it)
testsuit stop                    # stop it, and the tsqd it started
```

`testsuit.toml` is read from `--config`, else `$TESTSUIT_CONFIG`, else `./testsuit.toml`, else `testsuit.toml` in the
user's configuration folder (`%APPDATA%\testsuit` on Windows, `~/.config/testsuit` elsewhere). Without any: the exploit
mode alone, on the workspaces of the last launch (a folder picker the first time). Relative paths are relative to the file.

**A sample to start from**: [src/testsuit/app/samples/testsuit.toml](src/testsuit/app/samples/testsuit.toml), installed
with the package (`testsuit/app/samples/testsuit.toml` in its folder), has every section and setting, commented out
(`#key = value`, its default or an example) with a few lines of explanation each, and an example of every type of data
source and destination (InfluxDB 3, InfluxDB 2, ClickHouse, S3, Nextcloud), with the environment variables testsuit
reads. Copy it, then remove the `#` of the settings to set (and of their `[section]` line). Its variant
[testsuit-local.toml](src/testsuit/app/samples/testsuit-local.toml), for a personal local use (the exploit mode alone,
for this machine only), is the one the [Windows installer](#windows-installer) puts in place. A test keeps both in
step with the settings of the code.

```toml
modes = ["sequencer", "exploit"]   # default ["exploit"]
title = "Rail lab"                 # the title of the UI (top bar and browser tab); default "testsuit"
logo = "logo.svg"                  # an image before the title: a file, or an http(s) URL; default testsuit's icon

[ui]
listen = "127.0.0.1:8650"          # the one port of the UI and of every API behind it
browser = true                     # open the browser at the start
theme = "teal"                     # the color theme: blue (default), teal, forest, violet, copper, graphite
# base_path, public_url, trusted_proxies: behind a reverse proxy, see below

[ui.splash]                        # the splash screen at the opening of the UI, faded in and out (0.1 s)
enabled = true                     # shown once per login session with [auth], else once a day in a browser
duration = 1.0                     # seconds it stays; 0 turns it off
image = "splash.png"               # instead of the logo and title (40% of the width, Playfair Display): an image
                                   # file (png, svg...) or an http(s) URL

[ui.home]                          # the Home page: see "The Home page" below
enabled = true                     # default: on in the exploit mode alone, off with the sequencer
background = "home.svg"            # its background image (a file, or an http(s) URL), and the dark theme's
background_dark = "home-dark.svg"
label = "Production"               # a vertical text along the left edge, to tell the instances apart

[[ui.home.bullets]]                # its buttons (default: one for each top-level tab and each tool)
title = "Grafana"
url = "https://grafana.example.org"   # another app (a new browser tab), or a tab of the app: "Plot", "Tools/Extract"
color = "#a855f7"
icon = "chart"
roles = ["lab-viewer", "editor"]   # with [auth]: who sees it (OIDC roles or app roles); default everybody

[exploit]
folder = "~/tests"                 # the default workspace (default: the one of the last launch)
folders = ["~/bench-a", "~/bench-b"]   # more shared workspaces; others are added from the top bar (see Workspaces)
results = "~/exploit_results"      # where the exploit_runner runs of shared workspaces are kept (default <folder>/exploit_results)
remote = false                     # true: also for other machines, through a reverse proxy (see below)

[cache]                            # the file sources (S3, Nextcloud) downloaded: see "File sources" below
folder = "/data/testsuit-cache"    # default: the user's cache folder
reserve = "1GB"                    # free space a sync must leave

[sequencer]
config = "tsq.yml"                 # tsqd's configuration (default: $TSQ_CONFIG, then /etc/testsuit/tsq.yml)
listen = "127.0.0.1:8640"          # where the tsqd testsuit starts listens (keep it on 127.0.0.1)
restart = true                     # start tsqd again when it ends by itself
# url = "http://lab:8640"          # instead: a tsqd running elsewhere, used as it is (not started)
```

**The Home page.** With `[ui.home]` on (by default in the exploit mode alone, not with the sequencer), the UI
opens on a Home page, also reached by a click on the title of the top bar: the whole window, its background image
(`background`, and `background_dark` for the dark theme), the user menu at the top right (with `[auth]`: a click on
the name lists the app role, the OIDC roles, the sources and destinations, as in the top bar), an optional `label`
written vertically along the left edge ("Production", "Dev", in `label_color`), and big round buttons. Each
`[[ui.home.bullets]]` has a `title`, a `url`, a `color` (any CSS color; the text on it is black or white, whichever
reads better), an `icon` (a built-in one: `home runs datapacks lab exploit config criteria plot tools extract inspect
delete chart database file eye link book terminal gauge`, or an image URL; default the icon of the tab) and `roles`.
`url` is an http(s) URL, opened in a new browser tab, or a tab of the app by its path, by its label or key, in any
case: `Criteria`, `Plot`, `Infra`, `Configuration`, `Tools/Extract`, `Tools/Delete DB data`, `Exploit/Plot` (Plot and
Tools are subtabs of Exploit with the sequencer alone, top-level tabs with the exploit mode: either path works). A
button to a tab this app does not show is greyed out. `roles`: with login on, the OIDC roles, or the app roles
(`guest`, `editor`, `admin`: that role or a higher one), that see the button; the server sends only those of the
user's roles. Without buttons, one for each top-level tab and each tool of the app. With the Home page and the
sequencer, the Runs tab is `#/runs-home` (its Queue or All runs subtab, as before).

**Data sources and destinations.** The databases the **Extract** tool reads (*Database…*) and writes (*Output*) are
the ones declared here, by a stable name; there is no ad-hoc database form any more. A field given a value is fixed:
the page shows it read-only (a secret only as set) and the server uses it as declared, whatever the browser sends; a
field left blank (or not given) is filled in by the user. An entry with only its `type` is a database the user
describes wholly. A secret is given as `<field>_file`, a file of the host (relative to `testsuit.toml`), or as
`env:<VARIABLE>`; the Configuration tab lists only the names and types. tsqd, when testsuit starts it, reads the same
file (`$TESTSUIT_CONFIG`).

```toml
[sources.lab-influx]               # source types: influxdbV3, influxdbV2, clickhouse (and those of plugins)
type = "influxdbV3"
label = "Lab InfluxDB"             # shown in the page (default: the name)
host = "http://influx:8181"
token_file = "/run/secrets/influx_token"
org = "lab"
database = "bench"
table = ""                         # blank: the user fills it in (here a regex, empty meaning all tables)

[sources.any-clickhouse]
type = "clickhouse"                # everything left to the user (host, user, password, database, table)

[destinations.lab-clickhouse]      # destination types: influxdbV3, influxdbV2, clickhouse (the writers of data2db)
type = "clickhouse"
url = "clickhouse:9000"
user = "writer"
password_file = "secrets/clickhouse_writer"
database = "extracts"
# table: blank, the user names it
```

Fields: `influxdbV3` source `host, token, org, database, table`; `influxdbV2` source `host, token, org, bucket,
measurement`; `clickhouse` source `url, user, password, database, table`; `influxdbV3` destination `url, token,
database, table`; `influxdbV2` destination `url, token, org, database (bucket), table (measurement)`; `clickhouse`
destination `url, user, password, database, table, timestampColumn`. `roles` (with login on, see below): the OIDC
roles that may use the source or destination (see it, browse an S3 or Nextcloud one, plot or extract from it;
extracting also needs the editor app role); absent, everybody may. `roles_delete` (destinations only): the OIDC roles
that may delete its data with the **Delete DB data** tool (an empty list: whoever may use it; absent: nobody, the
destination is not offered for deletion). `[destinations.<name>.grafana]` (optional): what its Grafana datasources get
(see **Grafana datasource** below): `url` (how Grafana reaches the database; default: the destination's), `user` (a
read-only one; default: the destination's), `password` or `token` (`password_file`, `token_file`, `env:VAR`). A plugin
adds a type with `testsuit.datasources.register_source_type` / `register_destination_type` (kind `database` or
`files`).

### Workspaces

Both modes work on a list of workspaces, picked in the UI, each browser on its own:

- the **sequencer mode** (the **Datapacks** tab): tests repositories, those of `server.workspaces` in `tsq.yml`, and
  those added with *Add repository…* (cloned by git URL into `<storage.root>/workspaces`, listed in
  `<storage.root>/workspaces.yml`);
- the **exploit mode** (the folder button of the top bar, *Change workspace…* in the Criteria bar): folders of this
  machine, those of `exploit.folder` and `exploit.folders` in `testsuit.toml`, and those added from the UI (remembered
  in `exploit_workspaces.json` of the user's configuration folder). Each browser keeps the one it picked; the routes
  `/x/w/<id>/criteria/...` and `/x/w/<id>/exploit/...` are those of workspace `<id>`, `/x/criteria` and `/x/exploit`
  those of the default one (the shared workspace opened last, `--folder`, or `exploit.folder`).

A workspace is **shared** or **personal**:

| | Shared | Personal (login on only) |
|---|---|---|
| added by | an admin (anyone with login off), or the configuration files | an editor, for themselves |
| seen by | everybody | its owner and the admins (marked *personal · owner*); the editing sessions on it too |
| removed (and its files downloaded) by | an admin; not those of the configuration files | its owner or an admin |
| exploit_runner runs kept in | `exploit.results`, else `<folder>/exploit_results` | `<folder>/exploit_results` |

Without login there are no users, so every workspace is shared, as before. A personal workspace keeps its name
for itself: two workspaces never share a name, whoever owns them. Removing one takes it off the list: in the
exploit mode its folder is not touched; a tests repository added by URL is removed only once clean, with its clone.

### The Tools tab

The **Tools** tab (`#/tools/<tool>`; in the sequencer mode, the *Tools* subtab of **Exploit**) holds the tools turned
on in `testsuit.toml` (all by default):

```toml
[tools]
enabled = ["extract", "inspect", "delete", "grafana"]   # any of them, shown in this order
max_jobs = 2                                 # Extract and Inspect jobs running at once, the others queued
memory_reserve = "1GB"                       # memory kept free: a job waits before a parameter that would take it
```

Extract and Inspect jobs run in the server: at most `max_jobs` at once (per process: testsuit, and tsqd for its
Exploit tab), the others queued with their place shown, so that a few heavy extractions do not slow the server
down for everyone. Before loading a parameter, a job waits while it would leave less than `memory_reserve`
available (the machine's memory, or its container's limit: cgroup v2), and fails after 5 minutes, rather than
have the server killed.

- **Extract** writes parameters of data files or databases to HDF5, CSV or a database destination. Its *Range and
  names* keeps the min and max dates (on the times of the source, as stored, so that a database source applies them
  in its query; to the microsecond, the nanosecond for a database) and the renaming (a regex and its replacement),
  with the names as they will be written, on the parameters picked, the names given twice flagged. Its *Steps* are a
  chain applied in order to every parameter:
  - **Time offset**: by a value (seconds, a duration such as `2h30m`, or `now`), or by a **parameter**: its instant
    value is added to the times (a clock drift, as `apply_clock_correction` does; *inverted* subtracts it), on the
    times both cover;
  - **Vertical offset** (a value, or `autoz` / `autoz:<N>s`: the first value, or the mean of the first N seconds, set
    to 0) and **Scale**;
  - **Downsample**: `bucket` (a value per period: mean, median, min, max, first or last), `minmax` (the min and the
    max of each period, keeping the peaks for a plot) or `lttb` (Largest-Triangle-Three-Buckets, to a number of
    points);
  - **Low-pass** and **High-pass** filters: `butterworth` or `bessel` (order 1 to 8, a cutoff frequency in Hz),
    `moving-average` (a window); zero-phase (forward and backward) or causal. Each continuous segment is filtered
    apart (a gap longer than 5 times the median period splits them), and an irregularly sampled parameter is refused
    (downsample it with `bucket` first).

  An HDF5 output records what was done from the original data: its root has `ExtractedBy` (testsuit version, date,
  user), `ExtractInputs`, `ExtractRange`, `ExtractSteps` (the chain in order, with its parameters), `ExtractRename`
  and `ExtractDerived`; each dataset has `ExtractSource` (the parameter read, or the expression of a derived one),
  and those of `ExtractRange`, `ExtractSteps` and `ExtractRenamed` that apply to it.

  The server checks the chain as it is edited (a wrong value, or an order to reconsider, such as a filter after a
  downsampling). The former *date offset* and *vertical offset* modifiers are still read, as first steps.

  **Derived parameters** are computed from others: a name and an expression such as
  `sqrt(p("ax")**2 + p("ay")**2)`, where `p("<parameter>")` reads a parameter (`p("<source>::<name>")` to name its
  source; a name found in several sources gives a derived parameter per source) and `t` the times in seconds. They
  have the numbers, the operators, the comparisons, `& | ~`, `pi`, `e`, `nan`, `inf` and the functions `abs sqrt exp
  log log10 log2 sin cos tan arcsin arccos arctan arctan2 sinh cosh tanh hypot degrees radians floor ceil round sign
  minimum maximum clip where isnan isfinite mean median std min max diff integral`. The expression is parsed by the
  server and walked by its own evaluator (`testsuit.misc.safeexpr`): no attribute, subscript, import, keyword or any
  other Python, so a user cannot run code through it. A derived parameter is computed on the times of the first
  parameter it reads (the others interpolated), then goes through the steps.
- **Heavy inputs** (thousands of parameters, files of gigabytes): Extract and Inspect load one parameter at a
  time, so memory follows the largest parameter, not the input (10 HDF5 files of 1 GB and 500 parameters each:
  about 1 minute and 200 MB to HDF5). A parameter that fails (unreadable, or a step that does not fit it) is listed
  and the others go on; if the first 10 all fail, the job stops there (a cause common to all, such as a cutoff above
  half the sample rate). The progress shows the parameters done, the time spent and an estimate of what is left,
  the current step with how long it has lasted, and Stop turns into *Stopping…* until the current step ends. A CSV
  input is read in batches (its loader parses the whole file for any parameter); a CSV output is meant for modest
  volumes, prefer HDF5 for large ones.
- **Inspect** shows, for each parameter picked and the same steps, its rows, missing values, first and last times,
  period and rate, gaps (and the largest), min, max, mean and standard deviation, copied as CSV in one click. *Extract these…* opens Extract
  with the same inputs, parameters, derived parameters and dates.
- **Delete DB data** deletes data of a destination declaring `roles_delete`, for a user with one of those roles and
  the editor app role: it lists the databases, tables and parameters, and deletes the parameters ticked, a whole table
  or a whole database, within an optional time range (both bounds included, to the microsecond, the nanosecond where
  the database stores it). Dropping a database or a table (without a time range) needs the admin app role and its name
  typed again. What can be deleted depends on the database: ClickHouse everything (a column dropped, or its values in
  the range set to NULL and the rows left empty deleted); InfluxDB 2 a bucket, a measurement, or a measurement within
  a time range (its delete API cannot delete a single field); InfluxDB 3 a database or a table only (row deletes are
  not in its API). A database or table set in `testsuit.toml` cannot be dropped through another name. Every deletion
  is logged with its user.
- **Grafana datasource** (only with a `[grafana]` section) creates, for the editor app role, a Grafana datasource of a
  database of a destination (InfluxDB 2 and 3 through Grafana's InfluxDB plugin, ClickHouse through
  grafana-clickhouse-datasource), in an organization of `[grafana.orgs]` open to the user (its `roles`). Its name is
  `<project> - <title>`, with an optional ` - <YYYY_MM_DD>`: the projects, titles and dates already in the
  organization are offered (read from its datasource names), and a new project is confirmed. **One datasource per
  database**: its uid comes from what it reads (type, server as Grafana reaches it, database), and a datasource
  reading that database already in the organization (by that uid, or one made by hand) is shown with its link instead
  of creating another one. Grafana gets the read-only credential of `[destinations.<name>.grafana]`; without one, the
  destination's own when `testsuit.toml` declares it (a secret typed in the page is never given to Grafana), and the
  admins see a warning: it may write, and whoever edits dashboards of the organization can use it. **Extract** to a
  database offers *Create a Grafana datasource* (ticked by default): checked before the extraction starts, created
  once the data is written; its failure leaves the extraction done and says why. Every creation is logged.

```toml
[grafana]
url = "http://grafana.lab:3000"           # as testsuit reaches it; public_url: as the browsers do (the links)
user = "testsuit"                         # a Grafana server admin: datasources in any organization below...
password_file = "/run/secrets/grafana"
# token_file = "/run/secrets/grafana_sa"  # ...or, without user, a service account: its own organization only
[grafana.orgs.lab]                        # name (in Grafana; default: the key) or id, label, roles
name = "Lab"
roles = ["lab-data"]
```

**Picking files**: the folder picker of Plot, Extract and Exploit finds the files of a name pattern (`*toto.h5`, case
ignored) in the folders picked and all their subfolders, local or of an S3 or Nextcloud source, and adds them all
(at most 2000).

### Login and app roles

Off by default: without an `[auth]` section, nobody logs in and everything is open, as on a lab machine. With one,
testsuit logs the users in with an OpenID Connect provider (Keycloak, or any OIDC one), and every request, to the UI,
to the exploit mode or to tsqd, is checked on the server by the user's **app role**:

| App role | What it may do (each role may do what the ones above it may) |
|---|---|
| `guest` | see the runs, campaigns, the lab and the workspaces (read only); plot data, inspect it and check criteria (exploit_runner); read run files and reports in the browser. No data file (HDF5, CSV, TDMS, MDF..., archives), no download, no export, no extraction, no change |
| `editor` | edit the workspaces' files, commit and push, pull, revert; add and remove their own personal workspaces (see Workspaces); generate and post datapacks and campaigns, cancel, kill, retry; reviews and issues; extract, download data, reports and exports; delete parameters of a destination (with its `roles_delete`); create Grafana datasources (in the organizations of `[grafana.orgs]` open to them); probe the lab, put components on hold or in maintenance, run their commands by hand, self-test |
| `admin` | drop a database or a table (Delete DB data); add and remove shared workspaces (tests repositories, folders of the exploit mode), download their files, see every personal one; edit the lab (its Editor session, its layout), reload it; the Configuration tab's tsqd log and restart, stop testsuit, change the default exploit workspace |

```toml
[auth]
issuer = "https://sso.example.org/realms/LAB"   # its <issuer>/.well-known/openid-configuration is read
client_id = "testsuit"                          # a confidential client of the provider
client_secret_file = "/run/secrets/testsuit-oidc"   # a file of the host (or client_secret = "env:VAR")
# ca_file = "/etc/ssl/certs/company-ca.pem"     # the provider's CA, when not a public one (TLS is always checked)
# roles_claims = ["resource_access.testsuit.roles", "realm_access.roles"]   # the default: client, then realm roles
# audience = "testsuit"                         # what tokens' aud must hold (default: client_id)
# session_idle = "8h"                           # a session unused this long ends

[auth.roles]                                    # the OIDC roles giving each app role: the highest one matched wins
guest = ["lab-viewer"]
editor = ["lab-editor"]
admin = ["lab-admin"]

[sources.zoneL-influx]
type = "influxdbV3"
roles = ["zoneL-data"]                          # only users with this OIDC role see it, plot and extract from it
```

- **The login**: the testsuit server logs the user in itself (Authorization Code flow with PKCE) and keeps the tokens;
  the browser only gets an HttpOnly session cookie, so a script injected in a page cannot steal a token, and the
  downloads, the event stream and the plots work as before. The access token is refreshed on the server. Sessions
  live in memory: restarting testsuit logs everybody out. A user the provider knows but who has none of the mapped
  roles sees a "No access" page with their roles.
- **The user menu**, at the right of the top bar: the user's name and app role; a click shows the app role, the OIDC
  roles received (those that gave the app role highlighted), the data sources and destinations they may use, and
  *Log out*. What the role does not allow is greyed out, with the role it needs; the server refuses it anyway.
- **On the server, every route**: each route of testsuit, of the exploit mode and of tsqd has a rule (the lowest role
  allowed, `testsuit/auth/guard.py`); a route without one is refused to everybody. testsuit passes the user's access
  token on to tsqd, which checks it again itself: its signature against the provider's keys (fetched once, again for
  a new key), its issuer, audience and expiry; no call to the provider per request. So tsqd cannot be reached around
  testsuit, even when its port can be. A change made with the session cookie needs the `X-Testsuit: 1` header the UI
  sends (CSRF). Reviews and comments record the logged-in user.
- **Scripts and CI** (`tsq`, the GitLab runner) use a service account of the provider (a client with the client
  credentials grant, its service-account roles mapped like a person's): its access token in `$TSQ_TOKEN` (or the file
  `$TSQ_TOKEN_FILE`) for `tsq`, as `Authorization: Bearer` for any other client, to testsuit's `/seq/...` or to tsqd.
- **The exploit mode** still answers only this machine unless `exploit.remote`; with login on, `exploit.remote = true`
  is the way to open it to the other users, by role.

**Keycloak**: a confidential client `testsuit` with the standard flow only (no implicit flow, no direct access
grants), PKCE `S256`, the redirect URI `<public_url>/app/auth/callback` exactly (no wildcard), and an audience mapper
putting `testsuit` in the access tokens' `aud`; the app roles as client roles (`lab-viewer`, `lab-editor`,
`lab-admin`), the data roles apart (`zoneL-data`...), both given to groups. A realm to start from, with test users, is
[examples/keycloak/testsuit-realm.json](examples/keycloak/testsuit-realm.json). Without a Keycloak at hand,
`python tests/fake_oidc.py 8655` runs a fake provider (never in production: anybody logs in as anybody) for
`issuer = "http://127.0.0.1:8655"`, client secret `s3cret`.

**File sources: S3 and Nextcloud.** A source of type `s3` or `nextcloud` is a store of data files: the file pickers
of **Plot**, the **Tools** and the data of **Exploit** list it under *Top*, after the folders of the server. It opens
on its `root` and lists one folder at a time, when that folder is opened (one S3 `ListObjectsV2` with a delimiter,
one WebDAV `PROPFIND` of depth 1), so a bucket of millions of files is never listed whole. Adding a file, or a
folder (the data files directly in it, not its subfolders), downloads them into the cache folder of the server
first, with a progress bar; a file already there with the same size and ETag (else modification time) is not
downloaded again (*cached* in the picker). The pickers then hand over the local copy, read as any other file by
the data loaders. Downloads are written under a temporary name, renamed once complete, and locked per file: two
users (or testsuit and tsqd) picking the same file download it once, the second following the first one's progress.
A sync that would leave less than `cache.reserve` free in the cache folder is refused before downloading anything.
A cached file not used (synced, plotted, extracted, run on) within its source's `retention` (default `90d`) is
removed, at the start and then daily. All their fields are declared in `testsuit.toml` (nothing is asked to the
user); the browser only names the source.

```toml
[cache]
folder = "/data/testsuit-cache"    # default: ~/.cache/testsuit/sources (%LOCALAPPDATA%\testsuit\sources)
reserve = "2GB"                    # free space kept (default 1GB)

[sources.lab-s3]
type = "s3"
label = "Lab S3"
endpoint = "https://s3.lab.example.org"   # empty: AWS
region = "eu-west-1"
bucket = "recordings"
root = "campaigns/2026"            # the prefix the picker opens on (default: the whole bucket)
access_key_file = "/run/secrets/s3_access"
secret_key_file = "/run/secrets/s3_secret"
retention = "30d"                  # 90d by default; m, h, d or w

[sources.team-cloud]
type = "nextcloud"
url = "https://cloud.example.org"  # or a WebDAV folder URL (…/remote.php/dav/files/<user>)
root = "/Shared/recordings"
user_file = "secrets/nc_user"
password_file = "secrets/nc_app_password"
verify_tls = true                  # default true
```

Fields: `s3` `endpoint, region, bucket, root, access_key, secret_key, verify_tls, retention`; `nextcloud` `url, root,
user, password, verify_tls, retention`.

Behind the one port: the UI under `/ui/`, the app's own API under `/app/`, the exploit mode under `/x/`, the REST API
of tsqd under `/seq/` (passed through, its event stream included). tsqd itself listens on `127.0.0.1` only. The
exploit mode runs the user's own code and reads any file of the machine: it (and *Stop*) answers only requests made
on that machine, never one through a reverse proxy (`X-Forwarded-For`, `Forwarded` or `X-Real-IP`), unless
`exploit.remote`; other browsers get the sequencer's tabs only. With the exploit mode on too, its pickers also offer
the data of the sequencer's runs.

### Behind a reverse proxy

Only the one port of `ui.listen` is put behind the proxy (keep it on `127.0.0.1` when the proxy runs on the same
machine). The proxy brings TLS, and the authentication of the users when testsuit's own login is off (without
`[auth]`, testsuit has none; with it, give `ui.public_url`: the login comes back to `<public_url>/app/auth/callback`).
What to know:

- **Sub-path**: every URL the UI uses is relative, so it works under any sub-path. Either the proxy strips it (nginx
  `proxy_pass http://127.0.0.1:8650/;` with the trailing slash), and nothing is to set; or the proxy passes it on, and
  `ui.base_path` names it (`"/testsuit"`: testsuit then answers under `/testsuit/...`, and redirects anything else to
  `/testsuit/ui/`).
- **Live updates** are Server-Sent Events (`/seq/events`), no websocket: no `Upgrade` to pass on. The proxy must not
  buffer them: testsuit sends them with `X-Accel-Buffering: no` (nginx honours it); for others, turn buffering off
  for that path, and give it a read timeout above 15 s (tsqd sends a keep-alive every 15 s).
- **Uploads**: a datapack or campaign posted from the UI can be large: raise the proxy's limit (`client_max_body_size`
  of nginx, 1 MB by default).
- `ui.public_url`: the URL users open (`"https://lab.example.org/testsuit"`), which `testsuit` and `testsuit status`
  print and the Configuration tab shows.
- `ui.trusted_proxies`: the addresses of the proxies (`["127.0.0.1"]`) whose `X-Forwarded-For` and
  `X-Forwarded-Proto` testsuit believes (the client's address and `https` in its logs and redirects).
- `exploit.remote = true`: the exploit mode (and *Stop*) for the users of the proxy too, not only on the machine
  itself. It runs code as the user testsuit runs as, on that machine: only behind a proxy that authenticates them.
- **The `tsq` command line** reaches tsqd through the same URL: `tsq --server https://lab.example.org/testsuit/seq`
  (with the credentials the proxy asks, in the URL or a `.netrc`; with testsuit's login on, an access token in
  `$TSQ_TOKEN`).

nginx, the proxy passing the sub-path on:

```nginx
location /testsuit/ {
    proxy_pass http://127.0.0.1:8650;          # no trailing slash: /testsuit/... reaches testsuit as is
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_read_timeout 1h;                     # event streams stay open
    client_max_body_size 2g;                   # datapacks posted from the UI
    auth_basic "testsuit";                     # or your SSO; or nothing, with testsuit's own login ([auth])
    auth_basic_user_file /etc/nginx/testsuit.htpasswd;
}
```

```toml
[ui]
listen = "127.0.0.1:8650"
browser = false
base_path = "/testsuit"
public_url = "https://lab.example.org/testsuit"
trusted_proxies = ["127.0.0.1"]
```

Apache (`mod_proxy_http`): `ProxyPass /testsuit/ http://127.0.0.1:8650/testsuit/ flushpackets=on` and
`ProxyPassReverse` alike, `RequestHeader set X-Forwarded-Proto https`, with the same `testsuit.toml`. To serve it at the
root of a host instead, leave `base_path` out and proxy `/` to `http://127.0.0.1:8650/`.

What each launch did is in `testsuit.log`, and what tsqd printed in `tsqd.log`, both in the user's configuration
folder: read them when a launch from a shortcut, which shows no console, seems to do nothing.

On Linux, `testsuit` (and `tsq view`) open the browser with the desktop's own openers (`$BROWSER`, `xdg-open`,
`gio open`, then the usual browsers), run without the conda environment's folders on their `PATH`: the `gio` of a
conda environment has no handler for web pages (it printed `gio: <url>: Operation not supported` and no browser
opened). What the openers print goes to the log; when none opens a browser, the command says to open the address by
hand.

To use testsuit without cloning it, install straight from GitHub (add `@<tag>` to pin a version):

```bash
pip install "testsuit @ git+https://github.com/laurentmldev/testsuit.git"
```

## Loading data in Python

The data loaders (the file managers of `testsuit.datatools.DataFileMgrs`) give the parameters of a data file as
pandas objects indexed by dates in seconds since epoch, for a script or a notebook of your own. `FolderParamMgr`
opens a file of any format (HDF5, CSV, TDMS, MDF, DXD, UDBF, the formats of plugins...), a folder of them (read as a
whole) or a list of those:

```python
import pandas as pd
from testsuit.datatools.DataFileMgrs.FolderParamMgr import FolderParamMgr
from testsuit.misc.MonitorProgress import MonitorProgress

mgr = FolderParamMgr("recording.h5")
print(mgr.getFieldNames())                     # the parameters found, as "<file>::<parameter>"
params = mgr.findParams("Motor.*Temp", monitorProgress=MonitorProgress(name="load"))  # a regex of the parameters
df = pd.concat(params, axis=1)                 # one DataFrame, a column per parameter
df.index = pd.to_datetime(df.index, unit="s")  # optional: datetimes instead of seconds
```

`testsuit.datatools.datatoolbox.loadDataframeFromFile("recording.h5", "Motor.*Temp")` does the same in one call (and
merges a parameter found in several files of a folder). To plot data by hand, use the Plot page of
[the testsuit app](#the-testsuit-app).

## Plots

Figures (the Plot page, mexploit `plot*` checks, sequence timelines) are drawn by a plot backend:

| Backend | mexploit / exploit_runner report |
|---|---|
| `plotly` (default) | interactive figure (zoom, hover, 3D rotation), or `svg`/`png` with kaleido |
| `matplotlib` | SVG (`figure_format: png` also works) |

Pick it per check with `rendering_engine: matplotlib` in the scenario YAML, per run with `mxp --plot-backend matplotlib` / `exploit_runner --plot-backend matplotlib` (or the `PLOT_RENDERING_BACKEND` environment variable). The Plot page always draws with plotly. The figure format works the same way: `figure_format`, `--figure-format`, `PLOT_FIGURE_FORMAT`.

The exploit_runner HTML report stays a single file that works offline with plotly figures: they are stored as gzipped plotly JSON and drawn by plotly.js, which the report then embeds once (about 2 MB). Reports made with matplotlib only don't embed it. In mxp's own `pytest_report.html`, each plotly figure is drawn in a frame by a page of `pytest_report_files/`, which shares one copy of plotly.js. Another library can add its own backend with `testsuit.datatools.plotBackends.register_plot_backend()`.

## Writing criteria

The checks run on test results are mexploit scenarios: YAML files of entries, each running a criterion (a `crit_*` function, built in or from a plugin) with its fields. Each criterion declares its fields (a Pydantic model), so the tools know what a scenario may contain:

| Tool | What it does |
|---|---|
| `mxp describe` | every criterion a scenario can use, with its help and the JSON Schema of its fields; the helpers of expressions |
| `mxp lint` | checks a scenario without running it: fields, expressions, computed parameters, parameter names against data (`--auto`: with the keys of its test definition) |
| `mxp utest` | unit tests of a scenario: small data cases (`criteria_utests/<scenario>/utests.yml`), each with the status every check must give, and the coverage of each check |
| `testsuit` | [the testsuit app](#the-testsuit-app), its exploit mode (on a folder: `--folder`, `exploit.folder`, else the folder opened last; *Change folder…* opens another one): the criteria editor in the browser: completion of the criteria, fields, helpers, parameters and keys, problems as you type, the unit tests with their matrix and coverage, the data of the cases as tables and plots; **Exploit**, which runs exploit_runner on scenarios, dictionaries, keys set by hand and data picked in the page; and **Plot**, to plot the parameters of data files by hand (2D or 3D, a style per trace, exports to PNG, HTML and CSV); and **Tools**: Extract, to write parameters of data files or databases to HDF5, CSV or a database (InfluxDB, ClickHouse), through a chain of offsets, downsampling and filters, with derived parameters; Inspect, their statistics; Delete DB data; Grafana datasource, a datasource of a database in Grafana. Also in its sequencer mode (criteria on the Datapacks tab, and, with the exploit mode off, an Exploit tab with its subtabs Criteria (exploit_runner), Plot and Tools, on the data of its runs). |
| `mxp vscode` | sets up VSCode with no extension of its own: schemas for completion and validation, unit tests in the Testing view, tasks for lint (Problems view), utest and edit |

Scenarios are Jinja templates rendered before they run: a value can be a key of the test's dictionaries (`max: "{{ train.speed_limit_mps }}"`), a shared part can be included (`{% include "limits.inc.yml" %}`), and a loop can apply the same checks to several parameters (`{% for p in train.monitored %}`). The tools above render them too, and report each problem on the line where it is written ([examples](src/testsuit/exploit/README.md#templating-with-jinja-keys-includes-and-loops)).

An unknown field in a scenario is a warning when it runs, in its log and in the exploit_runner report; it will be an error in a next version. The [exploit README](src/testsuit/exploit/README.md#writing-scenarios-describe-lint-and-unit-tests) tells more, and [examples/toytrain](examples/toytrain) has unit tests for its criteria, every check covered.

## Datapacks

The `datapack` command builds the input files of every slot of a test setup and packs them in a zip. A test definition names a setup and its configuration; the setup declares data repositories (datasets imported by importers such as `git`), slot classes with their input files, and configurations listing the slots (each bound at run time to a lab component by the test sequencer):

```yaml
# testdef.yml
id: toytrain_max_speed
name: Max speed
setup_file: ../../setup/toytrain_setup.yml
setup_config: sim_bench
dictionaries: [scenario.yml]
```

Input files are Jinja2 templates (`{{ train.speed_limit_mps }}`, `{% include "x" %}`, loops, filters) rendered with keys from YAML dictionaries: setup dictionaries first, then imported datasets, then test definition dictionaries, each overriding the previous ones. A key can reference other keys (`output_dir: "{{ testdef.path }}/../datapacks"`), and an undefined key is an error. The zip follows the BagIt layout: `data/<slot>/input/` holds the generated files, `datapack.yml` records what they were built from and which keys each file used, and `context.yml` holds every resolved key, so a datapack can be used without its dictionaries. `datapack --setup-config <name>` uses another configuration of the setup than the test definition's, for example to build the same test for another platform. `datapack --verify <zip>` checks its checksums. A **campaign** file (`<name>.campaign.yml`) lists test definitions to generate with the same version of every dataset and to run together: `datapack <name>.campaign.yml` builds all their datapacks, and the sequencer runs them as one campaign run with a synthetic report. Test definitions and checks can list the **requirements** they verify (`reqs`), from a YAML file of the tests repository or any requirements tool through a plugin: `reqs matrix` builds the coverage matrices of tests, results and campaigns, and `reqs uncovered` lists what no test covers ([sequencer README, section 10.3](src/testsuit/sequencer/README.md#103-requirements-coverage)). `examples/toytrain/datapack` is a complete example. To have an AI write a test definition from a test specification, give it [docs/ai/testdef_prompt.txt](docs/ai/testdef_prompt.txt) followed by the specification, the lab roles and, when there is one, the setup to reuse (the prompt lists its inputs). The [datapack README](src/testsuit/datatools/datapack/README.md) gives the usage, the file formats and the architecture.

## Repository layout

```
ui/                     the web UI (React, TypeScript): npm run build writes it into src/testsuit/app/ui
src/testsuit/           the installable package
  datatools/            load data files into pandas, convert to HDF5, push to a DB
    plotBackends/       matplotlib and plotly drawing of plotHelpers' figures
    DataFileMgrs/       one reader per file format (Csv, Tdms, Mdf, Dxd, Udbf, H5, InfluxDb, Clickhouse)
    datapack/           datapack generation: YAML dictionaries, Jinja2 templates, BagIt zip
  reqs/                 requirements coverage: sources and their backends (plugins), links, snapshots, matrices
  exploit/              checks of recorded data, see its README
    mexploit/           YAML scenario checks (corridors, sequences, computed params, plots) run through pytest
    runner/             runs mexploit over test sessions and builds HTML reports
  app/                  the testsuit app: testsuit command, testsuit.toml, its server (one port, the web UI built from ui/), the tsqd it starts
  sequencer/            test sequencer: tsqd daemon, REST API, run engine, Editor (tsq command line in cli/)
  misc/                 logging, progress reporting, file helpers
  cli/                  command-line tools (see below)
docs/diagrams/          PlantUML figures of the READMEs (sources and rendered SVG)
docs/ai/                prompts for AI tools: testdef_prompt.txt writes a test definition from a specification
examples/toytrain/      the example project: a toy train's test environment (library extending testsuit, sequencer configuration)
tests/                  pytest suite (*_t.py)
  etc/                  input data, scenarios and configs used by the tests
  ref/                  reference outputs the tests compare against
```

## Command-line tools

Installing the package puts these commands on your `PATH`. Each prints its full usage with `--help`, for example `data2h5 --help`. They can also be run as `python -m testsuit.cli.<name>`.

| Command                  | Purpose                                                           |
|--------------------------|-------------------------------------------------------------------|
| `data2h5`                | extract parameters from data files or folders into an HDF5 file   |
| `data2db`                | push parameters from data files into a database (InfluxDB, ClickHouse); also the Extract tool of the app, which writes HDF5, CSV or a database |
| `extract_data_any`       | decode raw bit fields into parameters from a JSON/YAML config (example: `examples/config_extract_data_any.json`) |
| `extract_data_flags`     | extract flag values described in a YAML file                      |
| `apply_clock_correction` | shift timestamps of a folder of data files                        |
| `testsuit`               | [the testsuit app](#the-testsuit-app): the web UI, with its exploit and sequencer modes (`testsuit status`, `testsuit stop`) |
| `mxp`                    | run a mexploit scenario folder against data folders; `mxp describe`, `mxp lint`, `mxp utest`, `mxp vscode` help to write and test scenarios ([Writing criteria](#writing-criteria)) |
| `exploit_runner`         | run mexploit over whole test sessions from a YAML config          |
| `tsdata`                 | [Inspect and Extract](#tsdata-and-its-small-windows-installer) of the app, from the command line: parameters of files and databases, statistics, HDF5 or CSV output |
| `datapack`               | generate a datapack from a test definition file                   |
| `reqs`                   | requirements coverage: browse the requirements sources, coverage matrices of tests, results and campaigns, uncovered requirements |
| `tsq`                    | test sequencer client: submit datapacks, follow runs, manage the lab (`pip install "testsuit[sequencer]"`) |
| `tsqd`                   | test sequencer daemon: queue, lab locks, runs, REST API (its web UI: the sequencer mode of `testsuit`, which starts it) ([sequencer README](src/testsuit/sequencer/README.md)) |
| `evalfile`               | render a Jinja2 template file with keys from YAML dictionaries    |

**HDF5 files written** (`data2h5`, `apply_clock_correction`, `extract_data_any`, `extract_data_flags`, the
Extract of the Exploit pages): each parameter is a dataset of its group, whose `TimestampRef` attribute names its
timestamp (index) dataset. The parameters of a group whose timestamps are exactly the same (same values, same type)
share one timestamp dataset; a timestamp that differs gets its own (`<name>`, else `<name>_2`, `_3`…). The comparison
hashes and reads the data by chunks, so it holds for files of several GB. Appending rows to a parameter keeps it on a
shared timestamp only while its other parameters get the same rows. The group keeps the list of its timestamp
datasets (`IndexDatasets`) and each timestamp dataset its user count and hash (`IndexUsers`, `IndexDigest`).

**Secrets.** Wherever a password or a token is given (the `token` of an InfluxDB config file, the `password` of a ClickHouse one, `data2db --token`, the credentials of a requirements source), it can be a reference rather than the secret itself: `env:<VARIABLE>` reads an environment variable, and `file:<path>` the content of a file, such as a Docker or Kubernetes secret (`token: file:/run/secrets/influx_token`; trailing white space dropped; a relative path is relative to the config file, or to the current folder on the command line). The sources file of the requirements accepts references only.

## Using the library

```python
from testsuit.datatools.datatoolbox import loadDataframeFromFile
from testsuit.exploit.mexploit.mexploit import mexploit

# run the checks of a scenario folder on a data folder, results written to out/
dfs = loadDataframeFromFile("tests/etc/data/csv/flags.csv", ".*")  # one DataFrame per parameter

rc = mexploit("tests/etc/mexploit/scenarii/mxp_OK_main_functions", "tests/etc/data", "out/", force=True)
```

The scenarios under `tests/etc/mexploit/scenarii/` are working examples of every check type. The [exploit README](src/testsuit/exploit/README.md) gives the usage of `mxp` and `exploit_runner`, the scenario and configuration formats, and the architecture.

## Running the tests

```bash
pip install -e ".[dev]"
pytest          # runs tests/*_t.py
ruff check .    # catches runtime errors such as undefined names
```

CI (`.github/workflows/tests.yml`) runs the same lint, the tests on Python 3.10 and 3.12, and a package build, on every pull request.

See [CONTRIBUTING.md](CONTRIBUTING.md) for how to add a file format, a mexploit check or a script, and how another library can register its own formats, criteria and report logo.

## License

Copyright (C) 2026 Laurent Millet-Lacombe.

testsuit is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See [LICENSE](LICENSE) for the full text.

The AGPL also covers network use: if you run a modified tsqd for other people, you must offer them its source code. The web UI links to the source from its top bar; point that link at your own copy if you change the code.

Every source file starts with the license notice (see [CONTRIBUTING.md](CONTRIBUTING.md#license-notice)). The vendored libraries under `src/testsuit/exploit/runner/report_libs/` keep their own licenses.
