Testing¶
Test helpers (snodra-messaging-test)¶
InMemoryBuses(typePrefix, userId): implementsEventBus,CommandBusandQueryBusin memory for unit tests without Docker. Messages still pass through the JSON codec.register(handlerBean)adds handlers;publishedlists events. A scatter-gather returns one part from the registered handler (service and instancein-memory); a streaming query collects the registered streaming handler's flow (honouringmaxResults). A subscription query (subscribe) answers its initial result from the registered handler and takes its updates frombuses.emitter, a localQueryUpdateEmitter(emit,complete,completeExceptionally, filtered like the real one;buses.openSubscriptionscounts the open ones): no credits, and an emit is delivered at once, not after the commit of a surrounding transaction.maxResults,cancel()andtake(n)end it as against a hub.SnodraContainers.hubMtls(directory, services, serverCertificate, serverKey, clientCa, clientAuth = "required"): the hub image (SNODRA_SERVER_IMAGE, defaultsnodra-server:dev) in modeenforcewith[[service]]tables and a client CA (P5c). Issue the hub's own pair from the client CA with both usages, so the image's health check (which presents it underrequired) passes. Generate the CA and the certificates at test time; the starter's own tests use BouncyCastle in test scope for that (the JDK'skeytoolcannot give a URI SAN and a seconds-long validity at once).InProcessHub: in-JVM stand-in for the hub (start(),channel(),dropInstance(...)(also with aStatus),lastRequestHeaders(),lastRequest(),registrationsFrom(...),lastRegisterFrom(...),acksSentTo(...),echoHeartbeats = falseto simulate a hub that stopped answering), for hub-client tests without a container. It answers everyRegisterwith aRegisterAck(heartbeatInterval,heartbeatTimeout,replyTimeoutas default,maxTimeout,typeTimeouts);emitTimeouts = falseemulates a hub that loses requests. Flow control as the real hub: a firstRegisterwithout permits isINVALID_ARGUMENT, permits, a per-instance queue by priority (queueCapacity, full:RESOURCE_EXHAUSTED),permitsGrantedBy(...),permitMessagesFrom(...),permitsAvailable(...),queuedFor(...),forwardedOrder(); permits never exceed the session's cap (initial_permits, raised byPermits.grant). Multi-hub:lastStatusFrom(...)(with the processors),statusMessagesFrom(...),requestsFrom(...),sessionsOf(...), andpauseReading = truestops reading every stream. Like the real hub it keeps one session per instance id: a new stream registering an id replaces the older one (sessionsReplacedOf(...),streamsOpenedBy(...);replaceSessions = falsekeeps both), andackDelaydelays eachRegisterAckas network latency would. Query modes (P4a): shared query types, scatter-gather with parts, end,max_results, the deadline and aCancelto every forwarded target of a gather that ends early, as the real hub; an unknown request mode isINVALID_REQUEST, andinject(instanceId, message)writes any server message to an instance's stream. Streaming queries (P4b): one target, credits (uint32) andFlow, parts and ends relayed,max_results, the idle timeout (paused while the credit is 0),maxStreamDuration, cancels both ways and the gates as the real hub (a unaryReplyto the target is ignored),dropPartsdrops relayed parts byseq(the real hub's full-buffer drop), andopenStreams(),creditOf(requestId),flowsFrom(instanceId)andcancelsFrom(instanceId)observe it. Subscription queries (P4c): every live instance of the type is a target as they are at the open, the initial request goes out as<id>#0through a permit and the queue, updates are renumbered behind the initial part under the sender's credit and the buffer (subscriptionBuffer, 256: one more ends it),max_resultscounts updates, cancels fan out both ways, a target leaving is silent unless it was the last (HANDLER_DISCONNECTED),maxSubscriptionsPerInstance(1024) refuses withRESOURCE_EXHAUSTED,maxSubscriptionDuration(off) ends withCANCELLED, and the gates are the real hub's;openSubscriptions(),subscriptionTargetsOf(instanceId),subscriptionCreditOf(requestId)andbufferedUpdatesOf(requestId)observe it. Processor control (P6b):control(instanceId, request)sends aControlRequestto the instance's session and awaits itsControlReplyfrom that session,controlRepliesFrom(instanceId)lists every reply.InProcessHub.auth(P5a):HubAuth.enforce(tokens),HubAuth.permissive(tokens)orHubAuth.OFF(default), withtokensa map from the plain test token toAclEntry(service, handle, send)(patterns: exact,prefix.*,*), answers like the real hub: inenforcethe firstRegisteris closed withUNAUTHENTICATED(no credentials, an empty token, ajwton a hub withoutservices, an unknown token) orPERMISSION_DENIED(another service name, a command, query or shared query outsidehandle), a laterRegisteradding a forbidden type likewise, and a request outsidesendgets an immediateError{PERMISSION_DENIED}in every request mode (UNAUTHENTICATEDif the token leftauthmeanwhile).prefix.*needs something after the dot (it does not matchprefix.itself).authmay be replaced at runtime and, like the real hub on an ACL reload, replacing it inenforcecloses the live sessions the new ACL no longer allows (UNAUTHENTICATEDfor a token that left,PERMISSION_DENIEDfor a service name or handled type it no longer grants; their in-flight requests fail as on any disconnect); setcloseSessionsOnAuthChange = falseto keep them and test the per-request refusal instead. Like the real hub (unlessauthisOFF), aRegisternaming the instance id of a live session of another service is closed withPERMISSION_DENIED(instance id … belongs to another service) and the owner is left alone.permissiveallows and records.authViolations()lists every violation (code, message, enforced, a monotonic timestamp, so tests can assert the spacing of reconnects) andtokensSeenFrom(instanceId)the token of everyRegisterreceived, refused ones included.InProcessHuband JWT credentials (P5b):HubAuth.enforce(tokens, services)/permissive(tokens, services)take the[[service]]tables asAclEntry(service, handle, send). Ajwtcredential whoseazpis the registering service and that has such an entry is accepted with its rights; anotherazpor a service without an entry isPERMISSION_DENIED, a token that is not three segments with anazpisUNAUTHENTICATED, and withoutservicesthe hub answers "jwt credentials are not configured". The signature andexpare not checked (use the real hub image for that).jwtsSeenFrom(instanceId)lists the JWTs of theRegisters andcredentialsSeenFrom(instanceId)thejwtortokenof everyClientMessage.credentials, and a refresh is judged like aRegister's against the session's own service.SnodraContainers.hubJwt(...)starts the hub image under test with JWT authentication (issuer, JWKS URI,[[service]]ACL file, leeway 0 s, expiry grace 2 s).TestCertificates.generate(dir, names): a throwaway self-signed certificate made at test time with the JDK'skeytool(PEM certificate, also the CA a client trusts, and PKCS#8 key; valid forlocalhostand127.0.0.1by default).SnodraContainers: unstarted Testcontainers definitions.kafka(),mongo()(single-node replica set, needed for transactions),hub()from the hub image under test,snodra-server:devor the one named bySNODRA_SERVER_IMAGE, with ports 7000 and 7001 (every hub test runs on it: the hub and this library ship together),hub(env)for it with extraSNODRA_SERVER_*settings,hubAcl(dir, acl, authMode, tls, env)for it with access control and TLS (it writes the ACL file, with the SHA-256 of each token, intodirand copies it and theTestCertificatesinto the container, withSNODRA_SERVER_AUTH_MODE,SNODRA_SERVER_ACL_FILE,SNODRA_SERVER_TLS_CERTandSNODRA_SERVER_TLS_KEYset),hubJwt(...)andhubMtls(...)(below), andhubImageAvailable().SnodraTestKafka(bootstrap, typePrefix, topic).awaitEvent<T>(): reads an event back from the topic.SagaTestFixture(SagaClass::class, beans…): drives one saga with events and time, in memory; see Testing a saga.
val buses = InMemoryBuses(typePrefix = "workouts")
buses.register(WorkoutHandlers(repo, buses)) // the handler publishes events through the same in-memory bus
val result = buses.sendBlocking(LogWorkout("legs"))
The end-to-end test (TwoServicesEndToEndTest) starts Kafka, MongoDB, the real hub and two Spring Boot services. It is
skipped when snodra-server:dev (or the image named by SNODRA_SERVER_IMAGE) is not present in the local Docker daemon. Build the image from the snodra-server repo:
docker build -t snodra-server:dev .