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 (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/:
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:
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 (
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.
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 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), otherwise UI classes and
@Configurablebeans miss their dependencies; -
add
-XX:+EnableDynamicAgentLoading -Djdk.attach.allowAttachSelf=trueto the VM options of the JUnit run configuration template if you runRuntimeInstrumentationTest.
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
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
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 only checks that the packaged app starts).
Test bases
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:
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 (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 theExtensionServiceof the Spring context, which has no decorators), -
points
Configurationto a new foldertarget/test-home/ctx-<random>/instead of~/.marginalia, -
makes
TestUserServicethe 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.authenticateworks as usual;PasswordHashTestkeeps 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:
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:
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). 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".
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().
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:
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:
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), 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).
It answers:
Programming answers
Chat completions are answered in this order:
- queued responses -
llm.enqueue(...)orllm.reply("text"), one per request; - the responder function -
llm.respondWith(request -> ...), if set and it returns a response; - the fallback -
llm.fallback(...); - otherwise HTTP 500 no response programmed.
MockLLMResponse builds one answer:
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.
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:
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
-
verify:
ExtensionService.verifyExtensionfollows everyregisterDecoratorcall to the@Extendablemethod 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); -
load: its
onExtensionLoadpasses and it is among the loaded extensions; -
unload cleanly: after it is stopped (
stopExtension, as Admin → Extensions → Stop) nothing of the application points into it any more.PluginLeakFinderwalks theOsgiServiceImpl, 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,AtomicReferences andOptionals, 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):
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.
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:
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):
-
ExtendableMethodVisitorTesttransforms fixture classes frominstruct/fixture/withinstruct/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. -
BuildTimeWeaverTestruns the weaver of the build on a copy of the fixture classes: the@Extendableones get the hooks and the@Wovenmark, 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@Extendableclass of the application was woven by the build, and it covers when the agent is installed (woven.properties,marginalia.extendable.agent). -
RuntimeInstrumentationTestinstalls 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@Configurableclass with a generic supertype, and that a class marked@Wovenis left alone. -
ExtensionVerifierTestruns the extension verification on the extensions offixture/verify/VerifyFixtures(decorators that are valid, ask for things that don't exist, or can't be followed) against the decoratedVerifyTarget. Their class files are packed into a JAR on the fly and served by a stand-inBundle. 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. -
PublicAPISignatureTestchecks the@PublicAPIof every instrumented method of every@Extendableclass 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 byajclike 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.txtdoes 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:
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. 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>Testand put it in the package of the area it tests; Surefire runs every*Testclass. -
Extend the lightest base that works (
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
llminstead. -
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
FlywayMigrationTestautomatically (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 testbefore opening a pull request - CI runs the same command.