Testing
Every task that adds or changes user-visible behavior ships three layers, written before the code:
- Service or integration test:
@SpringBootTest, real database. - UI integration test:
@UiTest, no browser. Fast; runs in./gradlew test. - Browser test: Selenide and Jmix Masquerade against a running app in headless Chrome, tagged
e2e. Runs in./gradlew e2eTest.
Both commands must pass before a UI-touching task is committed: ./gradlew clean test e2eTest.
Appointments are proved on the sample by AppointmentsTest (booking coupled to the move, conflicts, two
simultaneous bookings with the second waiting on the database lock and no sleep, reschedule and reassign, cancel and
decline, whole days, a repeated key, access) on HSQLDB and with -Pjcm.db=postgres and -Pjcm.db=sqlserver,
AppointmentsLocksModeTest (the same again on HSQLDB with hsqldb.tx=locks), AppointmentConfigTest (the
entries' startup refusals), BookableResourceParserTest (the resource files) and AppointmentsE2eTest (the button,
the dialog, the card and a refusal in the browser).
The agenda is proved by ResourceAgendaTest (pure: a day's cut, back to back never counted together, across
midnight on both days, a cancelled one holding no hour, a day the clocks change), BookableResourceParserTest
(agenda-roles and its refusals), AgendaTest on the sample (who may open a resource and the exported read held to
the same rule, a record the caller may not read told as Booked and nothing more, a cancelled one shown apart to a
reader and not at all to anyone else, the order, the edges of a day and a range, the person's zone, 31 days) on
HSQLDB and with -Pjcm.db=postgres and -Pjcm.db=sqlserver, AgendaUiTest (the page and its role, the address, the
words for cancelled, everything sent to the browser for someone who may not read a record searched for its title,
people, ids and case number, a resource not offered, and the agenda over the booking dialog with what was typed
kept) and AgendaE2eTest (a planner by keyboard on the page and from the dialog, Escape and Back, focus returned, no
sideways scroll at 390px, the accessibility scan light and on a phone and dark). AgendaE2eTest writes its pictures
to JCM_SHOTS_DIR, or build/reports/agenda. The test accounts keep no zone, so a UI test reads the zone from
CurrentAuthentication, never the machine's. AgendaTest also holds the exported read to 31 days and 1900 to 2999,
a 31-day appointment that started a month before the day read, and both reads inside system work a person started
and under a job-role token. AgendaCostTest (with StatementCount, sharing ChartCostTest's context) pins the
cost: 62 bookings over 31 days in three statements for a reader (one for the bookings, two for the one case type)
and fewer for someone who reads none, the same as one day; five with a second case type among the bookings; the
exported read's history in one statement; a page opened by address reads the bookings once; "Show cancelled" reads nothing. ResourceAgendaTest
places the hour marks on a 23- and a 25-hour day. AgendaUiTest checks the day fields and the titles against
DateFormats (the sample's and a written d MMM yyyy), an address with a day no agenda can show, and a cleared
day; RecordActionBarUiTest the booking dialog's date fields and the day the agenda opens on. AgendaUiTest also holds the
record's appointments card to the agenda's words for a day and its hours, and AgendaE2eTest types a day in the
application's format into the agenda's day field (and the ISO form) and into the booking dialog, and books with it;
it types the hour both ways, 2:00 PM as the sample writes it and, in a second test under a 24-hour date-time
(set with DateFormats.commit and put back), 14:00. DateFormatsTest cuts the time out of Korean, Chinese and
time-first formats and picks a time field's clock. AgendaTest books two case types on one resource for someone
who reads some of the records and not others (the second type is put in the running registry for the test: the
sample declares one). AgendaRowRulesTest (the rows profile, on RowRulesFixture) holds the agenda to row rules
written in role files: a booking on an appeal the person's rows do not reach is "Booked" on the page and through
Appointments.agenda, one they reach is told in full, and one called off out of reach is not told. The Agenda page
is on CaptionsTourE2eTest's tour.
UI integration tests as a specific user
@UiTest(authenticator = X.class), where X extends AsUserAuthenticator from jcm-test-support and overrides
username(). The class and its constructor must be public. Seed the user first with UserSeeder.seed(...), which
creates users, resource roles and row-level roles and is safe to call repeatedly.
@UiTest(authenticator = MyTest.AsWorker.class)
@SpringBootTest(classes = {MyApplication.class, FlowuiTestAssistConfiguration.class, MyTestSeed.class})
@ActiveProfiles("test")
public class MyTest {
public static class AsWorker extends AsUserAuthenticator {
@Override protected String username() { return "worker-a"; }
}
}
SeedUser.withRoles(username, password, roleA, roleB) gives a user several resource roles. Test every role a
component ships the way a customer will assign it: alone, with only the host's minimal UI role.
A UI integration test does not check view permissions when it navigates: a user without the view policy still
opens the view. Prove a role grants a screen with Jmix's AccessManager: apply UiShowViewContext(viewId),
UiMenuContext(menuItem) and CrudEntityContext(metaClass) and assert each is permitted (the sample's
AdminRoleAloneSupport.permits does this), or log in through a browser test.
Browser tests
- Tag the class
@Tag("e2e")and use@SpringBootTest(webEnvironment = RANDOM_PORT)with profilestestande2e; thee2eprofile setsjmix.ui.ui-test-mode=true. - Prefer one
@SpringBootTest(classes = ...)list and one set of properties for every browser test class: a class that differs starts a second web application in the same JVM, which costs a startup. Each application installs its own security context strategy into Spring Security's staticSecurityContextHolderwhen it starts, so the first one would then answer every page with a 500 (Authentication is not set) and the sign-in page never appears.jcm-test-supportprevents that: itsSecurityContextStrategyListener, registered inMETA-INF/spring.factoriesfor every Spring test, points the holder at the strategy of the test's own application before each test (SignInAfterAnotherContextE2eTestin the sample pins it). - Log in through the real login view with
LoginPage.loginAs(user, password). - Reach a case band button through
com.jcm.testsupport.CaseBand(click(id),offered(id, name),says(id, badgeId, text),folded(id)): past three secondary buttons, or on a narrow window, the band puts a button into its More menu (#caseActionsMore, entry#caseMore-<id>), hidden in the page, so a test that clicks the id alone passes on one width and fails on another. See the design system's "The case band at every width". - Select by the words a user sees, never by a caption key: JCM's own entities show their captions (
Title), no longer the key (Task.title), in screens, queue headings, field history and the data dictionary. - A timeline kind chip (
timelineFilter-<kind>) cycles shown, highlighted and hidden, and the choice is kept in the signed-in user's settings across records and sign-ins: press twice to hide a kind, readdata-state, and press Reset (timelineFiltersReset) at the end so the next test as that user starts from every kind shown. - Wait for the browser's address, never read it once: Vaadin writes it with
history.pushStateorreplaceStateinside asetTimeout, after the response is drawn, so the next screen (or a saved case's workspace) can show while the address is still the old one (/newafter the first save). UseSelenide.webdriver().shouldHave(WebDriverConditions.urlContaining(path), timeout)before asserting onWebDriverRunner.url()(the sample'sCaseScreenE2eTest.addressEndsWith); a slow runner, such as the two-server run behind Traefik, finds the gap. - Sign-in through a provider is a context of its own: the sample's
OidcSignInE2eTestruns under theoidcprofile (the OIDC filter chain replaces the login form, so it cannot share thee2econtext), starts Keycloak in a container fromkeycloak/jcm-realm.json, draws the realm users' passwords and the client's secret when it starts and sets them through Keycloak's admin API, so no file holds them; the issuer and the secret reach the context through@DynamicPropertySource. It is@EnabledIf("com.jcm.testsupport.Docker#present"): skipped, never passed, without Docker. The test signs in on Keycloak's own form (#username,#password,#kc-login) and signs out through the application's user menu, then expects Keycloak's form again, which proves the provider's session ended too; it also opens/login(Spring Security's provider page under OIDC, not the application's form) and sends a stray authorization code to/login/oauth2/code/jcm, which lands on/login?error. - The sample's
LdapSignInE2eTestis the LDAP twin, under theldapprofile (the LDAP authentication manager stands in front of the database's): it starts OpenLDAP (bitnamilegacy/openldap:2.6, arm64) withldap/jcm.ldifcopied into the image's custom LDIF folder, waits forslapd starting(the port opens earlier, during the image's setup, before the admin's password is set), draws the admin's password and every user's when it starts and sets the users' through an admin bind, so no file holds them; the URL and the manager's password reach the context through@DynamicPropertySource. It signs in on the application's own form withLoginPage.loginAs, moves a user between groups with an admin bind and puts them back in@AfterEach, and reads the form's error from#login's shadow root,vaadin-login-form-wrapper's[part="error-message"](LoginFormError), to assert the refusal sentence. The "administrator sets the default after the first sign-in" case is shared with the OIDC test (FirstSignInDefault.proved, the provider's sign-in and sign-out passed in; it first asserts the "has not signed in yet" refusal for a user who never signs in). Both provider tests assert thejcm_SignInRoleGrantrows across three sign-ins (an administrator's assignment kept, a granted-and-assigned role staying when the grant goes). - Which account a sign-in uses: both provider tests sign in as a directory or realm user named
adminandAdmin(LDAP: entries the test adds and removes,uid=adminlisted in the officers' group; OIDC: realm usersadminandadmin-capital, whose token saysAdmin: the test points the profile scope'susernamemapper at the attributejcm-usernameand gives every realm user that attribute,Adminforadmin-capital, so one mapper writespreferred_username(two mappers writing one claim run in no fixed order); the test reads the ID token through a direct grant to prove the spelling) and asworker-a, a database account's name: each is refused with its sentence, admin's assignments unchanged and no grant rows. Both prove the first sign-in's identity row (jcm_UserIdentity) and the row reused at the next sign-in, and an administrator's assignment taking effect in the session (the switcher offers its job role).ProviderAccountsTest(plaintestcontext) callsProviderAccounts.claimandlinkdirectly: reserved names, database accounts in any case, another issuer, subject or source, linking. Clean the identity rows a test makes in@AfterEach. - The sign-in lockout counts in the database, so a test that locks a username deletes its
jcm_SignInFailurerows in@AfterEach, or later tests and other contexts on the same database find it locked.SignInLockoutFormTest(plaintestcontext) authenticates throughsec_AuthenticationManagerwith a newX-Forwarded-Forand remote address bound on every try, proves the lock, and proves the unlock by moving the failure rows back by the lock's duration (data, not a hook);SignInLockoutTest(jcm-identity) unit-tests the rule and the settings. - Usernames in test queries: SQL Server's
Latin1_General_100_CI_AS_SC_UTF8ignores letter case, soe.username = ?1withAdminalso findsadmin. A test that removes or counts the rows of one spelling filters the loaded rows by the exact spelling in Java as well ("Admin".equals(u.getUsername())), or its@AfterEachdeletes the break-glass admin and every later test that signs in as admin fails. HSQLDB shows the same matching withsql.ignore_case=truein the URL: start the test JVM with-Dmain.datasource.url=jdbc:hsqldb:mem:sample_test;hsqldb.tx=mvcc;sql.ignore_case=true(for instance throughJAVA_TOOL_OPTIONS) to try such a test before the release gate. - Break-glass accounts: both provider profiles set
jcm.identity.local-accounts=true.OidcSignInE2eTestprovesadminsigning in at/login/localand the sign-in lockout locking that route after five wrong passwords (worker-a, whose failure rows@AfterEachremoves);LdapSignInE2eTestproves the lockout on the LDAP form (ldap-manager), and provesadminstill refused on the application's form and signing in at/login/local, and a password-less account andsystemrefused there. The route's absence with the switch off isLocalRouteOffE2eTestin the plaine2econtext (no provider; the view is not registered,/login/localshows the application's form). Each setting value is one context: do not flip it in a test. - The grant recorder and the admin password are tested in the plain
testcontext without a provider:SignInGrantsTestcallsSignInGrantRecorder.recorddirectly and reads the rows;LocalAccountsTestcallsLocalAdminPassword.apply(password, required)directly (the refusals, the rotation, a drawn test value) and restores{noop}adminin@AfterEach, and constructs the two assertions with a stubbedExternalSignInprovider. NoSpringApplicationBuildertest starts a context for them in the sample. The admin password isjcm-core's:LocalAdminPasswordSettingsTest(jcm-core) binds the variable, andscripts/test-new-app.shstarts a scaffolded app withoutjcm-identityon theprodprofile and expects theJCM_ADMIN_PASSWORD must be setrefusal. - HTTP-level tests that need the port but no browser join the same context: the sample's
HealthEndpointsTestis@Tag("e2e")with the browser tests' annotations and asks the actuator withjava.net.http.HttpClient. It takes readiness down withSampleTestSeed.ReadinessSwitch(as.test.readiness-switch, aBlocksReadinessassertion that passes until the test sets its staticfailing, cleared in@AfterEach), never with a context of its own. Every sample context therefore lists that assertion, passing. Thee2eprofile setsjcm.health.readiness-cache=0so the flip is seen at once;JcmReadinessTestproves the cache with a hand-movedClock, never a sleep. - Gradle (the scaffold writes this for you): exclude the tag from
test; registere2eTestthat includes it, depends onvaadinBuildFrontend, and setsvaadin.productionMode=true. The tests run against the production frontend bundle, as customers do; development mode adds a dev-only overlay that pollutes the page. - Use an in-memory database for tests so sequences and rows do not persist between runs; assert relative numbering.
- A browser test that passes at once proves nothing until you have made it fail: remove the thing it checks and watch it go red, then restore.
- Work a queue's board in a browser test through a card's Move to button (
cardMove-<row id>, thenboardMoveTo-<column key>), the keyboard route, rather than a drag; a UI test callsQueueGrid.getBoard().drop(row, columnKey), which does what a drop does. Get next and the buttons on a record's own screen go by their ids too (queueGetNext,onrecord-<queue>-<button>); see contract. - Test two people taking work at once (Get next) in both of HSQLDB's modes: the test profile's in-memory database
runs MVCC, as PostgreSQL behaves, and the sample's and demo's file databases run LOCKS, where the race ends in a
deadlock the database breaks rather than at the unique key (the sample's
GetNextLocksModeTestrunsGetNextTestagain withhsqldb.tx=locks). - Test in
LOCKSmode too whatever makes a row in a transaction of its own and then holds it in the caller's: inLOCKSmode a write holds its whole table, so that transaction waits for ever on the caller's once the caller has written the table, both on one thread.AppointmentsLocksModeTestandAssignmentRulesLocksModeTestrun their suites again withhsqldb.tx=locks;jcm-core'sTableWideWritessays where a write holds the table, and there the row is made in the caller's transaction after a write that takes the table. HSQLDB's wait for a lock is not interrupted by a test's timeout: the hung-test guard ends such a run and prints every thread.
Configuration variants for tests
When a fixture changes child records, choose its allowed and refused operations from the contract for role-scoped child assignees, minimum child counts, and moving chosen children to another record. Keep the unchanged child-type rules in the fixture too; an override replaces the whole definition.
Tests add configuration; they never shadow a main file by accident. Fixtures that only add items (a test queue, a
test rule) go in the test resources' own jcm/ folder, with codes of their own (q.test.titled). A test that needs
a variant of a main file (another case type layout, a test jcm.yml with an extra inbox tab) puts the whole file
under an override root and names that root in the test profile:
# src/test/resources/application-test.properties (the sample's)
jcm.config.overrides=classpath*:jcm-test/
A file under jcm-test/ replaces the main file of the same kind and code (jcm-test/case-types/case.appeal.yml
replaces jcm/case-types/case.appeal.yml), or adds one; jcm-test/jcm.yml replaces the app's jcm.yml. Each
replacement is logged at INFO naming both files. Two override files for one code are refused, as in the main roots.
A profile with a different variant gets a root of its own (the sample's form-rules profile uses
classpath*:jcm-form-rules/; its oidc profile reads classpath*:jcm-oidc/ for the Keycloak mapping and its
ldap profile classpath*:jcm-ldap/ for the OpenLDAP mapping, each before jcm-test/). See contract.
The sample's storage-s3 and storage-azure profiles are contexts of their own for StorageS3Test and
StorageAzureTest: each sets jcm.storage.kind, the bucket or container and its own in-memory database
(sample_storage_s3, sample_storage_azure, so rows whose file references name s3 or azure never meet the
other contexts); the endpoint and the keys, or the connection string, come from the running container through
@DynamicPropertySource, which jcm-storage reads when its beans are built (not in its environment post-processor,
which sees only the profile's file). Every other sample context has the storage starter installed and no kind set,
which is how local with the starter is proven.
jcm-test/identity/idp.test.yml (provider: oidc, unmapped: refuse) is read by every sample context, so the
studio's Roles area has a Granted at sign-in column to show; its values start test- so they never meet the oidc or
ldap profile's file (one value in two files of a provider is refused), and it grants only job.case-worker and
case-worker, which no parity fixture removes. No issuer is set outside the oidc profile, so the Roles area says
the file is not in use there ("would give ... once jcm.identity.oidc.issuer is set"); OidcSignInE2eTest proves the
in-use wording in the context that has the issuer.
Row rules in tests
Role files are fixed and read only from the classpath, so a test's role files with rows live in a root of their
own, a second normal root that only the tests of row rules name (the sample's rows profile, applied after test):
# src/test/resources/application-rows.properties
jcm.config.locations=classpath*:jcm/,classpath*:jcm-rows/
jcm.config.overrides=classpath*:jcm-test/,classpath*:jcm-rows-over/
They cannot sit in the test resources' own jcm/roles: a role file that writes rows on a case type's entity stops
every context whose job roles name a generated jcm-scope-... role of that case type, and the other tests' job role
job.unit-tester does. jcm-rows-over/ replaces that job role with one that names none.
jcm/access.yml is one fixed file, so a test cannot add a default-deny entity to it without taking that entity
from every other test's people. RowRulesFixture.DefaultDenyAppeals gives the context an AccessFiles bean
(@Primary) whose file is the sample's with default-deny: [Appeal]; the key itself is read and checked by
AccessFileTest and AccessFileCheckTest. A second server started by a test names the same class as a source.
A person of these tests holds the Java role case-worker, for screens and entity permissions, and one rows-...
role file beside it, never by includes: on a default-deny entity a role file may not include a role that reads it
with no rows. What the Java role grants on a managed entity adds nothing, so every action a test expects is listed
in the role file.
A workflow move by a role's own rows needs a transition that names a role file: jcm-rows-over/workflows/ holds the
sample's appeal workflow with review-note and worker-note added, each named for one rows-... role. The test
entities test_TwinFolder, test_TwinBinder and test_TwinPage are a record with two composition parents.
RowRulesAbsentTest runs in the plain test profile, where no role file writes rows, and holds what such an
application must keep: no policy, the same statements, and default-deny from an access file as written.
RowRuleCheckTest holds a fixture per startup refusal: role files as text through RoleFileParser, compiled by
RowRules.compile and checked by RowRuleCheck.problems, with job roles, workflows and automations given as text
through ConfigFiles.ofTexts. A new refusal gets its fixture there, asserting the file and line.
What startup refuses or warns of over a reference into a managed entity is a method of RowRuleCheck each
(namedThroughRuled, unsecuredReferences, orderedThroughRuled, listsOfRuled, rulesThroughRuled,
filteredThroughRuled, unqueryableReadRules), given the entities, the set of managed entity names and the files as
text, so a fixture needs no entity of its own; each also asserts that the application as it stands is refused
nothing. A test role that reads an entity by a predicate (@PredicateRowLevelPolicy, READ) stops the startup of
any test context in which that entity is managed, held or not. Where the same test sources serve contexts with and
without rows, keep the role's annotated class outside the packages Jmix scans and give it by a test
RowLevelRoleProvider that is absent where a configuration root writes rows or default-deny (the samples'
InMemoryRuleRoles), and seed nobody as holding it there.
SystemWorkBoundaryTest.noComponentReadsAHostThroughTheUnconstrainedManager fails for a component file that reads
an application record through an unconstrained data manager or an entity manager and is not in HostReads: add it
there with the gate it stands behind (the secured read or RecordAccess question asked first) or the reason it is
in order. A file that no longer reads so is taken off.
Letters by language and complete destinations in tests
LetterLanguagesTest (sample) starts with the override root jcm-letter-languages/ beside jcm-test/. Its
case.test-shared declares four parties on the claimant rows of test_SharedCase, by kind: primary and
representative (required languages, complete for print and email), witness (a language as a plain field) and
guest (a default). SharedClaimant carries the columns for it (907-test-claimant-destinations.xml). The
languages, Zorvian and Quelish, and every text are invented; a fixture for this never holds a real language's notice.
lt.notice is the plain pair, lt.pack the composed pair (a cover and a static sheet each, read back from the PDF
after LetterComposing.runDue()), lt.served asks complete-for: print, lt.open is for the parties that require
nothing. Sends run through Sends.run as a seeded writer; refusals of a letter file are published as a candidate
(Candidates.publishChecked) and read at letters/lt.x.yml:<line>, those of a party through CaseParties.parse. The
rollback test runs a set, a letter and a required send as one action list in one transaction and reads the
record, the letters and the rows afterwards. The refusal catalogue holds letters/language-without-for,
variants-without-language, variant-unknown and complete-for-undeclared. A test that needs a party to require
languages needs a root of its own: parties are read at startup, and the sample's main case type requires none.
The root also holds a party on the case itself (desk), the declared action serve (a set, a note, a
start-clock, a letter and a required send, run through DeclaredActions.run and read back as the record, its
notes, clocks, domain events, letters, documents and pieces), and lt.bundle, whose variant needs a document the
record has none of. Candidates.publishChecked(generation, context, root, changes) publishes into a root other than
jcm-test/ and carries that root's letter folders; Candidates.checkNextStart runs the second pass a studio publish
makes for a staged case type. LetterLanguageStartupTest (own-jvm) starts the sample with
jcm-letter-languages-required/, a whole small root, and reads the refusal. LetterLanguagesE2eTest (e2e,
single-server) opens the generated case screen's Letters tab and the template screen at 1440 and 360 pixels, light
and dark, and the list in a 340-pixel column with the rail's class, since a generated screen gives Letters a tab and
never the rail; pictures go to JCM_SHOTS_DIR or build/reports/letter-languages. LetterLanguagesTest watches
LetterComposer, LetterFiles and CommunicationRecords through spy beans to say what was stored and in what
order, never by counting files in the shared store. EntityCaptionKeysTest reads every module's messages.properties
on the classpath and refuses a caption keyed by an entity's name (jcm_Task.title), which Jmix never asks for. A job role narrows a user's
roles, so it signs in as SampleTestSeed.LETTERS_ADMIN for the template screen.
Field history in tests
Field changes are kept by the entity log as a save flushes, so a test saves through DataManager (or the case
screen) and reads the timeline as the user it checks: timeline.timeline(binding, record) filtered on kind
field-change (FieldChangeTimelineSource.KIND). Newest first; a record's creation is the oldest entry, Created.
Prove the security rules with a user whose role leaves a field out of view: (the change is withheld, with empty
values) and one who cannot read a reference's target (AuditHistory.UNOPENABLE). A test that counts a record's
timeline entries counts its Created entry and one entry per save that changed a kept field; a test that removes
records in clean-up leaves their kept entries behind, which nothing reads but the Removed records screen. Bulk JPQL
and SQL in a test's clean-up are not captured. The demo's DemoFieldHistoryTest, the sample's FieldHistoryTest
and CaseControlsUiTest (the chips and the expandable list), the browser test DemoFieldHistoryE2eTest and the
scaffold's generated <Name>CaseScreenUiTest (one audited change) show each layer.
Reference-list fields in tests
A fixture's reference-list field takes an item of its declared list, active today, even when the fixture is saved
through UnconstrainedDataManager or as the system (RefListMembershipGuard): pick the item by list and code
(e.list.code = ?1 and e.code = ?2), never by code alone, and use a retired item only as a value already stored. To
test a record holding an item that has since ended, store it while the item is active, then end-date the item. The
sample's RefListMembershipTest covers each save path, with test_RefTagged for a collection of items. A test
needs no new items in a shipped list either: use one of its shipped items, or a private list and a private field,
so no other test that counts the list's items sees a change.
Correcting a document's type
DocumentRetypeTest (sample, documents profile) proves the service: what a correction keeps, the read-only actor,
unknown and no-longer-offered types, a withdrawn file, a copy read before someone else's change, two corrections sent
at once from two threads (exactly one saved), and a history that leaves out a type its reader may not read.
DocumentRetypeUiTest drives the row's button and the dialog, DocumentRetypeChoicesUiTest a refused choice with
others left (as a person offered three types), DocumentRetypeReaderUiTest shows a reader no control,
and DocumentRetypeE2eTest corrects a type on the generated screen with the keyboard alone.
DocumentRetypeLostUpdateTest makes the lost write happen every time: a listener on the history row's
EntitySavingEvent, in a test configuration and so a context of its own (@DirtiesContext after the class), changes
the document in a REQUIRES_NEW transaction after the service has read it, so the database refuses the correction's
write; use the same hook for any other versioned row whose lost update needs proving without threads or sleeps.
LostUpdateTest (jcm-attachments, no Spring) holds which failures count as a lost write: build EclipseLink's
OptimisticLockException there through an anonymous subclass and setQuery, since its own factories need a session.
A history's limit is tested by saving its rows directly (a thousand in one SaveContext), not by a thousand
corrections. A test that removes a
record's attachments in clean-up removes its jcm_AttachmentRetype rows too (e.entityId = ?1).
A field that names a document revision
DocumentRevisionTest (sample, document-revision profile) proves the rule on the server. The profile adds a case
type of test entities, a report file (test_ReportFile) whose reviews (test_QualityReview) name one of its
documents in report (@DocumentRef(types = {"EVIDENCE", "MEDICAL"}), what a model field of type: document
generates) and follow wf.test.review (submit, return, approve; submit and approve ask {revision: report}). Its
people are DocumentRevisionSeed's: an author, a reviewer, and an author who reads the restricted type MEDICAL.
It covers a review keeping its revision through return and resubmission while the same name is uploaded again (ids,
bytes and SHA-256 compared, Documents.revisions in order), each refusal's sentence (another record, a missing id,
withdrawn, pending, infected, another type, a type the person may not read), the unconstrained data manager under
system work, a document withdrawn after it was named (the record saves, the moves refuse, whyNot says why), a
reviewer who may not read the document (no answer, closed), Documents.choices, a named document's type correction
refused with no history kept, and the leaf's and the field's refusals at load.
The races are made to happen, not waited for. A withdrawal that commits first runs in a REQUIRES_NEW transaction
inside the move's beforeMove, after the move holds the record and before it reads the document. The other order
uses two threads and two latches: one thread makes the move (or the save naming the document) in a transaction it
keeps open, the other withdraws (or corrects the type) and is shown still waiting after 1.5 seconds, then the first
commits and the second's outcome is asserted. Use the same shape for any rule that holds a row with RowHolds.
Since the review of that work the class also covers: the leaf's reads and a move made from its dialog; the value
formatted for its reader (and for who may read neither the document nor its record); a letter's text, the printed
page and the history of a case's own document field; a child two levels down; a child moved under another case; a
document moved away and corrected on its new record; typeChoices for a named document; a refusal that says nothing
of a record its actor may not read; a filed document's name, size and SHA-256 held against every save; and three
more races: a withdrawal waiting for a save, a save waiting for a correction, and two saves naming the same two
documents in opposite fields at once, eight rounds. DocumentRevisionScanTest adds a DocumentScanner bean (a
context of its own): a file is named only once passed, and a file never scanned, named by a row written before the
scanner, does not hold the leaf and is then found infected. Both classes pass on PostgreSQL and SQL Server
(-Pjcm.db=postgres, -Pjcm.db=sqlserver), races included. The test entities are a case (test_ReportFile, with an
optional cover), its reviews (report, annex) and their remarks (exhibit), in changelog 908; they are no
case type outside the document-revision profile, where a type correction therefore asks nothing of them.
A rule learned here: inside a data store listener never load a record through a data manager to ask whether it can
be read, and never hold an unversioned record by a locking read. A load inside a save reads the record again over
what the save changes, and the change is lost without an error. Ask before the save starts (beforeEntitySave),
hold by a write that changes nothing, and prove it with a save of a case and its child in one SaveContext, in
both orders, asserting every change of both (aCaseAndItsChildSavedTogetherInEitherOrderKeepEveryChange).
DocumentRevisionCostTest (with StatementCount, so a context of its own) pins the cost, and passed with these
numbers on HSQLDB, PostgreSQL and SQL Server: a column of fifty documents on one case in 3 statements once the list
has told its keys, and at most 12 for ten documents when it has not; 20 values of 4 documents written by a job on a
thread with no request in 5 (each document once, the case's files once); a stored document's save 1 (the read of its
row), a type correction where no field could refuse it the same 1, and a record's save on a case type with no
document field 0. Count inside the sign-in (as(user, () -> StatementCount.during(...))), since signing in reads
the user and their roles. DocumentRevisionStartupTest starts the sample for real with one more override root and
expects the refusal of a queue sorted by a document column.
Two things not to do. Do not add a second @JmixModule to a module's test sources to bring an entity into one
start only: the build writes the generated persistence descriptor under that module's package, stops writing the
sample's, and every other test's entities are then missing or stale (it passes on a warm build folder and fails on
a clean one). And do not rely on AttributeChangesProvider in a data store listener that runs after others: a
flush before it empties the change set. DocumentRevisionSeed.flushing turns on hooks that call
EntityManager.flush() (a loadValue does not flush: it runs with flush mode COMMIT); the tests that set it prove
a changed SHA-256 and a move are still judged.
A third: a query hint given to a data manager load does not reach EclipseLink unless it is one of the five Jmix
applies (eclipselink.read-only is stored and ignored), and a record loaded by a data manager inside a
TransactionTemplate is already detached, so changing it proves nothing about what a later load does to a record
the transaction holds. To prove that, take the managed instance from the EntityManager
(StoreAwareLocator.getEntityManager("main").find), change it, make the read, and assert em.contains and the
stored value after the commit (readsMadeWhileATransactionHoldsAChangedManagedRecordLeaveItsChangeToBeWritten);
for a save, let a lifecycle hook set the value on the merged instance and save the case and its child together in
both orders (aDocumentAHookSetsOnTheCaseOrOnAChildSavedWithItLosesNoChangeOfTheSave).
The startup refusals of DocumentRefs.onReady are tested by their functions (unusable, misdeclared, each branch
with its sentence), not by a real start, and cannot be otherwise in the sample: a model file is build input
(ModelFiles.KIND is fixed at build, so an override root cannot add one), a model's entity must also exist in the
metamodel with exactly its shape or ModelMetamodelCheck stops the start first with its own message, the sample's
entities are written by hand and match no model file, and an entity brought in for one start alone needs a second
Jmix module, which the paragraph above forbids. The demo, whose entities are generated, is where a real start of
these refusals belongs once it has a document field.
The test entities are a case (test_ReportFile, optional cover), its reviews (report, annex), their remarks
(exhibit, versioned, two levels down) and its loose notes (paper, no version). Changelog 908 was edited in place
while this work was in review; it is a test changelog that no stored database has run.
DocumentRevisionRowsTest (profiles test, document-revision, document-revision-rows, a context of its own)
proves the field where a role file rules rows. Its root jcm-document-revision-rows/ holds one role file,
rows-report-worker, which reads the report files not titled "sealed…" and their reviews not titled "private…";
the author's role writes no rows and reads every one. Each question is asked twice, outside any transaction and in
the middle of one (bothWays), and must be answered alike: a sealed file is not read; of a document filed on it the
worker gets no revisions, no choices, no picker offer, A document you cannot see as its label, on a screen and in
what they export; naming it in a review of a file they read is refused in the words an unknown id gets; a review
they read that names a document since moved to a sealed file keeps it through their save, and their change of the
field, to another document, to none or to an id nothing has, is refused in one sentence, by the secured and by the
unconstrained data manager; a type correction refused for a private review says nothing of the review. To test an
application's own document field under row rules, do the same: give one person a role file with rows, file a
document on a record outside them, and assert on Documents.choices, Documents.revisions, the formatted value
and the save, as that person, inside a TransactionTemplate too.
DocumentRevisionUiTest opens the review's side panel on the generated case screen (ChildOpener.open) and reads
the picker: offered(), the item label, statusText(); over a document the person may not read the picker is
read-only and namesHidden() is true. DocumentRevisionE2eTest chooses a revision with the
keyboard alone, sees the server refuse the save once that revision is withdrawn, chooses the other and saves, with
two accessibility scans; it closes the refusal's notification before the second scan, since the notification's own
close button has no accessible name. ModelParserTest, SnapshotsTest and JavaWriterTest cover the model field:
its keys and refusals, its indexed key column without a foreign key, and the generated attribute. A test that removes
a case's attachments removes the records that name them first, or leaves them: the field has no foreign key.
Mailbox intake in tests
Test intake against com.jcm.testsupport.mail.TestMailbox (jcm-test-support): an IMAP server in the test JVM
(GreenMail) behind a fault proxy, a user and password made up for each start, plain IMAP on the loopback
(security=none, allowed outside prod, so no scanner is asked for). No real mail server, host or address is ever
needed; every sender and subject in a test is invented.
@SpringBootTest(properties = "jcm.config.locations=classpath*:jcm/,classpath*:jcm-mailbox/")
@Import(ReceiptCommitFault.class) // for failCommitOfNext / loseCommitAnswerOfNext
class IntakeAcceptanceTest {
static final TestMailbox MAIL = TestMailbox.start("intake"); // the file's connection name
@DynamicPropertySource
static void mail(DynamicPropertyRegistry r) { MAIL.settings().forEach((k, v) -> r.add(k, () -> v)); }
@Autowired ApplicationContext context;
@Test
void twoAttachmentsAreTwoRecords() {
MAIL.deliver(TestMessage.builder().attach("a.pdf", "application/pdf", pdf).attach("b.pdf", "application/pdf",
other).build());
TestMailbox.Poll poll = MAIL.pollNow(context); // jb.mailbox.poll through the job runner, started by test
assertThat(MAIL.folder(TestMailbox.DONE)).hasSize(1);
}
}
Keep the mailbox file in a test root of its own (src/test/resources/jcm-mailbox/mailboxes/, added by
jcm.config.locations) so the application's other tests start without it. MAIL.reset() empties the folders and
disarms the faults between tests. Failure cases and how to create each one:
| Case | How |
|---|---|
| Missing attachment bytes | MAIL.faults().cutFetch(200) (a cut BODY[], MESSAGE_INCOMPLETE), or TestMessage.withoutClosingBoundary() (PART_INCOMPLETE) |
| Failure on the second part | a record validator that refuses the second attachment's record (RECORD_REFUSED); nothing of the message is created |
| Commit failure | MAIL.faults().failCommitOfNext(); an uncertain commit: loseCommitAnswerOfNext() |
| Source move failure | MAIL.faults().refuseNext("MOVE") |
| Uncertain move response | MAIL.faults().loseAnswerOf("MOVE") (ACKED_GONE on the next poll) |
| Repeated delivery | MAIL.deliver(same) twice |
| One bad message among good ones | a broken message between two good ones; after eight polls it waits on "Work needing attention" for Retry or Hold |
A failed reading or move waits before it is retried (one minute, then longer); a test makes it due by setting
NEXT_ATTEMPT of JCM_MAILBOX_ATTEMPT or JCM_MAILBOX_ACK to null. The demo's MailboxIntakeTest,
MailboxRecoveryTest, MailboxRefusalsTest, MailboxNothingLeaksTest and MailboxSpikesTest show each. A real
server's behaviour is MailboxServerBehaviourTest, on com.jcm.testsupport.mail.DovecotMailbox (Dovecot 2.4.5 in a
container, MOVE on or off; @EnabledIf("com.jcm.testsupport.Docker#present")).
Saves of several records
A check on the save path that loads a record of the same save drops that record's changes with no error, and only when the store happens to write that record first, so a test that saves one record, or two in the lucky order, never sees it. Three things keep it out:
- Every composite save is tested in every order, asserting every changed attribute of every record. The store
writes new records first and then stored ones in the order given, and a listener hears each just before its own is
written, so build
new SaveContext().saving(a, b)andsaving(b, a). Give the children both ways: loaded on their own (application code) and merged into one data context with their parent (a screen); only the first lost data before the fix. The sample'sSaveSetKeepsEveryChangeTestsaves a case, a decision and a party in all six orders both ways, a changed appeal with a new decision, with a decision moved under it, with a parent the person may not update (refused in both orders, though the copy saved alongside would pass the rule), a decision checked against the filing date the same save gives its appeal, a data context, the record API in one transaction, and two saves of one transaction. The demo'sSharedRecordSaveSetTestsaves a changed person with the case repointed at them, away from them, left on them and newly made for them, and a hidden person the same save would make readable (refused);AccountSaveSetTestsaves a person's own account with their profile row, which the account screen does in one step and whose form asks about the person signed in. UnsavedChangesGuardrefuses detected loss by default (jcm.save.unsaved-changes=failis now the production default; sample and demo profiles no longer override it), so a listener that makes one fails the first test that saves its record after another of the same save, and the log names the load, the record and the lost attributes.UnsavedChangesGuardTestpins it with test listeners. Refused withUnsavedChangesLost, nothing of the save stored: a load by id through either manager, a query that finds the record, a load that reaches it through another record's fetch plan, a locking read, and a load inside a save made inside the save; and a caller that catches the refusal and saves more, or a listener that catches it inside the save, commits nothing. Let through, every change stored: a value query,RecordOperations.storedValue, a load in its own transaction, a load of a record the save does not write, a locking read afterPendingWrites.flush(), a load after a save made inside the save, a load after the save has flushed. No report where nothing was lost: anEntityChangedEventlistener loading a record a before-hook changed (the sample'sAppealActivitysets the last activity), a load in the caller's transaction after a save in its own (joinTransaction(false)), a load after the commit. And a record a listener changes after the guards were asked about it is asked about again by value.UnsavedChangesLogModeTestrunslog;UnsavedChangesLostUiTestsaves the generated case screen with a listener that reads the appeal again and reads the notification, the kept edit and the log;SaveSetCostTest(withStatementCount) holds a save of 500 stored records to the statements for each record of a save of 50 and of one alone, and to a minute; the demo'sDocumentFieldsTestsaves a document's fields with the document, and with its record, in both orders;ChildStateGuardTest.aSaveOfSeveralRecordsAsksAboutTheParentOnceItsRowIsHeldhas a save of two parties wait for the row of the appeal one is moved under, and refuses it by the title the holder gave the appeal meanwhile.- A new listener, validator, hook or rule read is written with a value query. When a test of yours fails with
"Nothing was saved. Reload and try again.", the ERROR line above it has the stack of the load: do not catch it, do
not reorder the test's save, and do not set the property to
login a test. A test profile of an application's own exercises the production default (fail) without an override.
To see what unmodified code does, run the same test with jcm.save.unsaved-changes=off on a branch without the
value reads. Run these classes on HSQLDB, -Pjcm.db=postgres and -Pjcm.db=sqlserver; the mechanism is the
persistence context's, not the database's.
Print batches and the delivery facade in tests
PrintBatchService.build(code) claims and makes the files in the calling thread, so an integration test needs no
waiting; the screen builds through PrintBatchBuilding, on the server's print thread, unless
jcm.correspondence.print.background=false. To prove what a stopped build leaves, call request(code) alone (the
batch stays BUILDING with its claims), move leaseUntil into the past and call sweep(); a late make(ticket) must
then change nothing. To fail a build after its files exist, refuse the save of a PrintBatchFileRow from an
EntitySavingEvent listener, armed once. To race two builds, start the second on another thread from an
EntitySavingEvent<PrintBatch> listener and join it: the first then meets the unique claim key and is told
PrintBatchService.RACED. A connector for a test is a PrintConnector bean in a @TestConfiguration, which must be
in the context before a file naming it is published.
A batch picks every prepared piece its file names, whoever made it, and these classes run beside every other on one
database, so a test that counts must be immune to what the others leave, without touching their rows.
PrintRoomSupport (sample) does three things. Its notice is a template of the print room's own
(jcm-test/letters/lt.test.print-room.yml), which no other class sends, and its print batch file
(pb.test.notices, split by party) picks that template alone. It puts together only its own letters
(LetterComposing.joinNow), never runDue(), which would turn every piece another class left WAITING into a
prepared one after any snapshot was taken (that is how four pieces once counted as eight). And it claims each piece
already prepared under a batch that does not exist. It removes every print batch row afterwards.
piecesAnotherClassLeftWaitingForTheirPdfAreNotTakenIntoABatchHere proves it. It also gives appeals whose notice goes out by print (fourNotices()), a
print operator (print-operator, with jcm-print-operator and no access to appeals) and a reader with no print or
delivery role. Assert a file's day from its name, not from builtAt, which reads back in the database's offset.
Record through Deliveries as a seeded user holding jcm-delivery-recorder, and read back with pieces or piece.
A mailing dated in the past needs a piece written before it: set the row's createdAt back, as DeliveriesFacadeTest
does. A provider's recording runs with no person: wrap it in SystemAuthenticator.withSystem.
| Class | Proves |
|---|---|
PrintBatchNamesTest, PrintBatchDefinitionsTest, PrintBatchPackagerTest (jcm-correspondence) | a value in a name is never a path; the file's refusals at their lines; split, names, page counts, the manifest and the ZIP, and a damaged piece named |
PrintBatchTest (sample) | split files with page counts and each piece once; only prepared pieces and none twice; a piece held before its file is made; two builds at once; a failed and a stopped build leave every piece as it was; each permission; logged downloads of the same bytes; marking sent records MAILED once and starts a clock; a piece held after the build is left out; void; a connector's failure, retry and acceptance; refusals on publish; the facade; a job |
DeliveriesFacadeTest (sample) | the role refused; the same occurrence once; pieces and ledgers read back; the correction stops a clock and the next mailing starts it; a provider's word |
PrintBatchE2eTest (sample, e2e) | the print room in the browser: waiting, build, void with a reason, build again, the download under the operator's session, mark as sent, accessibility scans, 1440 and 390 wide; no screen without the role |
An action's email is not sent by the move: it waits, QUEUED, until EmailQueue.sendQueued() or
EmailDispatcher.dispatchDue() looks at it, and what the transport was handed is in the sample's
RecordingEmailSender.sent (filter by the run's addresses; nothing is written to email_SendingMessage). Time is not
slept through: dispatchDue(asOf) looks at what is due by asOf, so a retry's backoff, a hold's recheck and ceiling,
an after-hours, an attachment's wait and a stale claim are each one call with a later moment, while what is recorded
still carries the real time. The seams, each the real path:
- A hold is a field the test sets on the stored record after the move (
dormant,withdrawalReason; thetestprofile's case type declaresdocket-holdondocketNumber = 'HOLD-EMAIL'for every action email of an appeal). - A transport failure is an address holding
RecordingEmailSender.UNREACHABLE; a server refusing an address outright isRecordingEmailSender.beforethrowingAddressException; something happening while the server has the message (a claim running out) isRecordingEmailSender.after. Both hooks are static: clear them afterwards. - A listener or an automation that throws is
EmailDispatchTest.FailingListeners.ARMED: a bean post-processor wrapsDomainEventsand refuses everycommunication.*event while armed. Disarm, thenannounceDue(asOf). A notice is parked by callingannounceDuewith later moments until its attempts are used; it is said again throughEmailDispatchAttention.act(id, "retry", stamp). Remove parked notices afterwards. - What a message carries failing to be read, and a server stalling between its claim and the transport, are
@MockitoSpyBean EmailAttachmentsansweringread(throw; or callexpireStaleClaims(later)first, then the real method). Reset the spy afterwards. - What an envelope keeps of its policy is changed by replacing text in
policySnapshot(unanswerable(was, now)): a later version ("v":2), a case type's limit ("held":{"maxSeconds":3600,...}), a condition no longer answerable. - The transport check is
EmailTransportCheckContextTest(jcm-email): anApplicationContextRunnerwith Spring Boot's ownMailSenderAutoConfigurationand the module's properties; a JNDI session is a testInitialContextFactorynamed injava.naming.factory.initial, cleared afterwards. - An envelope that cannot be decided is one whose
policySnapshotis saved as text that is no JSON; a condition that cannot be answered is one whose kept text names a field the entity has not (unanswerable(was, now)). - A message sent and not recorded is
CommunicationRecordTest.FailingRecord, which refuses the envelope's save once it carriesdispatchedAt. - A document not through its scan is its
scanStatesaved asPENDINGorINFECTED; one whose bytes changed or cannot be read is itsfilepointed at another stored file, or at none; a confidential one itsconfidentialorreadRolessaved. A letter's email variant is ajcm_LetterCompositionrow foremail, its file written as the composing runner writes it (a JPQL update).LetterComposing.runDue()takes a run of rows, and other classes leave theirs: call it until the letter has its PDF.
The template's email: is published as a change to a letter file that already has a stored row
(lt.appeal.party-notice, lt.test.plain), since a publish in a test commits no new template. The sample's
access.yml lists MEDICAL under emailed-document-types and not NOTICE. A test that leaves an envelope waiting
marks it outboxWaiting=false afterwards, or another class's pass sends it.
| Class | Proves |
|---|---|
EmailDispatchTest (sample; also run with -Pjcm.db=postgres and sqlserver) | an email waits for its turn and is recorded ACCEPTED at the sending, once; a move rolled back leaves nothing; a clock from the sending waits while held; a hold added since defers without reporting delivery; one of two holds lifted releases nothing; a person's hold and a declared one stand apart; a voided piece never goes; a refusing hold suppresses, with communication.suppressed; a plain email held by the case type's hold; a hold taken out of the file releases nothing; a hold or an obsolete rule that cannot be answered waits and is failed unsent; an envelope that cannot be decided is pushed back while the rest go; a held message past its ceiling; a listener failing on held, released, accepted, failed and suppressed changes none of them; obsolete discarded or kept; retries with backoff and failure after the attempts; four servers at once send one message; a send answering after its claim ran out; a party closed, gone, moved or with a bad address; one message per addressee and one refused address failing alone; the letter and the named documents carried; a withdrawn, unscanned, infected, retyped, confidential, changed or disguised document; a changed letter variant; a file never readable; a restricted type and the access file; a person never records mailed or delivered, and a failed piece released is tried again; who may read an envelope's history; the files' refusals at their lines; a clock from the sending starts while the automations fail, and events are heard in the order they happened; a notice parked, shown, refused to a stranger and said again; a read that throws and a claim ended before the handover leave the piece queued, never unknown; a policy of a later version holds; one person at one address gets one message; a held message is never dropped by default and is shown overdue; a case type's hold-max-hours and keep; a parked event skipped with a reason, those behind it said, a clock's word never skipped, a failed retry staying on the list; more than a batch of blocked notices and a failed clock's word still said (FailingListeners.CLOCKS fails what a clock hears) |
EmailDispatchRowRulesTest (sample, rows) | an email goes whoever reads its record; an envelope's history, the record behind an attention item and settling a piece in doubt follow the person's rows |
LetterLanguagesTest (sample) | a variant whose email: is not its letter's is refused at its line; an email address incomplete by the party's own complete when the message is sent is suppressed, and the other language's letter goes in its own message |
WorkAttentionEmailE2eTest (sample, e2e) | the emails on Work needing attention and the question Skip asks, 1440 and 390 wide, light and dark, with accessibility scans; pictures in JCM_SHOTS_DIR |
WorkAttentionUiTest (sample) | an action that needs a reason opens the question (view.choose(item, action); the dialog's parts are found on the page by id), does nothing with no answer, and hands the reason to its source |
CommunicationRecordTest (sample; also on PostgreSQL and SQL Server) | an answer that comes after a person recorded the piece as failed is kept on the piece and in the history, and a person's word is not recorded over one (recordIfStanding); a piece in doubt is told (communication.unknown), shown with its settle actions to one who may record them and with nothing of its record to a stranger, and settled from the list; a slow sender's answer kept for its piece after the envelope was claimed again; 130 held envelopes due before one fresh one, which goes in the same pass (drain() first, so the count is the test's own); a pass's message cap (dispatchDue(asOf, atMost)); two recipients are two envelopes and two messages; an address no message can go to is suppressed and never tried; two sweepers send once; a message sent but not recorded stands UNKNOWN once its claim runs out and is never sent again |
EmailTransportCheckTest, EmailTransportCheckContextTest (jcm-email), DeliveryOutcomesTest (jcm-correspondence), AccessFileTest (jcm-core) | the mail server's timeouts against the claim's lease; a start with no mail server, a blank host, the placeholder, a JNDI session with and without timeouts, the module's defaults and timeouts too long; what a person may record on an email piece, no source recording one as mailed, print pieces unchanged; emailed-document-types |
Leases and sweeps are made deterministic, never raced: both classes switch the background sweep off
(jcm.correspondence.print.sweep-delay=0) and call service.sweep() themselves; a lease is run out by writing its
end into the past, never by sleeping through it; and a renewal is proved by waiting, up to half a minute, to see
leaseUntil move (renewedPast), with the lease at its least, ten seconds. A long upload is a connector that waits
on a latch the test releases (TestConnector.RELEASE and ENTERED); DOWN makes it throw PrintNotTakenException,
BROKEN an ordinary exception, UNSURE PrintSendUnknownException, CRASH an Error (the server dying after
the stamp, the real path to a send the sweep must end), DEAF makes it wait through an interrupt, DURING runs
once after the provider has the file and before the connector answers, HOLD_STREAM has it open the ZIP and read a
byte before it waits and the rest after (LATE_READ keeps what that read met), and READ_FIRST has it take the whole
file before it waits, so only its answer is late. A lease lost mid-call is the lease run out by hand while the
connector waits: the next renewal fails, and the send gives up. A hung connector is the latch never released,
under send-timeout-seconds=10, the least the ten-second lease allows; a hung build is FailingStore.HUNG under
build-timeout-seconds=10. A file store that does not answer a removal is a @Primary PrintBatchFiles in a
@TestConfiguration (PrintBatchHandoverTest.FailingStore). Work on the server's own threads is asked for through
PrintBatchBuilding and waited for with within(...). A holder of one print permission is a test
role over it (PrintBuildOnlyRole, in the sample's test sources). A build that fails on one piece is made by pointing
the piece's letter at a stored file that is no PDF. What the sweep clears is planted by hand: a file in the store
named in zipPending, and a folder PrintBatchService.WORK_FOLDER + <batch id> + ... in the temporary directory.
| Class | Proves |
|---|---|
PrintBatchKeysTest (jcm-correspondence) | the claim's unique key and the batch number's are told apart as HSQLDB, PostgreSQL and SQL Server word them |
PrintBatchHandoverTest (sample) | a piece mailed with a batch goes in a later one once it is prepared again; a handed-off batch's claims are over and marking it sent counts what still waits; a batch with a held piece is not handed over; a long upload and a queued build keep their lease on a timer; a connector that cannot tell leaves the batch unknown; the sweep removes a stopped build's ZIP and folder; names, pieces and files need the download permission; a failing piece is named by its place |
Ad hoc email in tests
The queue is never sent on a schedule in tests (jcm.email.sending.enabled=false); a test calls
EmailQueue.sendQueued() and reads what a recording EmailSender kept: the sample's RecordingEmailSender (a
@Primary test component; mail to unreachable@example.test fails as a refusing server does), the demo's
RecordingMail (a @TestConfiguration imported by DemoCaseEmailE2eTest only). The sample's override copies of
case.appeal.yml (jcm-test/, jcm-child-workflows/, jcm-form-rules/, jcm-studio-removal/) each declare
email, as the main file does, so every profile offers "Email parties". Who may not send is a reader without
the permission (ref-blind) and, for recipients, parties-hidden, from whom a row rule (HiddenPartiesRole) hides
parties named "... sealed". The rate limit is proved with rows of jcm_CaseEmail written for one user, never by
sending 50 emails. CaseEmailGuardsTest seeds its own senders: email-case-hidden (case worker, appeals titled
"... hidden-appeal" hidden by HiddenAppealsRole) and email-address-blind (PartyAddressBlindRole: parties without
their address) and email-name-blind (PartyNameBlindRole: parties without their name). The jcm-test/ case type
names parties by their instance name (no name:), so the instance-name path is the one the sample's tests use. EmailLoggingTest captures the root log around a real send: the queue's own send goes to the
recording sender in tests, so the test also hands the message to the add-on's EmailSenderImpl with a mail server
that accepts everything. The browser test writes screenshots.
Configuration studio in tests
Studio tests set jcm.studio.* per test class, never in a shared test profile, so each class says which areas are
on: @SpringBootTest(properties = "jcm.studio.edit.workflows=true") for the switch, and the folder from a temporary
folder made once for the class through @DynamicPropertySource
(registry.add("jcm.studio.files", FOLDER::toString), FOLDER from Files.createTempDirectory); a unit test of
StudioSettings or StudioEditing uses a MockEnvironment and @TempDir. A class with its own properties starts
its own Spring context, so keep the studio's settings classes few. Test users holding a studio role get a random
password made at run time. Studio browser tests scan what they open (the diagram, with a record on it, the gallery, a
queue preview, the matrix) with AccessibilityScan.assertNoViolations and accept no findings: no accepted-findings
arguments. See
contract.
Editing tests share contexts rather than start their own. In the sample, the editing UI tests (History and the
workflow editor, the queue editor, inbox tabs, job roles, the matrix ticks, jcm.yml, the text editor) extend
StudioEditingUiContext (workflows, queues, app, job roles, tasks, deadlines, rules and identity editing on, Quartz said to
be clustered, one temporary FOLDER for jcm.studio.files) and signs in with
@UiTest(authenticator = StudioEditingUiContext.AsStudioEditor.class); each test wipes the folder and swaps the
startup generation back after itself (generation.swapBack(startup)), since the context and its generation are
shared, and a test that asserts History's contents empties jcm_StudioChange first (contexts may share one
in-memory database). The cached contexts of a module's tests share one test JVM: the sample's test task runs with
maxHeapSize = '3072m' (raised once for the production-readiness contexts) and the demo's with 1536m, so a new
studio test reuses an existing context class rather than adding properties of its own; a new context there needs the
heap raised in the same change.
The sample's ordinary test task also caps Spring's context cache at eight entries. This conservative experimental
headroom can cost extra context creation after eviction; it is a test-resource policy, not an application runtime
setting or proof that no memory leak exists.
jcm-test-support also registers UiTestServiceLifecycleListener through Spring's test listeners.
For @UiTest, Spring wraps Jmix's extension: the listener destroys the new fixture service after Jmix has
removed authentication and cleaned views, notifications and dialogs. It owns only an exact
TestSpringVaadinServletService, distinct from the pre-method service, whose test servlet names the same
already-loaded Spring context. It captures before test execution, with a fallback for setup that publishes
its service then fails. Cleanup runs once, removes its per-method state even on failure, and attaches a cleanup
failure to the original failure when available. Browser/production, stale and foreign-context services are not
owned; a service first published during the test body is not a setup fallback. Context lookup does not start a
failed context. Explicit extension registration must retain Spring's wrapping order.
A two-method real UI regression observes public service-destroy callbacks after teardown; boundary tests cover ownership, setup failure and cleanup exceptions. Jmix initialization that fails before publishing its service cannot be safely owned by this listener. Vaadin 25.1.14 destruction also clears the static signal transaction fallback; concurrent active-service transaction behavior has not been established. The listener does not add session/current-instance/servlet-context cleanup or close Spring-owned executors. The eight-context policy is independent. This fixture correction establishes neither the sole cause of earlier heap exhaustion nor a product memory-leak or complete-suite heap guarantee.
The studio on several servers. StudioAppliedAssertionTest runs in StudioEditingUiContext (Quartz clustered, no
jcm.servers, so editing stays on): it publishes through WorkflowDraft and saves jcm_StudioChange rows by hand
with a new publishId, server other-host and a publishOrder from Sequences
(Sequence.withName(StudioHistory.PUBLISH_ORDER)) to stand for a publish made on another server, and calls
StudioHistory.noteAppliedAtStartup() for what a restart does (the current generation's files standing for the files
this server loaded); it covers the refusal while behind, an own undo, outside rows from another server, and the order
by number over the clock. It empties jcm_StudioChange before and after each test, since a row left by hand would
make as.studio.applied fail and the publisher refuse for the tests after it. StudioSeveralServersUiTest is the one
context with jcm.servers=2 (every editing switch on, a temporary folder): a browser test (@Tag("e2e"), so it runs
in e2eTest and not in test, whose heap stays as it is), which checks the overview (Off and the reason for every
area, scanned), the workflow editor (Publish disabled with the reason), History and Download, and calls
StudioPublisher and StudioHistory.undo directly. The fast proof of the publisher's refusal above one server is the
unit test StudioPublisherServersTest (a publisher built with nothing but its settings). Both sample classes are
@Tag("own-database"): they delete and write History rows. A unit test
of the reason uses MockEnvironment().withProperty("jcm.servers", "2") (StudioEditingTest).
StudioSingleServerRestartTest (jcm.servers=1, workflows editable, a temporary folder, @Tag("own-database"))
covers a single server taking its files as applied: it publishes, wipes the folder and swaps the startup generation
back (the published file reverted, as a restart would load it), then calls noteAppliedAtStartup() and onReady()
for a start, and expects an outside change as the newest, as.studio.applied passing and a publish accepted; also a
server already stuck behind an unnumbered outside row, and a restart with the files as published recording nothing.
StudioSeveralServersUiTest.aRestartLeavesAServerBehindAPublishItsFilesLack is the same start on two servers: still
behind, no outside row, the publish refused.
A test that publishes a change the version rule would refuse because other tests left records on the version
(removing or renaming a state, undoing a publish that added one) runs it inside
StudioTestRecords.withoutInstancesOn(unconstrained, "wf.appeal", 1, work), which sets that version's workflow
instances aside and puts them back after; the demo's DemoStudioReturnTest has its own copy of it
(withoutInstancesOnTheAppealsVersionOne, since StudioTestRecords lives in sample-appeals/src/test) for
wf.appeal version 1 before undoing the Return publish. Never weaken the rule for a test.
A demo's studio script runs as one browser test (the hearings demo's DemoStudioPublishE2eTest): its own in-memory
database (main.datasource.url=jdbc:hsqldb:mem:<name>) with the seed on, the areas the script edits on in the
class's properties, and jcm.studio.files a temporary folder from @DynamicPropertySource, so nothing is written
into the sources and @DirtiesContext throws the context away after. It empties jcm_StudioChange first (contexts
may share a database), signs in and out as the people of the script, scans each view and dialog it opens (the Undo
confirmation too) and times itself: System.nanoTime() from the first sign-in to the last assertion, the
application's start left out, logged as Studio demo took <n> s and failed above 120 s with the time in the
message. The same publishes made through WorkflowDraft and QueueDraft as a test user holding the studio editor
role (DemoStudioReturnTest) prove the behaviour without a browser; a test there that undoes a workflow change sets
aside the instances on that version first, or the version rule refuses the undo.
Check parity: where a new check's fixture goes
A publish must refuse exactly what the next start would refuse, with the same message. The proof is a catalogue of
fixtures in jcm-test-support, one folder per app: src/main/resources/jcm-refusals/<kind>/<name>/ for the kinds
the sample installs, read by RefusalFixtures.all() and run by the sample's StudioCheckParityTest, and
jcm-refusals-demo/<kind>/<name>/ for the kinds only the demo installs (seed), read by
RefusalFixtures.all(RefusalFixtures.DEMO) and run by DemoCheckParityTest; a fixture of a kind an app does not
install would be refused as an unknown folder, not as its own mistake, so each catalogue holds only kinds its app
reads. Each test (record Fixture(name, files, message)) runs every fixture through both routes:
StudioPublisher.check(change) as a studio editor with the fixture's areas on, and
generation.files().withRoot(studioRoot, files) then generation.prepareAll(candidate, reloadables, checks) as
startup reads. A fixture folder holds the changed files under their own folders (queues/q.fixture.unknown.yml,
jcm.yml; an empty <code>.removed is a marker; seed/seed.fixture/letter.txt a data file) and one of:
message.txt: the refusal, word for word.{file}stands for the display of the fixture's first file (in path order) under the studio folder,{file:<path>}for another of its files (an item listed in both a list and its extension),{loaded:<path>}for a file the application loaded with that path under its root (a case type the fixture does not change, the file a marker clashes with). Lines are the fixture's own:{file}:6: queue 'q.fixture.unknown': unknown key 'colour'; ....passes, an empty file, for files the checks accept (a set value naming an item the same publish adds, a questionnaire naming a list the same publish adds, a new workflow version).
When a registry or the loader gains a refusal, or a check moves, add a fixture named for the mistake
(<kind>/<what-is-wrong>) beside the kind's others; a check that lives in a listener or in commit fails the publish
route at once, which is the point. Fixtures are written against sample-appeals (case.appeal, case-worker) and
run under the test and form-rules profiles, so a form rule naming a transition is on the case type (identity
fixtures use job.case-worker, job.refdata-admin and ui-minimal; the sample's parity test also fills
{job-roles} with the job roles its context holds, by code, for identity/unknown-job-role; the sample installs
both provider starters, whose ProviderInstalled beans let provider: oidc and provider: ldap files load there);
seed
fixtures are written against demo-hearings (case.appeal, job.intake, start-review). The twin of a passing fixture (the same files less the one that
makes them pass) belongs beside it, refused with today's message, so a check that moves out of verify is caught:
queues/set-value-without-candidate-refdata beside queues/set-value-needs-candidate-refdata.
StudioAtomicReloadTest is the other half: a reader thread taking generation.current() in a loop never sees a
transition without its button or the button without its transition while publishes add and remove both. A caller
that needs two kinds consistent takes one Generation and reads both from it; two registry calls agree only while no
publish lands between them.
Scheduled jobs and business logic in tests
The test profile does not start the job scheduler, so nothing fires on its own while tests run:
# src/test/resources/application-test.properties (the scaffold writes this with the jobs starter)
jcm.jobs.scheduling-enabled=false
A test runs a job with JobService.runNow(code): with scheduling off it runs in the test's thread and returns the
finished JobRun (outcome, items done and failed; failures(run) for what failed). Run it with nobody signed in, or
as a user holding jcm.jobs.run-now (JobsAdminRole); a signed-in user without it is refused. Job lists and run
counts are shared by every test in the context, so assert on the job's own codes and records, not on whole tables.
Test a lifecycle hook or record validator through a real save (DataManager.save), as a user would make it, and
assert what was stored; a save in system work, and one in quiet system work, where the hook must or must not run.
A hook's afterCommit runs only once the save's transaction commits, so a test that saves inside its own
transaction (@Transactional) never sees it.
Queue date availability
Queue date coverage is in QueueDefinitionParserTest, QueueScheduleTest, QueueScheduleServiceTest,
QueueScheduleUiTest and QueueScheduleE2eTest. Parser cases include inclusive endpoints, one-day and open
intervals, leap dates, strict scalar/empty refusal with file/line, old constructors and withTab preservation.
The service and real-grid tests freeze the injected application TimeSource, restore it and configuration/data
after each test, and use readable sentinel rows with positive in-range/undated and denied-access controls.
Both dedicated clock-spy application contexts use @DirtiesContext(classMode = AFTER_CLASS) so Spring closes
and removes them from the test cache after their classes. Verify actual pool shutdown at class completion on
HSQLDB and PostgreSQL; focused passing assertions alone do not establish complete-suite memory stability.
They cover Inbox, query/search, count, holds, board, export, Get next claims/assignments, home/dashboard fallback,
and retained grids' fresh paging/search/reload/count plus explicit preview after the end day. Already rendered
rows stay until interaction. Browser coverage uses startup files dated in 2000/2100 and an undated control, so
external cluster runs need no local configuration swap. Run the affected sample tests on HSQLDB and PostgreSQL.
Studio authoring tests cover lossless date edits and clearing in both line-ending styles, all four gallery date
forms, retained future/expired cards, initialized read-only controls, new/existing queues and atomic invalid-range
refusal followed by correction without losing other edits. Malformed keyboard dates retain scheduled bounds,
block Check/Publish and preserve other edits; correction and explicit empty clearing are covered separately. StudioQueueDatesE2eTest types dates with the keyboard,
checks refusal/no write, corrects and publishes, reopens and clears, and verifies the gallery, viewer and denied
access. Six early-close cases hold actual deferred overlay opening callbacks, type a date and close with
real Enter, then release the callbacks. Both fields cover release while closed and reopening before release,
with stale-first and current-first notification orders. They must restore surrounding controls, reopen normally
and allow subsequent keyboard Check with an axe scan. The scheduling hook changes no field value or aria state.
The publication and editable-calendar race methods are single-server: Studio refuses all editing when
jcm.servers exceeds one, including Check and opening editable date fields. Viewer/denied cases remain cluster
eligible. It captures desktop and 390px gallery/editor layouts; runtime scheduling retains the cluster-compatible startup fixtures. Run affected UI and browser tests
on HSQLDB and PostgreSQL.
Search result refreshes
CaseSearchUiTest records a real grid client key, refreshes the search, and delivers the pending click: a retained
record must open its case screen. It also refuses unknown keys and rows removed by filtering (including a delayed
Open button's old object), then opens a current result. CaseSearchE2eTest delivers an expired row-key event in
the browser, checks the visible refusal, narrows the results and opens the exact remaining case. Browser tests that
click Search before opening a row wait for the changed summary or result set, so they select from the completed
search. The demo's StackE2eTest searches for its seeded letter and waits for that keyword's summary before opening it.
Keyboard checks after editing text
The studio text editor sends edits lazily. StudioE2eTest.theTextEditorByKeyboard waits for Save to become enabled
before its real Tab traversal and Enter activation, then checks the refusal at the typed key's line and the discard
confirmation. Check that the Vaadin button lacks the disabled attribute: Selenide's generic Condition.enabled
can pass for this custom element while that attribute is still present. Appending text without a newline leaves
the gutter size unchanged, so that size cannot confirm the edit reached the server. Keep the enabled-state wait and keyboard assertions separate: do not directly focus Save,
replace Tab with a click, or add a sleep. A Save button excluded from the tab order must still fail this test.
Accessibility
AccessibilityScan.assertNoViolations(view, accepted...) runs axe-core for WCAG 2.1 A and AA. Stock Jmix 3.0.3
filter and pagination components fail it, so known framework-origin findings are accepted by name
(JMIX_FILTER_COMBO_BUTTON, JMIX_SIMPLE_PAGINATION); anything else fails. Remove an accepted entry when the
framework fixes it.