# Testing

Marginalia's tests are integration tests first: most of them start the real Spring XML configuration against a
throwaway SQLite database and talk to a fake OpenAI-compatible server. They need no network, no model and no API key,
and they run in CI on every push and pull request. This page explains the test infrastructure and how to add tests.

The tests are in two modules, split like the classes. The platform's own tests and its test base (`PlatformTestBase`,
the fake LLM, the CRUD contracts) are in `marginalia/platform/src/test/java/com/github/enerccio/marginalia/`, run on the
platform alone and are published as the platform's test-jar ([below](#the-platform-s-tests-and-the-test-jar)); the
tests of Marginalia are in `marginalia/src/test/java/com/github/enerccio/marginalia/`. The packages are the same in
both, so paths below are relative to either.

## Running the tests

From `marginalia/`:

```sh
mvn test                                     # all tests
mvn test -Dtest=LorebookActivationTest       # one class
mvn test -Dtest='Backup*Test'                # a pattern
mvn test -Dtest='MacroRenderingTest#name'    # one method
```

Surefire is configured in `pom.xml` with:

| Setting | Why |
|---|---|
| `-XX:+EnableDynamicAgentLoading -Djdk.attach.allowAttachSelf=true` | `RuntimeInstrumentationTest` installs the ByteBuddy agent (the fallback of development runs) into the test JVM. |
| `marginalia.test.woven=true` | Tells `BuildTimeWeaverTest` that the classes under test went through the `weave-extendable` step of the build, so it checks that every `@Extendable` class of the application is woven (skipped in an IDE run). |
| `marginalia.test.home=target/test-home` | Folder for the test databases (see [The application folder](#the-application-folder)). |
| `marginalia.staleSaves=${test.staleSaves}` (default `fail`) | A save of an entity from a copy read before the last save of its row (a stale save, `StaleSaves`) fails the test with `StaleSaveException` instead of only being logged; `-Dtest.staleSaves=log` only logs it. A test that saves a stale copy on purpose sets `StaleSaves.setMode(LOG)` around it and `setMode(null)` after. See [Extended attributes](plugins/extended-attributes.md). |
| `forkCount=${test.forks}` (default 3), `reuseForks=true` | The test classes are spread over that many JVMs, one class at a time in each. Every JVM has its own Spring context and so its own database: SQLite lets one writer in at a time, and the `@Configurable` aspect (the `@Autowired` fields of the UI classes) is one for the JVM and bound to one Spring context, so threads of one JVM with a context each do not work. `-Dtest.forks=1` runs the classes one after another (times below). |

The platform's POM (`marginalia/platform/pom.xml`) configures its tests the same way, with 2 forks by default and
`logback.configurationFile` pointing to its test logging ([The platform's tests](#the-platform-s-tests-and-the-test-jar)).

How long `mvn test` takes (about 3,000 tests in the first two rows), with the machine, as the time depends on it. Add a row for yours: the
`Total time` line of Maven, once with `-Dtest.forks=1` and once as it is. Each fork has a heap of `-Xmx1g` (`test.heap` in the pom; `-Dtest.heap=-Xmx3g` for a test that needs more): the JVM default is a quarter of the RAM, which three forks and the Maven JVM filled on a 16 GB machine.

| Machine | `-Dtest.forks=1` | 3 JVMs (default) | Memory of the 3 JVMs |
|---|---|---|---|
| Intel Core i7-10700K (8 cores, 16 threads), 32 GB RAM, NVMe SSD (btrfs on LUKS), Linux, JDK 26 | 19 min | 7 min | 6.5 GB peak |
| Apple M4 (10 cores), 16 GB RAM, internal SSD, macOS, JDK 26 | 2 min 20 s | 1 min 27 s | 1.8 GB peak |
| Apple M4 (10 cores), 16 GB RAM, macOS, JDK 26, 4,651 tests, IntelliJ and a browser open (2026-11-09) | not measured | 7 min 41 s with the heap capped at 1.5 GB per JVM (`-Xmx1536m`); 10 min with no cap | a JVM without a cap went to about 4.5 GB each (four with Maven), with the cap about 1.5 GB each |

After a `mvn install` or `mvn package` that compiled with plain javac, `mvn test` may skip the AspectJ compile of the classes that did not change and leave them unwoven: a `@Configurable` class (a command, a UI class, an anonymous subclass in a test such as `SearchReplaceCommandsTest`) then has `null` in its `@Autowired` fields. `touch` the source of the failing test, or build with `clean`; it is not a bug of the code.

A class can run after any other in its JVM, and the classes of a JVM share its database, so a test must not count on what the database holds (see [The shared database](#the-shared-database)): create data with `uniqueName` and compare with what was there before.

Reports are written to `target/surefire-reports/`; the CI job uploads them as an artifact when a test fails.

### In the IDE

Tests run from IntelliJ IDEA like any JUnit test, with two conditions:

- the classes must be compiled with AspectJ (see [Building from source](building.md#aspectj-weaving)), otherwise
  UI classes and `@Configurable` beans miss their dependencies;
- add `-XX:+EnableDynamicAgentLoading -Djdk.attach.allowAttachSelf=true` to the VM options of the JUnit run
  configuration template if you run `RuntimeInstrumentationTest`.

Without `marginalia.test.home` the tests fall back to `target/test-home` relative to the working directory, so run
them with `marginalia/` as the working directory (IntelliJ's default for the module).

## Libraries

| Library | Used for |
|---|---|
| JUnit Jupiter 6 | Test engine, `@Test`, `@BeforeEach`, `@TempDir`... |
| AssertJ | All assertions (`assertThat(...)`) - use it instead of JUnit's `Assertions`. |
| Spring Test | `@SpringJUnitWebConfig`, context caching, `@DirtiesContext`. |
| JDK `HttpServer` | The fake LLM server (`test/llm/MockLLMServer`). |

There is no mocking library. Services are tested through the real Spring beans and the real database; the only
fake is the model server.

## What is covered

| Package | Tests | What they check |
|---|---|---|
| `test` | `TestBaseSmokeTest` | The test infrastructure itself: isolated folder, session user, mock LLM wiring. |
| `test/llm` | `MockLLMServerTest` | The fake OpenAI server against the real `openai-java` client. |
| `statistics` | `ManuscriptStatisticServiceTest`, `WordCountingTest`, `PartDeleteCountingTest`, `TokenCountingTest`, `AgentStatisticsTest`, `ActivityTrackerTest`, `TimeUnionTest`, `GenerationTimeTest`, `ManuscriptSizeTest`, `SizeSeriesTest`, `BookDataStatisticsTest`, `StatisticRangeTest`, `StatisticChartsTest`, `StatisticReportServiceTest`, `StatisticsPolicyTest`, `StatisticsBackfillMigrationTest`, `StatisticsReconstructionTest`, `WritingActivityTest` | The [writing statistics](domain-model.md#writing-statistics-manuscriptstatistic-activityinterval-manuscriptsize): what is counted where (the versions of a part, the deletes, the tokens of a request, the agents' side), the stretches of time and their union (the tracker with a fake clock, a generation, the linger, a suspended computer), the size of a book and its growth, that clones, imports and restores count nothing, the report, the rebuilt history (one test per rule, and the migration on a database), the configurations of the charts, the days worked on, the streaks and the goal, and the privacy controls (both switches and the retention, that the writers drop what they would record, pruning with the size row that stays, clearing a user and everybody, the administrator only). |
| `crud` | `*CrudTest` (`ExtensionAICrudTest` for the AI of an extension), `OwnedCrudContract`, `ExtendableCrudContract` | Create, update, soft and hard delete, owner isolation and extended attributes of every entity. |
| `db` | `FlywayMigrationTest`, `ConcurrentTransactionsTest`, `FulltextMigrationTest`, `OriginalResponseMigrationTest`, `PermissionsMigrationTest`, `DatabaseRestoreCheckTest`, `PreMigrationBackupTest` | Migrations on an empty, a V1 and a pre-Flyway database, followed by Hibernate schema validation (`FlywayMigrationTest` also checks that V9 keeps `manuscripts.description` in `extendedContent` and that the `V13` rebuild of `usages` keeps the rows, defaults and indexes of a V12 database); `FulltextMigrationTest` runs the app migration that fills `_fulltext` of existing rows on the Spring context, `OriginalResponseMigrationTest` the one that copies `response` into `originalResponse` (deleted parts too, `modification` kept); the check of a database before a restore and the fall back to the previous database when a restore fails on start (no Spring context); `PreMigrationBackupTest` checks the copy `Configuration.resolveDb` saves before an existing database is migrated (an older version, no history table, nothing for a current or new database, only the newest three kept). |
| `domain` | `HelpAssistantServiceTest`, `HelpAdminDataTest`, `ProblemLogTest`, `UiProblemsTest`, `ExtendableEntityListenerTest`, `ExtendedContentCompressionTest`, `LoreChangesTest` (one notice per transaction after the commit, none on a rollback, the page that wrote), `FulltextQueryTest`, `ChatMessageSearchTest`, `TokenLimitsTest`, `AISharingTest`, `UsageServiceTest`, `AILimitServiceTest`, `ExtensionAIFactoryTest`, `CronScheduleTest`, `SillyTavernEntryConverterTest`, `TemplateHelpersTest`, `OsgiServiceImplTest`, `PermissionServiceTest` | Smaller units: extended attribute serialization, token limits, cron parsing, SillyTavern conversion; `FulltextQueryTest` and `ChatMessageSearchTest` cover the full-text query (words, phrases, `*`, escaping) and the search over all branches with the choice of the branch that shows a part (Spring context). `HelpAssistantServiceTest` covers the help assistant against the mock LLM: only administrators set it up, with an AI of their own, the AI is looked up at every request (deleted, or its owner no longer an administrator: unavailable), who pays (limits checked and usage counted only for a shared AI with *Apply limits*, otherwise `UnmeteredScope`), the default and the edited prompts per role, the functions the model calls (the manual, `get_ui_state`, and `interact_with_ui` only when interactions are allowed and there is a page) with a stub `UiStateSource` (also `read_last_errors`, and the Admin data functions: only for an administrator and only when allowed, an unknown topic refused). `HelpAdminDataTest`: the end of an extension's log without secrets, cut from the front, and how the tool guards the topic and the number of lines. `ProblemLogTest` / `UiProblemsTest`: the session's log of what the user was shown (newest first, 20 kept, the same message told twice is one problem, secrets removed, text cut), what is recorded from the notifications and the exceptions through a fake Vaadin session (`UI.setCurrent` replaces the thread's session, so the session is set after the UI), and the merge of the copy the browser kept. Its settings belong to the installation and survive between tests, so the test saves the defaults first. `OsgiServiceImplTest` loads, replaces and unloads extensions on a real OSGi framework with test bundles built on the fly (`TestExtensionActivator`), lists the invalid ones (`getInvalidExtensions`, not the stopped ones), including the verification reports that allow or refuse starting them; it has no Spring context; it also checks that an extension's localization bundles are registered while it is loaded, removed on unload, and that an extension can't replace a language that already has a bundle; at startup only the newest version of an extension in the folder is loaded and the older JARs are moved to `old-versions`; stopping and starting extensions (the `.STOPPED` flag survives a restart, an upload starts a stopped extension) and the extension logger (SLF4J formatting, tail reading, rotation, removal with the extension); the AIs shared by administrators (visible to all, read-only for others, only administrators share, the setting that stops users from creating AIs while keeping the existing ones) and the `Usage` of a user per AI (adding up, a row per user of a shared AI, who may list them, the overview of all users for administrators only). |
| `manual` | `ManualParserTest`, `ManualServiceTest`, `ManualLanguageTest` | The user manual of the help assistant: sections by heading with the text cleaned, the title falling back to the label, the pages loaded without pictures, finding a page by path with tolerance, links between pages pointing at existing pages, the address of each page on the published site (and that `docs/` has a file for every one), the tools printing it, the search ranking the relevant page first and finding nothing without usable words. The manual in the language of the user (`ManualLanguageTest`): a translated page in its language with the address of its site, English for a language without translations or a code that is no language, the list and the search giving the translated sections of the same hits, the tools reading and linking in the language, a heading keeping the id the translation tool writes before it, and for each of the seven languages: every page translated with the sections of the English page (the search maps a hit by place), the code blocks and the inline code of the English page unchanged in the translation (the rule of `manual_i18n.py verify`), the links of the pages pointing at existing pages (and that `docs/<language>` has a file for every page). |
| `ipc`, `tool` | `IPCServiceTest`, `ToolServiceTest` | `ToolServiceTest` (the `ToolService` registry, with fake providers): a provider gets only the checked items that are still offered, nothing checked or everything gone gives no tools, a suite without items is on or off, the hint of the user replaces the default one, two suites with a function of the same name fail with both names, a provider that throws is left out, the commands of a provider are registered with it and removed with it, registering a key again keeps its place, the items as they are now, the count of what is on, and the selection as plain JSON that `compact` trims. The providers of `IPCService`: order of registration, replacing a key, separate book and story part providers, `null` for a provider that is gone, errors reaching the caller, removal by bundle, snapshots of the listing. (`OsgiServiceImplTest` checks that unloading an extension removes its providers.) |
| `inference` | `InferTest`, `InferenceSessionTest`, `PartialJsonTest`, `RoundStatsCollectorTest` | `InferenceSessionTest`: the header `X-Session-ID` the mock LLM receives (an opaque 32 hex hash, the same for one user and kind, other for another kind, scope, user, none outside an `InferenceSession`; a new part, a regeneration and the part of another book share it). `InferenceService.infer` against the mock LLM: whole text, schema check (`SchemaCheck`), answer read into a class, function calls during `infer`, provider failure; the schema built from `@LLMSchema` / `@LLMField`; `stream` passing a schema. `PartialJsonTest`: `PartialJson` reads the JSON of a streamed answer so far (unfinished strings, keys without a value, escapes, fences that are not closed yet). |
| `revision`, `crud`, `db`, `loc` (new) | `MessageRevisionServiceTest`, `PartAuthorshipTest` (who wrote the words, from the versions: typed, generated, edited, redrafted, regenerated, restored, an agent, no history; the sums of a branch), `PartHistoryRecordingTest`, `PartHistoryActionsTest`, `PartHistoryLimitTest`, `PartHistoryBackupTest`, `VersionSearchTest`, `PartRevisionMigrationTest`, `MessageRevisionCrudTest`, `VersionHistoryPermissionMigrationTest`, `RevisionLocalizationTest` | The version history of a part: what records a version and from which source, restore / roll back / labels / the trash, the limit and the pruning, backups with the history, *Include versions* in the searches, the migrations. See [Version history](version-history.md#tests). |
| `prompt`, `domain.service.impl` (new) | `MessagePromptTest`, `StoryAroundTest`, `PromptComparisonTest` | `LoreUsageServiceTest` (the report over a tree of parts with hand written records: branch against all branches, range, statuses, entries that are gone or moved, another user) and `LoreUsageDialogsTest` (the two windows). `MessagePromptTest`: the built prompt, the lore and the lore usage of a part in their own row (`MessagePromptService`: stored deflated, replaced, removed when empty, shared by a branch, deleted and restored with the part, kept in a backup) and the migration that moves it out of the extended content. `StoryAroundTest`: the story around a part as the earlier messages of the conversation of the annotate and the redraft (the budget in steps, a new part only appends). `PromptComparisonTest`: two built prompts compared like a prefix cache (per-message status, the first difference, the shared share). |
| `generation`, `ui.workspace` (new) | `GenerationAccessUiTest`, `PartIconTest` | `GenerationAccessUiTest`: a listener shows something through `accessUI` and the generation waits for the answer (sending goes on with the request; stopping ends the generation before the request is sent), and a generation without a UI is not held. `PartIconTest`: every icon is well-formed SVG, the icons differ and the component carries the style class and the drawing. |
| `domain.service`, `ui.dialogs` (sharing) | `SharedLibraryTest`, `SharedImportDialogTest`, `CloneSettingsTest` | `SharedLibraryTest`: a lorebook or protocol is not shared by default; another user sees it with its author and the owner does not; deleted, unshared and agent copies are not offered or imported; the copy is private, owned by the importer, with the entries, tags, negative tags, description and attributes, and leaves the original alone; only the sub lorebooks that are shared are copied (with everything below an unshared one left out); `findUnsharedSubbooks`, `share(book, withSubbooks)`, unsharing, and a user who does not own the lorebook; the description in clone, export and import. `SharedImportDialogTest`: the list, the empty message, the **Import** button (the copy, the callback, a lorebook unshared meanwhile) and the preview showing only shared sub lorebooks. `CloneSettingsTest`: the clone of a lorebook, protocol and AI. |
| `function` | `FunctionRegistryTest` | Interfaces become function schemas (the continuation is not in them), arguments are parsed, methods run on the executor and answer through `FunctionContinuation` (also from another thread, first answer wins), interfaces with a method that returns a value or lacks the continuation are rejected. |
| `generation` | `InferenceFunctionCallTest`, `GenerationRequestTest`, `LorebookActivationTest`, `BuiltPromptHistoryTest`, `ReservedTokensTest`, `TokenBreakdownTest`, `FailedGenerationTest`, `AILimitGenerationTest`, `ExtensionAIGenerationTest`, `ImageAttachmentGenerationTest`, `InferenceAttachmentsTest`, `MetaSummaryTest`, `RedraftTest`, `UsageGenerationTest`, `GenerationOptionsTest` | Full generations: what is sent to the model, which lore is activated and where it goes, the story history in the prompt (new part, swipe, regenerate), tokens reserved by extensions, the stored token breakdown of a prompt (sections, reserved and cut story, payload messages, `null` for parts without it), a failed request leaving the story unchanged, images staying with a part and never reaching the model, the attachments of an `LLMChatMessage` (image as a data URL or URL, WAV audio, a file; a plain string content without attachments; audio of an unsupported format rejected before any request) as the content parts of the request, meta summaries and the summary chain, redrafts (the prompt of `RedraftService`: the part, the instructions, the story before and after it, valid summaries standing in for the older story and outdated ones left out, the newest story kept when it does not all fit, the prompt chain book → user → default, nothing stored), the tokens counted per user (reported by the provider or estimated, also for a direct `stream` call, a failed request not counted); `InferenceFunctionCallTest` covers the model calling functions: tools in the request, results sent back, several calls and rounds, calls answering from other threads, failed and refused calls reported to the model, the round limit, cancelling while a call is pending and the tool role resolvers. |
| `templates` | `TemplateServiceTest`, `MacroRenderingTest`, `MacroLorebookFixtureTest`, `DefaultTemplatesTest` | Handlebars rendering and SillyTavern macros; the built-in templates. |
| `lorebook` | `LorebookImportExportTest` | Marginalia and SillyTavern lorebook import and export. |
| `backup` | `ManuscriptRestoreTest`, `ManuscriptBackupCopyTest`, `ManuscriptCloneTest`, `BackupLorebookTest`, `BackupAiProtocolLinkTest`, `BackupImagesTest`, `DatabaseBackupScheduleTest` | Book backups, restore and copy, lorebook and provider linking, the images of parts in backups (the archive made on export, own resources for restored and cloned books), scheduled database backups. |
| `export` | `ExporterTest`, `ExporterImagesTest` | The story exporters (TXT, Markdown, HTML, DOCX, PDF, EPUB): text and Unicode, linked contents and chapter navigation, splitting of long stories, embedded images and where they are placed among the text (all formats; PDF and Word checked by text and structure). |
| `domain/model`, `ui/dialogs/manuscript` | `PartLayoutTest`, `ImagesDialogTest` | Where the images of a part are among its text: the anchors and the cuts between blocks (never inside a list or a code block), groups, wrapping only at the sides, width limits, the old values without a position; the dialog of the images saving the position, the wrap and the width, the preview button, `PartView` building the pieces and the pictures. |
| `styles` (1.6.0) | `PartStyleTest`, `PartStyleServiceTest`, `PartStyleEditorTest`, `PartStyleApplierTest`, `PartStyleTransferTest`, `PrintStyleTest`, `ReaderStyleChooserTest` | The text styles: the registry with *Normal* and *Book*, the stylesheet an option set makes (nothing for an empty style, values that can not leave their declaration, the custom CSS last and with matching braces, the background on the whole element), the service (built in styles can not be changed, duplicate, delete, the default), the editor of the Settings (changes stay in memory until the settings are saved, reload is the discard), the entries of the menu of the story and the style on the element, export and import of `.style.json` (round trip, unknown options counted, files refused, the horror example of the manual loads), the stylesheet for paper (`toPrintCss`, units to points, colors to RGB), and the style chooser of the reader (the Book style until the choice, the cookie, only the styles of the reader). |
| `export` (1.6.0) | `ExportSettingsServiceTest`, `ExportSettingsEditorTest`, `ExportDialogStyleTest`, `ExporterStyleTest`, `ExporterTemplateTest`, `ExporterTargetsTest` | The style and the templates of each format (the own look of the format unless the user chose another, only styles for exports can be chosen, a template per format and key, a blank one is the default, an invalid one is refused), the Exports tab (stored on Save only, the defaults are not stored), the choice in the export dialog, the print style in HTML, EPUB, PDF and Word, the title page template, and the formats for other tools (front matter, AO3, SillyTavern chat, Obsidian vault). |
| `inference` (1.6.0) | `StreamStopTest` | A stop ends the wait for the server at once, both while it still reads the prompt (nothing sent) and between two chunks, with a fake server that holds the answer back; the same for `infer` and `round` (`aStopDoesNotWaitForTheServerToAnswerAnInfer` / `...ARound`), and for a whole generation (`GenerationEndEventsTest.stoppedWhileTheServerReadsThePromptEndsAtOnce`: the end is reported within seconds, outcome `CANCELLED`). |
| `utils` | `AttributeMergeTest` | The merge of the dynamic attributes when the settings are loaded again before they are saved: the keys held by the page win, those only the fresh copy has stay. |
| `crud`, `backup` (extension settings, 1.6.0) | `ExtensionSettingsInheritanceTest`, `BackupExtensionSettingsTest` | The settings extensions add to the books: the book, then the nearest folder, then the user level, then the default of the extension; a blank value clears and a missing key leaves it; the values stay while the extension is not loaded; a failing supplier does not break the resolution; the folders of a backup come back with their extension settings and an export writes what the book inherits. |
| `desktop` (1.6.0) | `BundledPluginsTest` | The launcher of the desktop app (`src/desktop/java`, compiled as a test source): the first start copies every bundled plugin, a second one nothing, a plugin the administrator removed stays removed (also in a newer version), a new version is copied next to the old one. |
| `security` | `ApiKeyEncryptionTest` | API keys stored encrypted with the installation key; the app migration encrypting plain ones. |
| `security` (1.9.0) | `OutboundAddressGuardTest` | The addresses the server may call (no application, a lookup the test controls, 127.0.0.1 standing in for a public address and 127.0.0.2 for a private one): the private ranges, a name with one private address among public ones, an unknown host; the client of `publicOnly` looks the name up once and connects to that address with the `Host` header of the name; a name that answers public at the check and private at the connection (DNS rebinding) is refused before anything is sent, also asynchronously; `https` is checked and connected directly. |
| `api`, `domain/security` (1.9.0) | `ApiDispatcherTest`, `ApiDocsTest`, `ApiKeyServiceTest` | The [HTTP API](api.md) without HTTP: the key and its access, the commands in the scope of a book, the runs and the administration; the page of the API and its OpenAPI description (what needs no key, what a key adds, the description lists exactly the calls the dispatcher answers); who may have keys, what is stored of them (a hash) and when they stop working. |
| `domain/service/run`, `inference`, `generation` (runs, 1.9.0) | `RunsTest`, `AIGatePriorityTest`, `AfterPartTest`, `RunCornerTest`, `PhraseWatchStepTest` | The registry of runs: the sweeper (a forgotten run ends, one that works, waits for the author or for the model and a window of a live page stay), an agent refused on a book any run works on, the part a generation writes saved only by its own threads; the author's generation going before the requests of what follows a part at the queue; a parallel step that writes the part fails; finished runs in the panel until closed; a redraft that writes a watched phrase back in is redrafted again, three rounds at most. |
| `extensions.smoke` (1.9.0) | `PluginSmokeTest` (only with `-Dmarginalia.plugins`), `PluginLeakFinderTest` | Every built plugin verifies, loads and unloads without leaving anything behind, see [The plugin smoke test](#the-plugin-smoke-test). |
| `utils` | `ClientAddressResolverTest`, `GeneratedTextHighlighterTest`, `AuthorshipTrackerTest` (the merge of versions over the words), `BuildInfoTest`, `CommandUtilsTest`, `TextDiffTest`, `WordDiffTest`, `TimeSafeTextTest` | `GeneratedTextHighlighterTest`: the diff view's highlight (shared words marked, the author's text not, one mark per line, markdown line prefixes outside it, a huge rewrite). The client address: the header is ignored without trusted proxies and from any other peer, chains of proxies, CIDR ranges, no host name lookups (no Spring context). |
| `loc` | `LocalizationTest`, `BundleCompletenessTest` | The language of the session selects the bundle, texts a bundle lacks come from the default language, a language can't be registered twice, the default one can't be removed, `UserSetting.language` is saved (Spring context). Every key of the Japanese, the French and the Spanish bundle is translated and its `%s`/`%d` placeholders match the English text. |
| `ui` | `LLMSnapshotTest`, `StatisticsViewTest`, `ActivityCalendarGridTest`, `WorkspaceLLMSupportTest`, `WorkspacePartsLLMTest`, `HelpAssistantWidgetTest`, `ResourcesPartTest`, `BranchSearchTest`, `PromptComparisonDialogTest`, `ViewerFoldersTest`, `WorkspaceStateTest`, `AIDialogExtensionTest`, `TabDockTest`, `LorebookPreviewTest`, `LorebookEditorDialogTest`, `LorebookEntryEditorTest`, `LorebookEditorLockTest`, `AutoAnnotateDialogTest`, `InvalidExtensionsWarningTest`, `LazyContextMenuTest`, `LazyBranchTest`, `MultiTagDialogTest`, `MassChangeModelProtocolDialogTest`, `MassChangeLanguageDialogTest`, `MassRenameDialogTest`, `MassRenameTest`, `LorebookMassEditDialogTest`, `LorebookLockViewTest`, `LorebookSubbookTokensTest`, `PermissionsDialogTest`, `LorebookSearchReplaceDialogTest`, `ManuscriptSearchReplaceDialogTest`, `ToolSelectionDialogTest` | The Resources tab grid: lazy paging, only the user's files, deleting the selection. The search of the branch view (`ManuscriptTreePart` with a stand-in for the book window): the result line, "Show in story" switching the active branch and ignoring ids of other books. `WorkspaceStateTest`: the autosave of the workspace - what each `Restorable` stores and restores (tab, filters, open book, lorebook entries, the new turn form), what is skipped when it is gone, and the state kept in `UserSetting.workspaceState`. `AIDialogExtensionTest`: the type Extension of the AI dialog with a fake factory - the provider is chosen, its form shown and applied, Test Connection uses the unsaved values, an AI of an unloaded extension is edited with a notice. `TabDockTest`: the sidebar `TabDock` - the layout it builds, detaching a tab into a sheet or a column by drag and drop, joining another sheet, the stored selection and the layout and the position of the sidebar divider kept in the attributes of the manuscript. `LorebookPreviewTest`: the lorebook preview of the story editor - the top level rows with and without the sub lorebooks (deep, shared and circular sub lorebooks), no lorebook, and what a refresh keeps. `LorebookEditorDialogTest`, `LorebookEntryEditorTest`, `LorebookEditorLockTest` (an `AgentTestBase`): the full-screen lorebook editor - opening entries in tabs and where a new tab goes, the layout, the open entries and the editor modes kept in the lorebook, the entries of the sub lorebooks, per-field saves that keep what was changed elsewhere, the text conflict and its two answers, changes of other windows shown in place (`loreChanged`, `changedElsewhere`), read only while an agent works on the lorebook, the localized toolbar, the links between entries (Ctrl+click, *Mentioned in*). `LoreMentionsTest` (`domain`, no Spring): where a text names entries. `LoreImagesTest` (`domain`, no Spring): the image markup of entries. `LoreImagesGenerationTest` (`generation`): what the model gets of the images (stripped text; the answered message after the system prompt, the system message, the prompt). `LoreImagesTravelTest` (`backup`): the images copied with a clone, a lorebook file, a shared copy and a book backup. `InvalidExtensionsWarningTest`: the red bar about invalid extensions - hidden when none, names on hover for the administrator, a note without names for users, gone when fixed (with a fake `OsgiService`). `LLMSnapshotTest`: the tree the help assistant's model reads - paths, only the active branch against deep, hidden elements, a failing element, numbering of siblings, the interactions (offered now, applied in order and looked up again before each step, an unknown key, by path), the buttons that open a dialog (`dialogButtons`, not while a dialog is open) and `getLLMProblems` (an empty required field, an invalid one with its message, never a value, hidden, disabled and nested fields left out). `WorkspacePartsLLMTest`: what the lists of books, models and protocols (desktop and phone) and the settings tell the assistant and offer (`open-dialog:`, `open-tab:`; pressing the button is not tested here, a UI without a session can not attach the dialog). `WorkspaceLLMSupportTest`: the section names and the moves to open them (the workspaces themselves need the OSGi service, which the test context does not have, so there is no snapshot test of a real workspace). `ToolSelectionDialogTest`: the Tools window with fake providers - a section for each suite under its name, saving without a change gives the same choice, the filter of a section keeps the checked items and *Check shown* checks only what is shown, a suite without items is on or off and its hint is kept, and the button shows the number that is on and hides itself when no suite is installed. `HelpAssistantWidgetTest`: the button only while the assistant is on, the AI named, the limit warning, the stored conversation, reading and moving through a page, and merging the problems of the session with the ones the browser kept (an open dialog is added to the `UI` by hand: Vaadin attaches it at response time). `StatisticsViewTest` builds the statistics view (the tabs, the totals, the goal bars, the calendar of a book and of all books, on the desktop and on a phone) over real data; `ActivityCalendarGridTest` is the layout of the calendar, without a UI. They build Vaadin components without a UI session. |
| `domain/agents`, `ui/dialogs/agent`, `ui/workspace/parts` | `AgentServiceTest`, `AgentRunServiceTest`, `AgentRunnerTest`, `AgentMessageServiceTest`, `AgenticBooksTest`, `RunToolsTest`, `AgentRunStatusTest`, `AgentRunControlTest`, `ManuscriptLockTest`, `AgentSessionTest`, `CommandFunctionsTest`, `CommandFunctionsAgentTest`, `VirtualPathTest`, `VirtualFileSystemTest`, `AgentFileToolsTest` (these three, with `ImageFilesTest`, `ImageToolsTest` and `ZipUnpackTest`, in the platform module), `AgentVirtualFileSystemServiceTest`, `AgentDialogTest`, `AgentCloneAndStopDialogTest`, `AgentPartTest`, `AIGateTest`, `AgentApprovalTest`, `AgentAttentionTest`, `AgentContextTest`, `AgentCopyServiceTest`, `AgentDiagnosticsTest`, `AgentRunDiagnosticsTest`, `AgentHandlesTest`, `AgentMergeTest`, `AgentMergeNoLorebookTest`, `AgentRunPairsTest`, `AgentSubagentsTest`, `AgentSyncTest`, `AgentTranscriptExportTest`, `AgentWebhookTest`, `AgentWorkingCopyTest`, `CheckpointServiceTest`, `CommandScopeTest`, `ImageFilesTest`, `ImageToolsTest`, `LorebookLockTest`, `RequestSlotsTest`, `ZipUnpackTest`, `JsonMergeTest` (`domain/agents/jsonmerge`), `AgentConsoleDialogTest`, `AgentCheckpointBrowserTest`, `AgentContextViewTest`, `AgentCopyViewTest`, `AgentDiagnosticsViewTest`, `AgentMergeDialogTest`, `AgentModelsEditorTest`, `AgentSubAgentsViewTest`, `AgentWorkspaceSourceTest` (the browser: `WorkspaceBrowserTest`, platform), `JsonMergeDialogTest`, `PhoneWorkspaceAgentsTest` | Agents (on `AgentTestBase`): who may have them and how many, the status table, start / pause / stop / resume, the lock of a book while a run works (every service that changes the book refuses, reading and a paused run do not); the request context of a run (the session beans resolve as the owner, the language of the run, the context handed to another thread); the commands as functions of an agent (names, the schema of the forms, the call that picks a form, bounded results, `Error:` messages, the destructive mode and the approval; every registered command makes a function and a call on a thread of a run reads the book of the run); the cage of the files of an agent (paths, mounts, symbolic links, limits, no real path in any message); the runner against the mock server (a reply ends the turn, calls of commands, files and run tools, `finish`, `ask_user` and a message that goes on, errors for the model, the budgets, the context cap, a pause or stop that waits for the round in the air, a model error, a transcript with an interrupted call, a trashed run); the transcript rows; the agentic flag of books (the old lists return both kinds, the regular and agentic ones split them); the dialogs and the table of the Agents tab built without a browser (`ComponentTree` finds buttons in a built view). `DesktopWorkspace` can't be built in a test (it needs OSGi), so the condition that shows the tab (`AgentService.isAllowed`) is tested in the service. |
| `command` | `CommandServiceTest`, `CommandDispatchTest`, `CommandLineTest`, `CommandHelpTest`, `BuiltInCommandTextsTest`, `ManuscriptReadCommandsTest`, `ManuscriptWriteCommandsTest`, `LorebookReadCommandsTest`, `LorebookWriteCommandsTest`, `GenerationCommandsTest`, `SearchReplaceCommandsTest`, `BackupCommandsTest` | The command registry and dispatch (overloads, parameters, `async`, the scope a command runs in), the line parser and the help, every built-in text, and the read and write commands of the book and the lorebooks (their results, errors and the data severity), the commands that write with the model (on the mock LLM), search and replace, the backup command. `StatisticsCommandsTest` checks `get-book-statistics` and `get-statistics` (the days and totals, the default range, the side, the books by day or by book with the most words first, a wrong range, side or grouping refused). The test fixture `HelloWorldCommands` (`test/commands`) is the model of a suite and of an `async` command. |
| `search`, `manuscript`, `lorebook` (new) | `TextSearchTest`, `ManuscriptReplaceTest`, `LorebookReplaceTest`, `ManuscriptArchiveImportTest`, `LorebookArchiveImportTest`, `LorebookEditServicesTest`, `PartEditServicesTest` | Search and replace over the parts and the entries (the regular expression, the case, the dry run, the outdated summaries), the import of a zip of `.md` files into a book and a lorebook, the services that edit a part or an entry. |
| `summary` (new) | `SummaryTransferTest`, `SummaryImportExportTest` | The text file of the exported summaries (written and read back, blank lines around a text, CRLF, a header without a part, a file that is not an export) and the export and import through `SummaryService`: the order, an untouched export changing nothing, an edited text, a copy of the book matched by position only when asked, a part without a summary, an empty text. |
| `annotation`, `utils` (new) | `AnnotationServiceTest`, `AnnotationGenerationTest`, `AnnotateServiceTest`, `TextAlignmentTest`, `QuoteFinderTest`, `TextMarkupTest`, `AnnotationCleanupTest`, `AnnotationCrudTest` | Annotations: creating and listing, the passages moving with an edit (before, inside, at the edges, deleted and typed back, a typo, a replaced text found by the quote), merge, branch, delete and restore, the backup round trip, the notes marked for the prompt reaching the master template, a regenerated part; the model annotating against the mock LLM in every mode (a retry, an unreadable answer, two stages, quotes not found); the three text utilities. |
| `crud`, `generation`, `backup`, `domain`, `ui` (folders, 1.6.0) | `FolderCrudTest`, `FolderServiceTest`, `FolderTransferTest`, `FolderListTest`, `FolderSettingsTest`, `SettingsInheritanceTest`, `ModificationTest`, `FolderSettingsGenerationTest`, `BackupFoldersTest`, `BackupExportInheritanceTest`, `AgentFoldersTest`, `HelpAssistantBooksTest`, `FolderDialogTest`, `OrganiseDialogTest`, `OrganiseDialogFlowTest`, `BookPromptSettingsTest`, `MassChangeModelProtocolDialogTest`, `MassChangeLanguageDialogTest`, `ManuscriptPartFoldersTest`, `PhoneManuscriptPartFoldersTest`, `BookLabelsTest`, `StoryMassDeleteTest`, `TabDockIconsTest` | The folders, see [Folders](folders.md#tests): the entity and the service rules (names, cycles, delete, the lock of an agent's book), copy and move with name clashes, the settings of the folders resolved for a book and reaching the prompt of a generation, the modification time of books and folders, the folder in a backup and the inherited settings in an export, the working copy of an agent, the books tools of the help assistant, and the windows (settings, Organise with its keys, the lists on the desktop and the phone). The mass delete of parts and the icons of the minimized tabs are here too. |
| `generation`, `utils` (macros, 1.7.0) | `ClosestMacroTest`, `CommandMacroTest`, `ReflectUtilsTest` | `ClosestMacroTest`: `{{closest-message::n}}`, `{{closest-summary::n}}` and `` count the parts and summaries back from the part being written (a position that is not there is empty, the argument can be a macro, a regenerate and a swipe have the part they replace as the current one, a new part has none). `CommandMacroTest`: `{{command::name::argument}}` runs a read only command made for macros (its answer is in the prompt, it runs once per generation whatever the number of renders, other arguments are other calls, a command in an untaken branch is not run, an `async` one is waited for, one not made for macros is not run, a failing one renders empty and is not kept); the answer is kept with the part the generation continues from (a later generation from the part reads it, a regenerate or a swipe runs it again, a refresh drops the answers of calls that were not made); `availableInMacros` without `readOnly` is refused when the commands are registered. `ReflectUtilsTest`: a private method or field is found in a class whose hierarchy ends in JDK classes (`Object`'s methods cannot be opened: the lookup used to fail and an extension was told the method did not exist). |
| `cleanup` | `CleanupServiceTest`, `TrashServiceTest`, `SoftDeleteCascadeTest`, `PermanentDeleteTest`, `AgentCleanupTest` | Purging soft-deleted data (also an AI with usage rows), owned data, strong and weak references, resources whose object is gone (kept while a row, also one in the trash, names them or a contributor keeps them); the trash: own objects only, administrator sees all, restore refused while a deleted parent is not restored with it, extended content; `SoftDeleteCascadeTest`: a soft delete takes the owned objects with it and a restore brings them back (the purge tests there log in as administrator); `PermanentDeleteTest`: deleting parts and entries for good, children moved to the parent, active leaf, blocked deletes roll back. |
| `instruct` | `ExtendableMethodVisitorTest`, `BuildTimeWeaverTest`, `RuntimeInstrumentationTest`, `ExtensionVerifierTest`, `PublicAPISignatureTest` | The bytecode instrumentation of `@Extendable` methods, the weaver of the build and the runtime agent; the verification of extensions against the application; the `@PublicAPI` declarations of the `@Extendable` classes. |
| `architecture` (1.9.0) | `LayerDependencyTest` | The platform (the code Joi and the visual novel are to build on, see `TODO.REFACTOR.md`) does not name a class of the application: every main class has a layer in `layers/layers.txt`, the references that exist today are listed in `layers/allowed-leaks.txt` and the list may only shrink. See [The layer check](#the-layer-check). |
| `utils`, `generation` (1.7.0) | `AppClockTest`, `StoredTimesFollowAppClockTest` | `AppClock`, the one clock the application stores times from: it follows the system clock until a test sets another, every reader sees the set clock; a generation run "on" another day stores the times of the part (creation, modification, the stamps of the history) from it. The dataset build moves it day by day. |
| `planner`, `command` (1.7.0) | `PlannerServiceTest`, `PlannerCommandsTest` | The planner of a book: a scene is added at the end with a new uuid and never as done, the texts are stripped and a title is required, done and not done, an update keeps the place, moves stop at the ends, a missing scene is ignored on delete and an error elsewhere, the list is a copy, the listeners are told of every change until they are removed, the scenes travel with a backup, the limit of scenes; the commands add, update (only what is given), mark done and move by the number in the list, delete. |
| `planner`, `utils` (1.8.0) | `PlannerServiceTest`, `TurnDetailsMergeTest` | More of the planner: a scene is inserted after the scene given, two scenes become one in the place of the first (done only when both were), the parts of the active branch become scenes at the end (a long first line is cut for the title, nothing is imported when the scenes do not fit the limit). `TurnDetailsMergeTest`: what the merge dialog suggests for two turns, texts under each other, a blank or repeated text not joined, the names of both lists once, the first value where there is one, titles joined and cut. |
| `jobs`, `domain/agents`, `generation` (1.8.0) | `JobsTest`, `JobServiceTest`, `AgentRunnerTest`, `ResummarizeTest` | `JobsTest` (no application): closing the handle ends the job with its calls, a call outside of a job is not recorded and a request outside of one is a job of its own (`untagged` without a session), an asynchronous job ends when finished, a call still running when its job ends is cancelled, nested jobs, the sweep of idle jobs, a failing sink. `JobServiceTest`: an ended job is written with its calls, search filters and pages, purge deletes the matching jobs with their calls and nothing else, only an administrator reads or purges, a request to a model is a call of the job of the thread. A work session of an agent run and a whole re-summary run are one job each, a stopped run a cancelled one. |
| `summary`, `generation`, `ui.dialogs.bookimport` (1.8.0) | `SummaryPlannerTest`, `CreateSummariesTest`, `LoreNotesAgentTest` | `SummaryPlannerTest` (no application): where summaries go by tokens (the part that reaches the target ends the block), parts and chapters (the shallowest heading level that starts a part, the minimum of tokens that keeps a short chapter in the next block, also for the rest), the block limit, no parts. `CreateSummariesTest` (mock model): the parts after the newest summary, the plan up to a part, the summaries written oldest first and each valid (`collectBlocks`), only the parts after an existing summary, a stop that keeps the summaries before it. `LoreNotesAgentTest`: refused without the permission, without a model and for a book that has an agent, started with the model of the book, the instructions and only reading and lorebook-writing commands (all registered), a lorebook made, the run handed to the runner. |
| `utils/docimport`, `manuscript`, `ui.dialogs.bookimport` (1.8.0) | `DocumentFormatTest`, `TextFormatsTest`, `ProjectFormatsTest`, `PartSplitterTest`, `ManuscriptDocumentImportTest`, `BookImportSourcesTest` | The readers of the documents (Word and LibreOffice with their styles, RTF, Markdown, plain text, EPUB, an Obsidian vault and a Scrivener project, files that are not what their extension says), the cutting of a document into parts, the storing of the parts as the author's (not counted) at the end of a book or between two parts (what followed the place follows the new parts, the active leaf, the summaries over the place), and the sources and the place picker of the import window. |
| root package (1.8.0) | `SecretKeyPermissionsTest` | `secret.key` is created readable by its owner only; an open key of an existing installation is reported and left as it is (POSIX file systems only). |
| `crud`, `domain/service/run`, `inference`, `generation`, `ui.components`, `ui.widgets`, `ui.dialogs` (1.8.0) | `SafeWritesTest`, `StaleSavesScopeTest` (the saves are remembered by the database that owns the row: a row of another database with the same id is not stale, one of the same database is), `RunsTest`, `GenerationRunsTest`, `GatedInferenceServiceTest`, `AfterPartTest`, `AutoAnnotateStepsTest`, `RunCornerTest`, `FloatingWindowTest`, `WindowRunTest`, `BookWindowsTest` | The concurrency of long operations: a stale save is reported and `update` writes on the stored row; the registry of runs refuses with the name of the run (holds, modes, stages of a generation); every request waits for a connection of its AI in order, reports to the run it is bound to and gives its place back; what follows a part runs in its stages, stops, waits for the author; the panel of the runs lists the user's runs and windows; a floating window folds instead of closing while it works, ends with its book window or its page, is folded when a modal it was opened over takes it out of the page; a window request is a run; one window per book, and `openFor` opens a book for a plugin unless another one is open. |
| `update`, `utils` (1.8.0) | `UpdateServiceTest`, `WordCounterTest` | The status of the update watcher and the request for an update (files in `<data>/update`); the word count of mixed, Chinese and Japanese text. |
| `utils`, `manuscript` (1.7.0) | `LmStudioChatsTest`, `LmStudioImportTest` | The conversations of LM Studio: the messages, the thinking and the model, the name of the file when there is no name, the versions of a message as alternatives with the selected one shown, the system prompt and the tools that are not messages, conversations that share their beginning joined into one tree, the user message as the instructions with *merge*, a file that is not a conversation refused; the import makes the tree of a new book. |
| `inference` (1.7.0) | `InferenceListenerTest`, `ReasoningPassthroughTest`, `StructuredOutputsParseTest` | `InferenceListenerTest`: a listener is told of a request (kind, model, protocol, a copy of the messages), of each chunk and of the end (result, error, cancel), a failing listener does not break the request, a removed one sees nothing (the service stays wrapped: the job log keeps its own listener). `ReasoningPassthroughTest`: with the fake server, *None* (the default) sends no thinking, *Between tool calls* sends the thinking of the calls of this turn only and *Always* the thinking of every answer that has it, as `reasoning_content` of the assistant message. `StructuredOutputsParseTest`: the lenient reading of a structured answer (a markdown block, a sentence before the JSON, a trailing comma, a repeated key) and what stays strict. |
| `annotation`, `domain`, `extensions`, `generation` (the text of the story, 1.7.0) | `PassageServiceTest`, `ModelTextTest`, `PartTextRegistryTest`, `ExportTextRegistryTest`, `PartTextGenerationTest`, `ReplaceTextTest`, `StoredTextReadersTest`, `ResummarizeTest` | Anchored passages of an extension (the kind, the range and the data, a quote anchored, kept apart from the notes, moved by an edit, orphaned and back, copied to a branch, kept by a backup, deleted with the part); the map between the stored text and what the model reads; the registries (one preparation for all parts, the first of two overlapping edits wins, a failing contributor is left out, the footnotes of an export numbered across the parts); a generation reads what the model reads (prompt, `closest-message`, `current-message`, the lorebook scan); replacing the text of a part without flagging it as edited (tokens of what the model reads, summaries stay valid, a version in the history); every class that reads the stored text of a part is on the list in `stored-text-readers.txt`; the re-summarizing of all summaries (oldest first, uuids kept, meta summaries inner first, a stop changes nothing). |
| `export` (1.7.0) | `LatexExporterTest`, `ExporterFootnotesTest`, `PdfExporterNotesTest` | The LaTeX project (a zip, the preamble and metadata, special characters, chapters from the shallowest heading, CJK text, footnotes), the footnotes in every format (kept, listed after the text, linked, real footnotes in Word numbered across parts) and the notes at the foot of the page in the PDF with Japanese text drawn. |
| `ui.components` (1.7.0) | `ThreadCopyRequestAttributesTest` | A worker thread resolves the session scoped beans after the page is gone, the copy locks the same mutex as the page and never fails on an invalid session, a copy of a copy is the same copy. |
| `workset` (1.7.0) | `LargeWorksetTest`, `LargeWorksetMigrationTest`, `LargeWorksetSoakTest`, `ExportRoundTripCheck` (only with `-Dworkset.roundtrip=true`) | A book of a real size, the [dataset book](#the-dataset-book): restored and checked (100 parts and a branch of 3, 31 summaries, 1,697 annotations and passages, 360 versions, the stored prompts, the data of four plugins, the lorebook, the picture); `PartRevisionMigration` and `StatisticsBackfillMigration` over it (the result and the time); two users on long books (one of 400 parts) with generations in flight on a slow mock model while backups, edits and statistics reads run on other threads. |
| `backup` (resources, 1.7.0) | `BackupResourcesTest` | The resources a book points to besides the pictures (the audio an extension keeps with a part, named by uuid in the part's attributes): counted in the backup, packed into the archive, given as own copies (linked to the new parts, the new uuids written into the attributes) when the archive or the JSON is restored as a new book and when a book is cloned. |
| `crud` (export templates, 1.7.0) | `ExportTemplateInheritanceTest` | The templates of the exporters are inherited settings: registered with the exporter, the book beats the nearest folder beats the user's version beats the default, and a template nobody changed is not passed to the exporter. |
| `extensions`, `domain`, `notifications` (1.7.0) | `ResourceReaderAccessTest`, `NotificationServiceTest`, `NotificationSettingsEditorTest`, `LorebookEntryEditDialogTest` | What the readers of a published book may read of the files of its parts (`ResourceService.readForReader`); what can notify, what the user chose and when a finished run is worth a notification, and the notifications tab; the dialog that edits one lore entry from the lorebook tab. |
| plugin tests of the Audiobook and of the `http-hooks` library (1.7.0) | `marginalia/plugins/audiobook/src/test` (`PieceSplitterTest`, `LabelingTest`, `ScriptFromLabelsTest`, `ConversionQueueTest`, `ResourceAudioStoreTest`, `FfmpegTest`, `SpeechBatchTest`, `ChatterboxBackendTest`, `HiggsComfyBackendTest` (a fake ComfyUI), `HiggsTextTest`, ...), `marginalia/libs/http-hooks/src/test` (`HookRunnerTest`, `HttpTest`, `UrlGuardTest`) | Run in the plugin or library folder with `mvn test` (they need the application installed, `mvn install -DskipTests`). The queue tests use a fake speech server and a fake store; the ones of `FfmpegTest` run only where ffmpeg is installed. The splitting of the text, the labelling prompt and its windows, the script, the cache keys and the levelling of the loudness need no server. |
| `gpu`, `ui`, `ui.widgets` (GPU locks, 1.9.0) | `GpuArbiterTest`, `GpuServiceTest`, `GpuLockSelectTest`, `SettingsChangesTest` | `GpuArbiterTest` (no application): the turns of one GPU, sticky locks, the release steps only when another lock comes, `maxConcurrent`, the FIFO queue, a failed step, a GPU used outside. `GpuServiceTest` (a fake HTTP server for the steps): only an administrator sets them up while every user sees the choices, encrypted headers, the steps of a change of lock, deletes, `unload`, and an AI with a lock that holds the GPU for its request (also when a function it called asks the same model). `GpuLockSelectTest`: attaching the box keeps the chosen lock. `SettingsChangesTest`: a change deep inside reaches the nearest listener. |
| `annotation`, `generation`, `backup` (phrase watch list, 1.9.0) | `PhraseMatcherTest`, `PhraseWatchServiceTest`, `PhraseWatchStepTest`, `BackupFoldersTest`, `BackupExportInheritanceTest` | `PhraseMatcherTest` (no application): case, whole words, white space, curly quotes, regular expressions, entries that are off or can't be used, the cap of hits and an expression that backtracks forever. `PhraseWatchServiceTest`: how the lists of the user, the folders and the book add up, a scan with templates that makes nothing twice (a dismissed note included), the scan of the branch, entries that are refused. `PhraseWatchStepTest`: the step after a generated part, on and off. The backup tests: the list of a folder in a backup, the combined list written into an export with inherited settings. |
| plugin unit tests (1.9.0) | `place-provider` (`PlaceIndexTest`), `lorebookvcs` (`LoreEntryRevisionTest`, `LorebookVCSServiceTest`), `character-tracker` (`CharacterBookTest`, `CharacterTrackerServiceTest`), `authorsnote` (`AuthorsNoteServiceTest`), `sidequery` (`SideQueryServiceTest`), `lore-generator` (`LegacyNameToolsTest`, `LoreGeneratorServiceTest`, `DefaultsTranslationTest`), `reviewer` (`ReviewerServiceTest`), `gemma4toolsfix` (`Gemma4ToolsFixExtensionTest`), and a `<Name>LocalizationTest` in each of these but `gemma4toolsfix` | Plain JUnit, no Spring: run in the plugin folder with `mvn clean test` (the application installed first). The search of the places (names without accents, plurals and aliases of the types, the country by code or part of its name, the distance and the compass direction, the bundled data); a lore entry revision taken, applied and compared, an imported history matched to the entries by uuid, name and order, the SillyTavern revision history; the characters and relationships of a book, their text in the prompt and where it goes, the icons and the colors of the cards; where the author's note goes; the name of a side query tab and when it is asked for; the name categories saved before the tool dialog; which reviewer profile a book uses; which models get the Gemma 4 tool role. A service that needs another one gets a `java.lang.reflect.Proxy` of its interface set into the field. The localization tests check that every text is a constant with every translation and the same placeholders. |

The tests added in 1.4.0 check, besides what the names say: `GenerationOptionsTest` (a generation with another model and protocol than the book's, the book untouched), `PermissionServiceTest` and `PermissionsDialogTest` (the permissions and their window), `LazyContextMenuTest` (a menu filled when it opens) and `LazyBranchTest` (which parts of a long story the window has loaded while it slides), `TextDiffTest` and `WordDiffTest` (the sentence and the word diff of the review), `RoundStatsCollectorTest` (what a streamed answer says about how it went: finish reason, cache, reasoning, llama.cpp timings), `AgentCleanupTest` (an agent, its runs and the working copy are deleted, restored and purged together) and `ConcurrentTransactionsTest` (read-write transactions take the SQLite write lock, read-only ones do not wait for them). `test/TestImages` makes small pictures and `test/AgenticRequestAttributes` the request context of a run, for the tests of the agents.

Not covered by automated tests: the Vaadin UI (apart from `LLMSnapshotTest`, `HelpAssistantWidgetTest`, `ResourcesPartTest`, `BranchSearchTest`, `WorkspaceStateTest`, `AIDialogExtensionTest`, `TabDockTest`, `LorebookPreviewTest`, the lorebook editor tests and `InvalidExtensionsWarningTest`), the user interface and the model calls of the bundled plugins (their unit tests cover the logic without a model), and the desktop launcher
(the [CI smoke test](packaging.md#continuous-integration) only checks that the packaged app starts).

## Test bases

```mermaid
classDiagram
    PlatformTestBase <|-- MarginaliaTestBase
    PlatformTestBase <|-- OwnedCrudContract
    MarginaliaTestBase <|-- GenerationTestBase
    OwnedCrudContract <|-- ExtendableCrudContract
    MarginaliaTestBase <|-- BackupTestBase
    GenerationTestBase <|-- LorebookActivationTest
    ExtendableCrudContract <|-- ProtocolCrudTest
    TemplateTestBase <|-- MacroRenderingTest
    class PlatformTestBase {
        +llm
        +createUser()
        +login()
        +createAI()
    }
    class MarginaliaTestBase {
        +quietBackgroundWriters()
    }
    class GenerationTestBase {
        +ai
        +protocol
        +newManuscript()
        +generate()
        +onEvent()
    }
    class TemplateTestBase {
        +context
        +data
        +render()
    }
```

`TemplateTestBase` doesn't start Spring. Pick the lightest base that works:

| Base | Spring | Use for |
|---|---|---|
| none | no | Pure units (`CronScheduleTest`, `SillyTavernEntryConverterTest`, `FlywayMigrationTest`). |
| `TemplateTestBase` | no | Anything rendered by `TemplateServiceImpl`. |
| `PlatformTestBase` | yes | Code of the platform: users, permissions, AIs, jobs, inference, GPU locks; in the platform module it runs on the platform alone. |
| `MarginaliaTestBase` | yes | Services, repositories, backups, cleanup of the application. |
| `GenerationTestBase` | yes | Anything that needs a real generation. |
| `OwnedCrudContract` / `ExtendableCrudContract` | yes | The CRUD contract of a new entity. |

### MarginaliaTestBase

`test/PlatformTestBase` (users, permissions, the login, AIs on the mock LLM; in the platform's test-jar) and
`test/MarginaliaTestBase` on top of it (the background writers of the application, the sizes of the books and the
activity, see `quietBackgroundWriters`) start the context `classpath:META-INF/spring/test-application-config.xml`.
Each module has its own file of that name: Marginalia's (`src/test/resources/META-INF/spring/`) imports the production
`application-config.xml`, the platform's is the platform alone ([below](#the-platform-s-tests-and-the-test-jar)). Both
add `TestContextPostProcessor`, which

- removes the OSGi framework (`OsgiServiceImpl`) and the instrumentation agent (`RuntimeInstrumentationInitializer`;
  the classes of the application are woven by the build, so their hooks run in the tests and call the
  `ExtensionService` of the Spring context, which has no decorators),
- points `Configuration` to a new folder `target/test-home/ctx-<random>/` instead of `~/.marginalia`,
- makes `TestUserService` the user service: it hashes passwords with one round of SHA-256 instead of PBKDF2 (600,000
  rounds), which was close to half of the time the tests spent, every test creates a user. `authenticate` works as
  usual; `PasswordHashTest` keeps the real PBKDF2 hash covered.

Everything else is the production wiring: the services, Hibernate, Flyway migrations, the session-scoped current
user. The base class gives you:

| Member | |
|---|---|
| `userService`, `aiService`, `inferenceServices` | Autowired services; autowire any other bean in your test. |
| `currentUser` | The session-scoped `User` bean - the "logged in" user of the test. |
| `llm` | A [mock LLM scenario](#the-fake-llm-server) for this test method. |
| `uniqueName(prefix)` | `prefix-1a2b3c4d`, for names that must not collide with other tests. |
| `createUser()`, `createUser(login, password, admin)` | Saves a user; an ordinary user also gets the permission `CREATE_AI` (as the users of an installation from before the permissions have it; `AISharingTest` and the help tests give `HELPER` the same way). |
| `setPermission(user, type, granted)`, `updatePermission(user, type, consumer)` | Create or change a `Permission` of a user straight in the repository (no administrator is needed, unlike `PermissionService.save`). |
| `loginAs(user)`, `login()`, `loginAdmin()` | Makes a user the current user, like a login in the UI (`login()` and `loginAdmin()` create one first). The services that only administrators can use (cleanup, database backups, user delete / unlock / clear password, extension install) need `loginAdmin()`. |
| `createAI()` | Saves an OpenAI-compatible inference provider pointing to `llm`. |

Each test method runs in its own mock HTTP request and session (`@SpringJUnitWebConfig`), so session-scoped beans
start empty: call `login()` before using a service that needs the current user.

#### The shared database

Spring caches the application context, and with it the database, for the whole test run. All test classes that use
`MarginaliaTestBase` share **one** SQLite database. Write tests so that they don't depend on what else is in it:

- create the data a test needs in the test, with `uniqueName(...)` for anything looked up by name;
- assert on the entities you created (`contains`, `doesNotContain`), not on totals (`hasSize`);
- operations that work on the whole database (cleanup, database backups) must only assert on their own data - see
  `CleanupServiceTest`.

When a test really needs an empty database or changes global state, mark it with `@DirtiesContext`. The next test
then gets a new context with a new folder and database:

```java
@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)   // starts on an empty database
void lastAdminIsProtected() throws Exception { ... }

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)        // changes the shared backup schedule
class DatabaseBackupScheduleTest extends MarginaliaTestBase { ... }
```

The first context of a JVM costs about 20 seconds (Spring, Hibernate, Flyway; measured as the start of one test class on the first machine of the table, a context built later in a warm JVM should cost less), so use it sparingly.

#### The application folder

Each context gets its own folder under `target/test-home/` with the database, data, backup and extension folders.
They are not deleted after the run, so you can open a test database with any SQLite tool after a failure. `mvn clean`
or deleting `target/test-home` removes them.

### GenerationTestBase

`test/GenerationTestBase` runs real generations through every pipeline step (see
[Generation pipeline](generation-pipeline.md)). Before each test it logs in a new user, creates an AI pointing to
`llm`, saves a chat-completion protocol and sets the mock's fallback answer to `"generated"`.

| Member | |
|---|---|
| `ai`, `protocol` | The saved provider and protocol. |
| `newManuscript()` | An unsaved book with `ai`, `protocol` and minimal templates: user prompt ``, master template ``. Save it with `manuscriptService.save(...)`. |
| `generate(manuscript, instructions)`, `generate(manuscript, turnInput)` | Generates a new part and waits up to 30 s for the end. Returns a `GenerationRun`. A third argument `answer` (`boolean`) is what the author answers to the questions of the generation (outdated summaries: *No* stops). |
| `onEvent(event, manuscript, action)` | Runs `action` when this book's generation reaches a pipeline `Events` value; removed after the test. |

`test/GenerationRun` is the `GenerationListener` that stands in for the story editor. It records the streamed
response and reasoning, errors (`getErrors()`) and simple errors (`getSimpleErrors()`, the messages the UI shows in a
notification), warnings (`getWarnings()`), the created part (`getMessage()`), and the outcome (`COMPLETED` or `CANCELLED`). Questions the
pipeline asks the user (`askQuestion`) are answered *yes* unless the test says otherwise (`answering(false)`, or the `generate(manuscript, instructions, answer)` overloads of `GenerationTestBase`); they are recorded in `getQuestions()`.

```java
class MyGenerationTest extends GenerationTestBase {

    @Test
    void instructionsReachTheModel() throws Exception {
        Manuscript book = manuscriptService.save(newManuscript());
        llm.reply("The lighthouse was dark.");

        GenerationRun run = generate(book, "The keeper climbs the stairs.");

        assertThat(run.await(TIMEOUT)).isEqualTo(GenerationRun.Outcome.COMPLETED);
        assertThat(run.getErrors()).isEmpty();
        assertThat(run.getResponse()).isEqualTo("The lighthouse was dark.");
        assertThat(llm.lastCompletionRequest().getLastMessage().content())
                .contains("The keeper climbs the stairs.");
    }
}
```

To look at the pipeline state in the middle of a generation, capture it in an event listener. `LorebookActivationTest`
reads the activated entries this way:

```java
AtomicReference<List<LorebookEntry>> activated = new AtomicReference<>();
onEvent(Events.AFTER_PROCESS_LOREBOOK, book,
        e -> activated.set(e.getProperty(GenerationProperties.ACTIVATED_LOREBOOK_ENTRIES)));
generate(book, "...");
```

Listeners are global (`StoryGenerationService.addEventListener`); `onEvent` filters by book and always calls
`chain.next()`, so a failing assertion inside the action doesn't stop the generation. Assert after `generate` returns,
not inside the listener - an exception in the listener only ends up in the log.

### CRUD contracts

Every entity that belongs to a user has a CRUD test built from `crud/OwnedCrudContract`. The contract contains the
tests; a subclass only says how to make and change an entity:

| Method | |
|---|---|
| `service()` | The entity's `OwnedService`. |
| `newEntity()` | A new, unsaved, valid entity (referenced entities may be saved). |
| `assertCreated(loaded)` | Checks the fields set by `newEntity()` after a reload. |
| `modify(entity)` | Changes some fields. |
| `assertModified(loaded)` | Checks the changes after a reload. |

The inherited tests check identity and owner on create, find by id / uuid / for user, update (creation date kept,
modification date moved), soft delete (hidden from all `find*ForUser` and `findAll*` methods), hard delete, isolation
between users, and that saving as another user keeps the owner.

Entities extending `ExtendableEntity` use `crud/ExtendableCrudContract`, which adds the persistence of plugin
attributes (`getAttributes()`): nested JSON, changes and removals, unrelated updates, and `saveWithoutEvent`
(used by restore). Put at least one `@ExtendedAttribute` field into `newEntity()` and `modify()`, so the inherited
tests also cover the extended fields. `crud/ProtocolCrudTest` is a short, complete example.

When you add an entity (see [Database & migrations](database.md)), add its `<Entity>CrudTest`.

### TemplateTestBase

`templates/TemplateTestBase` creates a `TemplateServiceImpl` directly, without Spring, with a deterministic context:
the clock is fixed at Sunday, 15 March 2026, 14:30:45 UTC, random macros use a seeded `Random`, and the template data
describes a scene in the middle of a story (POV *Alice*, characters *Alice, Bob, Carol*...). One `data` object is
shared by all `render(...)` calls of a test, the way lorebook entries of one generation share their variables.

`MacroLorebookFixtureTest` renders `src/test/resources/macro-test.json`, a SillyTavern lorebook whose entries
document their expected output. When you change macro behaviour, update the fixture and the expectations together.

## The fake LLM server

`test/llm/MockLLMServer` is a small OpenAI-compatible server on `127.0.0.1` with a random port, built on the JDK's
`HttpServer`. One shared server lives for the whole test JVM (`MockLLMServer.shared()`); each test gets its own
**scenario** with its own base URL, `http://127.0.0.1:<port>/<scenario-id>/v1`. A provider created with
`createAI()` points to the test's scenario, so tests never see each other's requests or answers.

After every test `MarginaliaTestBase` also ends every run of the static registry `Runs` (`Runs.reset()`), so a window or a
generation a test left open holds nothing in the next one (`RunsTest`, `GenerationRunsTest` and `BookWindowsTest` test the registry,
see [Services](services.md#the-runs-and-what-they-hold)).

It answers:

| Endpoint | |
|---|---|
| `GET /models` | The scenario's model list (default `mock-model`; change with `llm.models(...)`). |
| `POST /chat/completions` | Streaming (server-sent events) and non-streaming chat completions. |

### Programming answers

Chat completions are answered in this order:

1. queued responses - `llm.enqueue(...)` or `llm.reply("text")`, one per request;
2. the responder function - `llm.respondWith(request -> ...)`, if set and it returns a response;
3. the fallback - `llm.fallback(...)`;
4. otherwise HTTP 500 *no response programmed*.

`MockLLMResponse` builds one answer:

```java
MockLLMResponse.text("Hello world")                        // one content chunk
MockLLMResponse.chunks("Hel", "lo").chunkDelay(ofMillis(50))
MockLLMResponse.split(longText, 20)                        // chunks of 20 characters
MockLLMResponse.text("answer").withReasoning("thinking")   // reasoning chunks first
MockLLMResponse.text("answer").withReasoning("...").reasoningField("reasoning")  // instead of reasoning_content
MockLLMResponse.text("cut").finishReason("length")
MockLLMResponse.error(429, "slow down")                    // OpenAI-style error body
MockLLMResponse.chunks("a", "b", "c").disconnectAfter(2)   // stream ends abruptly
MockLLMResponse.text("answer").usage(120, 8)               // token counts in the last chunk (only if asked for)
MockLLMResponse.text("late").waitFor(latch)                // held until the latch is released
MockLLMResponse.toolCall("add", "{\"a\":1}")               // the model calls a function; .andToolCall(...) adds one
```

`waitFor(latch)` is the tool for "while generating" states: the request is received, the pipeline waits for the
stream, and the test can stop the generation or inspect the state before releasing the latch.

!!!warning Retries
The `openai-java` client retries 408, 409, 429 and 5xx responses. A queued error response is consumed once per
attempt, so enqueue it several times (or use `fallback`) when a test expects the error to reach Marginalia. The server
closes the connection after every response, so a retry never reuses a stale pooled connection.
!!!

### Inspecting requests

Every request, including model listing, is recorded:

| Method | |
|---|---|
| `llm.getRequests()`, `llm.getCompletionRequests()` | All requests / chat completions, in order. |
| `llm.lastCompletionRequest()` | The last chat completion; fails the test if there was none. |
| `llm.awaitCompletionRequests(n, timeout)` | Waits for `n` completions - for asynchronous callers. |
| `request.getMessages()`, `getMessages("system")`, `getLastMessage()` | The chat messages (`role`, `content`). |
| `request.getPromptText()` | All messages as `[role]\ncontent` - handy for `contains` assertions. |
| `request.getBody()`, `getRawBody()`, `getModel()`, `isStream()`, `getApiKey()` | The raw payload. |

For code that calls an `InferenceService` directly (without the pipeline), `test/InferenceCollector` is a callback
that pulls the whole stream and waits for the end (it also records the `onFunctionCall` reports).

## The plugin smoke test

`extensions/smoke/PluginSmokeTest` takes the built plugin JARs and runs them the way the application does at startup: they are copied into the extensions folder of
the test home, an `OsgiServiceImpl` is made by the Spring context of the tests (the bean `TestContextPostProcessor` leaves out, so it gets the real services) and
started on a real Felix framework. Each plugin must

1. **verify**: `ExtensionService.verifyExtension` follows every `registerDecorator` call to the `@Extendable` method it names and checks the arguments, locals, fields
   and return values the decorator asks for (the check that keeps an extension that does not fit from starting, see [Verification](plugins/extendable.md#verification-before-loading));
2. **load**: its `onExtensionLoad` passes and it is among the loaded extensions;
3. **unload cleanly**: after it is stopped (`stopExtension`, as *Admin → Extensions → Stop*) nothing of the application points into it any more. `PluginLeakFinder`
   walks the `OsgiServiceImpl`, every singleton of the context (the target behind a Spring proxy) and the static fields of their classes, through the fields of the
   application's classes, collections, maps, arrays, `AtomicReference`s and `Optional`s, and reports each object, class or lambda that the class loader of a plugin
   defined, with the path it was found on (`commandService.commands[my-plugin][0]`). A decorator, a listener, a command, a provider or a setting that was not
   unregistered shows up there, and with it the class loader it keeps alive. Weak references are not counted; other libraries (Hibernate, Vaadin) are not entered.

The report names each plugin with what went wrong (the verification report, the log lines of a failed load, the leaks). The test needs the built plugins, so it is
skipped unless `-Dmarginalia.plugins` names them: a folder of JARs, or the `plugins` folder (then the JAR in the `target` of each). After `mvn install -DskipTests` in the
root (the application, the libraries and the plugins):

```sh
mvn clean test -Dtest=PluginSmokeTest -Dmarginalia.plugins=plugins
mvn clean test -Dtest=PluginSmokeTest -Dmarginalia.plugins=plugins -Dmarginalia.plugins.only=reviewer,sidequery   # some of them (start of the JAR name)
```

The `plugins` job of `desktop.yml` runs it on the JARs it built, so a change of the application that breaks a plugin fails the build. The context is thrown away after
the class (`@DirtiesContext`): what the plugins registered does not reach other tests.

## Coverage

`mvn clean test -Pcoverage` runs the tests with the JaCoCo agent (the `coverage` profile of `marginalia/pom.xml`; the agent goes in through the `argLine` property,
empty without the profile) and writes the report to `target/site/jacoco/` (HTML, XML, CSV). It is a report only, there is no minimum. The weekly `health.yml` workflow
runs it and puts the line and branch numbers into its summary, see [Continuous integration](packaging.md#healthyml).

## Expected errors in the log

Tests of failure paths make the code log errors on purpose. To keep them out of the test output (where they look like
real failures) and to assert on them, capture the logger with `test/ExpectedLog`:

```java
try (ExpectedLog log = ExpectedLog.capture(ExtensionServiceImpl.class)) {   // or capture("extension.my-plugin")
    ...
    assertThat(log.errors()).anyMatch(m -> m.contains("broken"));
}
```

While the capture is open, the logger's events are recorded and not passed to the console; `errors()`, `warnings()`
and `atLeast(level)` return the messages, `entries()` the full events with their exceptions.

## Instrumentation tests

The `instruct` tests check the bytecode that makes `@Extendable` methods extensible (see
[Plugin development](plugins/extendable.md)):

- `ExtendableMethodVisitorTest` transforms fixture classes from `instruct/fixture/` with `instruct/Instrumenter` -
  the same transformation the agent applies, without an agent - and checks that the result verifies, keeps the class
  schema, behaves like the original and exposes arguments and locals to decorators.
- `BuildTimeWeaverTest` runs the weaver of the build on a copy of the fixture classes: the `@Extendable` ones get
  the hooks and the `@Woven` mark, verify and call decorators, a second run changes nothing, a class compiled again
  is woven again. In a Maven run it also checks that every `@Extendable` class of the application was woven by the
  build, and it covers when the agent is installed (`woven.properties`, `marginalia.extendable.agent`).
- `RuntimeInstrumentationTest` installs the real agent (the fallback for classes the build did not weave; test
  classes never are) into the test JVM and checks classes loaded both before and after the installation
  (`fixture/agent/`), a `@Configurable` class with a generic supertype, and that a class marked `@Woven` is left alone.
- `ExtensionVerifierTest` runs the [extension verification](plugins/extendable.md#verification-before-loading) on
  the extensions of `fixture/verify/VerifyFixtures` (decorators that are valid, ask for things that don't exist, or
  can't be followed) against the decorated `VerifyTarget`. Their class files are packed into a JAR on the fly and
  served by a stand-in `Bundle`. Decorators must be anonymous classes with the context calls inside them, as in a real
  extension - a decorator that delegates to a helper class would not be checked. One test runs the same extensions
  against a woven copy of the targets: the verifier reads the locals of a woven class from the hooks.
- `PublicAPISignatureTest` checks the [`@PublicAPI`](plugins/extendable.md#the-public-api) of every instrumented method
  of every `@Extendable` class of the application against the compiled classes (`target/classes`). It reads them with
  ByteBuddy's type pool and the local variable table (`PublicAPISignatures`), so the application classes are not
  loaded or initialized, and it needs the classes compiled by `ajc` like the application. It checks the fields a
  plugin reads (`@PublicAPI(from, type)` on a field, opt-in) the same way. A failure names the method or field and
  prints the annotation it needs.

The fixtures are compiled with the same `-parameters` and `preserveAllLocals` options as the application; if you
change the compiler settings in `pom.xml`, these tests tell you whether extensions still see names of arguments and
locals.

## The layer check

`LayerDependencyTest` (`architecture`) guards the split of the platform from the application (`TODO.REFACTOR.md`).
`src/test/resources/layers/layers.txt` gives every main class a layer, `platform` or `app`: a line names a package or a
class relative to `com.github.enerccio.marginalia` (`.` is the base package itself), the longest matching name wins
and nested classes go with their outer class. The test reads the compiled classes with ASM (`ClassRemapper` collects
every class named in signatures, bodies, annotations and constants) and fails when

- a class has no layer (add a line to the map),
- a platform class names an application class that `layers/allowed-leaks.txt` does not list (make it a registration
  point or an interface of the platform, or correct the map), or
- a listed reference is gone (delete its line: the list only shrinks).

After a change of the map, `-Dlayers.update=true` rewrites the list from the classes (it writes to
`src/test/resources`, so run it from the `marginalia` folder).

The shared test code of the platform (`PlatformTestBase`, the mock LLM in `test.llm`, `ExpectedLog`, `ComponentTree`,
`TestContextPostProcessor`, `TestUserService`, the CRUD contracts) is compiled in the platform module, where an
application class does not exist, so it needs no check of its own.

## The platform's tests and the test-jar

The platform module (`marginalia/platform`) has its own tests: the units of its classes and the Spring tests of its
services (users, permissions, AIs and their sharing and limits, inference and the gate, tools, templates, GPU locks,
jobs, the database backup schedule, notifications, the CRUD of its entities, the virtual file system of the agents with
its file and image tools...), about 870. They run on **the platform
alone**, the way another application on the platform would start it:

| File (`marginalia/platform/src/test/`) | |
|---|---|
| `resources/META-INF/spring/test-application-config.xml` | The Spring XML of the platform: its beans (the platform's part of Marginalia's `services-config.xml`), the data sources, Flyway, the container beans (`LocalizationImpl` with the `L` bundles, `SessionPoint`), and `TestContextPostProcessor`. The example of what an application writes for itself: the platform ships no Spring XML. |
| `resources/platform-test/persistence.xml` | The platform's entities and `TestUserSetting` (the minimal `BaseUserSetting` an application would have). |
| `resources/platform-test-migration/V1__platform.sql` | The platform's tables (Flyway location `classpath:platform-test-migration`, set on the `configuration` bean as its `DatabaseCheck.Schema`), written from Marginalia's schema. `db/PlatformSchemaTest` in Marginalia's tests checks that every table there has the same columns and indexes in a database migrated by Marginalia's migrations: a change of a platform table in a Marginalia migration needs the same change here, as a new migration. Hibernate's temporary tables (`HTE_*`) are left out, Hibernate makes them. |
| `logback-platform-tests.xml` | The logging of these tests, named by the surefire configuration and kept off the class path (in a reactor build Marginalia's tests see the platform's test classes folder). |

Run them from the root: `mvn clean test -pl marginalia/platform`, or both modules with
`mvn clean test -pl marginalia/platform,marginalia` (with `-Dbuild.dir`, the platform's go to `<build.dir>-platform`).
A test of a platform class that needs Marginalia (a book, a generation, the commands it registers) stays in
Marginalia's tests.

The platform's POM makes a **test-jar** of these classes (`marginalia-platform-<version>-tests.jar`, installed with the
platform), and Marginalia's tests depend on it (`<type>test-jar</type>`, scope `test`): `PlatformTestBase`,
`MockLLMServer`, `InferenceCollector`, `ExpectedLog`, `ComponentTree`, `TestImages` and the CRUD contracts come from
there. The platform's context file is left out of the jar, so an application's tests start their own: an application
on the platform (Joi) depends on the test-jar the same way and puts its wiring into its own
`META-INF/spring/test-application-config.xml`. Building Marginalia alone in `marginalia/` takes the test-jar from the
local repository, so install the platform after a change of its tests (`mvn install -DskipTests -pl marginalia -am`).

## The dataset book

A test that needs a book of a real size (a long story with summaries, annotations, versions, translations, the data of plugins, a lorebook and a picture) does not build one: the repository has one, *Unregistered*,
the same book that the user manual offers as the [example book](../user/getting-started/example-book.md). It is two files in `src/test/resources/workset`: `book.zip` (the archive of the app with the picture, 6.1 MB)
and `lorebook.json` (a backup only links its lorebook, by a fixed uuid, so the lorebook is imported first). It was written by the harness described below, with the real generation loop and a model (Claude Haiku), not by a script that
imitates one, so it holds what the application leaves behind: prompts of up to 86k tokens, the versions of a redraft, the notes of an annotation, the passages of four translators, the audiobook scripts of the 100 parts (who speaks each piece, labelled by Haiku; nothing is spoken).

**Loading it** is `WorksetFixture.restore(backupService, lorebookService, name, true)` as the logged in user (about 5 seconds on an M4, a bit more on slower machines). Restore **once per class**, not per test: the database is shared by the
classes of a JVM and each test method has a session of its own, so keep the result in `static` fields and let the first test make it (`LargeWorksetTest.restoreOnce`); the tests of the class only read it. A test that changes the book
restores its own copy (`LargeWorksetMigrationTest`). The restore stamps everything with today; a test that needs the history of months (statistics) spreads the creation dates itself.
The context normally gets a fresh folder (`target/test-home/ctx-*`); with `-Dmarginalia.test.fixedHome=<folder>` (`TestContextPostProcessor.FIXED_HOME_PROPERTY`) it uses that folder and its database, which is how the harness continues
on the book of an earlier run. To run work as another user on a thread of its own, put a `MockHttpServletRequest` session on the thread (`RequestContextHolder`) and `loginAs` there (`LargeWorksetSoakTest.asUser`).

The tests do not assert times except against a limit that no machine we use comes near (a guard against something that became quadratic); they print what they measured (`[large workset]`, `[soak]`).

**Rebuilding it** is `tools/workset_run.sh` (the `WorksetBuilder` class: not a test, it does nothing without `-Dworkset.build=true`, and its name keeps it out of the suite). It needs the plugins built (`mvn install -DskipTests`
of the app, then `mvn package` in the four plugins it starts) and the `claude` command line tool, and it is resumable: every answer of the model is cached by a hash of the request in `work/harness/answers`, so a rerun asks only
for what changed. The folder `work/` is not in git. The skeleton (the beats, the lorebook, the languages, the knowledge seed) is in `work/dataset`. All the properties, the steps of the loop, the block close and what the review file
holds are in `marginalia/src/test/java/com/github/enerccio/marginalia/workset/README.md`. Two steps work on the finished book: `label` (the Audiobook labels every part with the book's model through the bridge, nothing is spoken; the bridge hands the JSON schema of a request to the `claude` tool, so a structured answer has the shape the application asked for) and `audio` (parts are spoken on a speech server that you started yourself, for a listening test; the audio is not kept in the repository). A run writes `work/harness/export/` (`book.json`, `book.zip`, `lorebook.json`); to replace the fixture copy `book.zip` and
`lorebook.json` into `src/test/resources/workset` (every replacement adds 5 to 6 MB to the history of the repository, so do it for a reason) and run `LargeWorksetTest`, whose numbers (the 103 parts, 31 summaries and so on) then change.
`ExportRoundTripCheck` (`-Dworkset.roundtrip=true`) imports a fresh export the way the application does and compares what comes back.

The text, the lorebook and the two constructed languages of the book are dedicated to the public domain (CC0); the picture is a public domain painting, see the manual page.

## Checklist for a new test

- Name it `<Subject>Test` and put it in the package of the area it tests; Surefire runs every `*Test` class.
- Extend the lightest base that works ([Test bases](#test-bases)).
- Create your own data with unique names; don't depend on what other tests left in the shared database.
- Don't call real models or other network services - program `llm` instead.
- Assert with AssertJ, with `.as("...")` where the failure message would otherwise be unclear.
- Capture expected error logs with `ExpectedLog`.
- A new entity gets a CRUD contract test; a new migration is covered by `FlywayMigrationTest` automatically (it runs
  all migrations and validates the schema against the entities).
- A bug fix comes with a test that fails without the fix, where the area is testable without the UI.
- Run `mvn test` before opening a pull request - CI runs the same command.
