Java testing

Use MockCalmLensServerClient to test your Java SDK integration offline, with an in-memory CalmLens or queued responses.

Setup

MockCalmLensServerClient runs an in-memory CalmLens behind a real client (mock.client), so your tests can upload, read back and serve assets, and see moderation decisions, without a network. Calls still go through the real client's validation, encoding and error mapping, and every request is recorded.

import com.calmlens.MockCalmLensServerClient;
import com.calmlens.MockCalmLensServerClient.Options;
import com.calmlens.MockCalmLensServerClient.Trigger;
import com.calmlens.MockDecision;
import com.calmlens.Models.*;

var mock = new MockCalmLensServerClient();
Asset asset = mock.client.assets.create(new SubmitAsset("photo.png", Content.bytes(pngBytes, "image/png"))); // pending
mock.completeProcessing(asset.id(), MockDecision.of("blocked").flag("violence", 0.9));
Asset current = mock.client.assets.retrieve(new AssetId(asset.id()));
// current.classification().moderation().status() is AssetModerationStatus.BLOCKED

Without a builder, the mock uses project project-1 (MockCalmLensServerClient.MOCK_PROJECT_ID), or the projectId option. The mock also accepts a CalmLensServerClient.Builder (new MockCalmLensServerClient(builder, options)), which sets the project ID itself, and validates its options like the real client. Its client makes no retries unless the builder sets maxRetries, so a failed request fails once; set it to test how your code handles retries. Retry backoff takes no real time.

Options

OptionEffect
moderateDecides each asset the mock moderates (see Moderation decisions).
createId, nowDeterministic IDs and timestamps. createId receives the object's prefix: asset, fldr, hl, hle, lens, evt or rev. The default clock moves on by at least a millisecond per reading, so assets created in a row have increasing createdAt.
projectIdThe project of a mock built without a builder; project-1 by default. Setting it with a builder throws sdk/invalid-argument.

Finished processing removes content unless the upload sets keepContentAfterProcessing.

Moderation decisions

The mock doesn't classify content. Options.moderate(input -> ...) decides each asset the mock moderates. The ModerationInput it receives has:

  • asset(): the stored asset, still processing.
  • content(): the uploaded bytes() (the parts of a multipart upload joined in order), and text() for a plain-text upload such as text.classify. Both are null when there is no content, such as for a website.
  • trigger(): why the asset is moderated: Trigger.UPLOAD, Trigger.RETRY (after assets.retry), Trigger.RERUN (after assets.explain with rerun(true)) or Trigger.COMPLETE (see below).
  • queued(): true when CalmLens would queue the work rather than answer with the decision: queued uploads, retries, reruns and COMPLETE.

It returns a MockDecision. MockDecision.of(status) takes pending (still processing), failed, allowed, limited, age-restricted, blocked or purged (which also removes the content), or the matching Outcome. A failed asset gets classification().failureReason() processing-error. Without moderate, queued uploads, retries and reruns stay pending and everything else is allowed.

flag(category, score) and flag(category, score, qualifiers) record a category's score from 0 to 1 and, optionally, its qualifiers' scores, and notEvaluated(category) marks a category as not assessed. A decided asset gets a complete report, as from CalmLens: raw.categories holds every category (unflagged ones evaluated with score 0), categories holds each evaluated category's policy score and action, and flaggedCategories lists the categories the decision acted on (categories scored 0.5 or more, unless the status is allowed). An unknown status, category or qualifier, a score outside 0 to 1, a category named twice, or findings on a pending or failed decision throw sdk/invalid-argument.

var mock = new MockCalmLensServerClient(new Options().moderate(input ->
    input.content().text() != null && input.content().text().contains("kill")
        ? MockDecision.of("blocked").flag("violence", 0.92, Map.of("violence-threat", 0.9))
        : MockDecision.of(input.queued() && input.trigger() != Trigger.COMPLETE ? "pending" : "allowed")));

Asset comment = mock.client.text.classify("I will kill you");
CategoryResult violence = comment.classification().moderation().raw().categories().get("violence");
// violence.score() is 0.92, the detection score
CategoryPolicyScore policy = comment.classification().moderation().categories().get("violence");
// policy.score() is the policy score and policy.action() what the policy does with the category
// comment.classification().moderation().flaggedCategories() is ["violence"]

A moderate function decides queued uploads straight away too. Return pending for them (input.queued() with Trigger.UPLOAD) to finish them later.

Finish processing

mock.completeProcessing(assetId) finishes processing a pending asset as CalmLens would, with the decision moderate returns for Trigger.COMPLETE (allowed by default); mock.completeProcessing(assetId, decision) uses the decision you pass. It records no review, so the asset can still be moderated again with assets.explain. It fails with 404 asset/not-found for an unknown asset and sdk/invalid-argument for an asset that isn't processing or awaiting a pending re-run:

Asset upload = mock.client.assets.create(new SubmitAsset("photo.png", Content.bytes(pngBytes, "image/png"))); // pending
mock.completeProcessing(upload.id(), MockDecision.of("age-restricted").flag("sexual", 0.8));
Asset decided = mock.client.assets.waitForDecision(new WaitForDecision(upload.id()));
// decided.classification().moderation().status() is AssetModerationStatus.AGE_RESTRICTED

The default key has no grants, so private content can't be served. For a key with Download assets, pass CalmLensServerClient.builder(MockCalmLensServerClient.createMockApiKey(MockCalmLensServerClient.Grant.download()), projectId) to new MockCalmLensServerClient(builder, options), or change the key's grants later with mock.setApiKeyGrants(...).

mock.withStorage(storage -> ...) reads or changes the stored assets, folders, events and content directly.

What the mock simulates

SimulatedBehaviour
Assets and foldersCreate, retrieve, list, list children, update, move, delete, delete content, retry, explain, decide, search and signed URLs. assets.decide refuses decisions like the API: an asset pending moderation can only be blocked or purged (409 asset/decision-not-allowed), and its current status gets 409 asset/decision-unchanged. Folder pages are ordered by name or creation time, with the folder ID breaking ties. assets.batch checks every ID first (an ID that is not an asset ID fails with 400 validation/invalid-request, issue validation/invalid-format), then applies the operation at once, in request order, rather than in the background, and adds one event per asset.
ListsAsset filters like the API's: the documented asset fields with ==, !=, >, >=, <, <=, =in= and =out=, joined by ; (and, binding tighter than ,), , (or) and parenthesised groups. * in an == or != value matches any run of characters, ignoring case. Any other field or operator, such as =like=, fails with 400 filter/invalid. Asset, hash list, entry, policy and lens lists sort by createdAt, id or both, and folder lists by name or createdAt; any other sort fails with 400 validation/invalid-request, issue validation/invalid-value. Cursors resume after the last item, so assets created or deleted between pages are neither repeated nor skipped, and a cursor only continues the query it came from.
SearchKeyword search like the API: every word of the query must appear, case-insensitively, in the name, ID, external ID, description, tags, type, content format or extension, or moderation status. Results carry the API's scores and matched fields, best match first, then newest; there is no semantic search.
UploadsMultipart parts must arrive in order, parts before the last must be at least 5 MiB, multipart image uploads must total at most 20 MiB, and parts must add up to a declared total. Content larger than the builder's partSizeBytes is uploaded in parts against the mock too, and repeated part keys replay, so you can test resuming an upload with the same idempotency key. A part out of order fails with 409 upload-part/invalid-number and the expected and received numbers, and the final part waits for the decision as chosen when the upload started, unless it sends wait.
Policies and lensesThe organisation starts with the General preset policy assigned to the project. Preset settings give every category its default action and no rules, and policy settings that leave out a category or a category's action, allowances or restrictions fail with 400 validation/invalid-request. Lenses can be created, listed, changed and deleted, and ensureLenses changes a lens to the definition sent.
Idempotency keys1 to 255 printable characters without a space at either end. A key replays the first response, and a failed request frees its key.
ErrorsThe API's codes, statuses and request IDs. Page sizes and event limits outside 1 to 100, search page sizes outside 1 to 20 and search queries outside 1 to 200 characters fail with 400 validation/invalid-request, listing the field and its issue, validation/too-small or validation/too-big, in the details' issues.
WaitingRetries and waitForDecision don't wait in real time; waitForDecision reads the stored asset.
EventsEvery upload adds asset.uploaded, then asset.classified and the automated asset.<status> (whose actor is automated) once it is decided, or asset.failed.
CDNcdn.serve returns stored bytes with their content type, Cache-Control as the CDN sets it (public only when anyone may see the asset, otherwise private; max-age=31536000, immutable for images and max-age=3600 for other content; private, no-store when the request carries viewer claims), the CDN's Cache-Tag and protection headers, and for images an ETag and Expires. Blocked, purged and failed assets, and assets whose content was removed or is still uploading, get 403 asset/not-available whatever the key; age-restricted ones requested without .viewerClaims(new ViewerClaims().ageConfirmed(true)) get 403 viewer/age-confirmation-required whatever the key, and private ones need Download assets. A classified image's placeholder is a small PNG rendered from its ThumbHash, public whatever the asset's visibility or moderation, and refused once the asset is purged or its content removed. URLs from cdn.signAssetUrl are served, /info included, until they expire, and mock.fetchCdn(url) loads one as a browser would, without the API key.
IDsLike the API's: each new object's prefix, _ and 20 random base62 characters, such as asset_5Gm2Rk8XqT3wLp9VbN4c or fldr_7Nc4Wq2Lm8Xt5Rk9Bv3P.

Events and reviewer decisions

mock.enqueueEvent(type, assetId, facts...) adds an event to the feed that events.list returns after cursors taken earlier, and returns it. An event about a stored asset carries the asset as it is, as from CalmLens. An asset.<status> event carries the moderation status it announces, as CalmLens sends it once the asset has that status. Retrying an asset, deleting its content and deleting it add asset.retried, asset.content-removed and asset.deleted events, as the API does. assets.explain with rerun(true) adds asset.rerun-requested and returns the asset unchanged: it keeps its decision until the one moderate returns replaces it, and keeps it when that is failed. A pending re-run waits for completeProcessing.

assets.decide records a reviewer's decision with its note and adds the matching asset.<status> event, as the API does. To simulate a reviewer in a test, use mock.decide(assetId, outcome): it records a reviewer decision in the asset's manualReviews and adds the matching asset.<outcome> event, whose actor is a user, with severity low for allowed and limited, high otherwise. PURGED also removes the content and first adds asset.content-removed. The moderation report stays as it was. PENDING and FAILED are not decisions and throw sdk/invalid-argument; to finish processing as CalmLens's moderation would, use completeProcessing.

Recorded requests and failures

mock.requests() returns every request, oldest first, with method(), url(), path(), decoded query(), header(name), bodyText() and status(). path() is relative to the API or CDN base URL, so it leaves out /v1, with each segment decoded, such as /projects/project-1/assets or /assets/<id>. status() is the HTTP status of the response, or null for a request that failed without one. mock.clearRequests() forgets the requests recorded so far.

MockCalmLensServerClient.Request sent = mock.requests().get(0);
sent.method();                    // "POST"
sent.path();                      // "/projects/project-1/assets"
sent.status();                    // 200
sent.header("Idempotency-Key");   // generated for each upload
sent.bodyText();                  // request body as UTF-8 (null when there is none)

mock.failNextRequest("transport-error"), "timeout" or an API error code fails the next request without running it: a network failure throws sdk/transport-error, a timeout sdk/timeout, and an API error code that error with its HTTP status. Pass new MockCalmLensServerClient.FailureOptions() as a second argument to narrow or shape the failure: operation("assets.create") fails only the next request that method sends (a name that isn't a client method, or a method that sends no request, throws sdk/invalid-argument), and for an API error, details(map) sets the error's details and retryAfter(seconds) answers with a Retry-After, so you can test code that reads getDetails() or getRetryAfter(). A transport error or timeout has no response, so failNextRequest throws sdk/invalid-argument for one with details or retryAfter, and queues nothing. Each queued failure fails one request, so a retry takes the next queued failure or reaches the in-memory API:

mock.failNextRequest("upload/website-rate-limit-reached", new MockCalmLensServerClient.FailureOptions().retryAfter(30));
ApiException error = assertThrows(ApiException.class, () -> mock.client.assets.list(new ListAssets()));
// error.getStatus() is 429 and error.getRetryAfter() is 30 seconds

Queued responses

Queued responses take precedence over the in-memory API, for exact request and error tests. Each answers one request, so with retries on, queue one response per attempt:

mock.enqueue(200, Map.of("id", "asset-1", "upload", Map.of("status", "completed")));
mock.enqueueError(ErrorCodes.ASSET_NOT_FOUND);
mock.enqueueCdn(200, "image/webp", imageBytes);
  • enqueue(status, body) queues a JSON response from a map, list or response record. enqueue(method, path, status, body) answers only a request to that route, with the path as path() records it.
  • enqueueError(code) queues the API's error response for a public error code, with its real HTTP status, error body (code, message, requestId and details) and matching X-Request-Id.
  • enqueueFailure(exception) and enqueueTimeout() simulate network failures.
  • enqueueEvents(nextCursor, hasMore, events...) and enqueueCdn(status, contentType, bytes) queue an events page and a CDN response.

Webhook handlers

CalmLensServerClient.toWebhookEventPayload(event) converts an event from events.list or mock.enqueueEvent into the delivery CalmLens sends for it: the same event fields, in the shape events.list returns them. CalmLensServerClient.createWebhookHeaders(secret, body, deliveryId, timestampSeconds) returns the headers of a signed delivery of the raw body, as CalmLens sends them. Pass Instant.now().getEpochSecond() as the timestamp, since handlers reject deliveries more than 5 minutes old, then call your handler with the body and headers. createWebhookSignatureHeader(secret, timestamp, body) builds only the x-calmlens-signature value.

Upload tokens

MockCalmLensServerClient.signUploadToken(apiKey, options, now, nonce) signs an upload token at a fixed time and nonce, for exact tokens in tests.

Generate test inputs

TestInputs generates authenticated test inputs from your project's secret test input key. CalmLens recognises them only in projects with Test inputs turned on. generateTestTextCode(input, testInputKey) returns a text code to submit as the whole text: text with anything else around the code is moderated as ordinary content. generateMediaTestCode(signal, testInputKey) returns a phrase to read aloud or show in a video. A TestInput lists instances (each a TestInput.Instance with a category, qualifiers and optional score and action), and optional regionalActions and unassessedCategories; pass a category name such as "violence" instead for one instance of it. TestInputs.CLEAN, LIMITED, REGIONAL_DELIVERY and the other constants are the portal's presets. An invalid key or scenario throws CalmLensException with code sdk/invalid-argument.

import com.calmlens.TestInput;
import com.calmlens.TestInput.Instance;
import com.calmlens.TestInputs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Example {
  public static void main(String[] args) throws IOException {
    String testInputKey = System.getenv("CALMLENS_TEST_INPUT_KEY");

    // Choose each instance's outcome: the strongest action wins
    String text = TestInputs.generateTestTextCode(new TestInput(List.of(
        new Instance("harassment", List.of("harassment-abuse", "harassment-documentary")).withAction("limit"),
        new Instance("harassment", List.of("harassment-threat")).withAction("limit"),
        new Instance("harassment", List.of("harassment-abuse")).withAction("block"))), testInputKey);

    // Regional delivery outcomes without category findings
    String regional = TestInputs.generateTestTextCode(TestInputs.REGIONAL_DELIVERY, testInputKey);

    // A test image to upload on its own: it survives JPEG, WebP and resizing
    Files.write(Path.of("test-image.png"), TestInputs.paintTestImage("violence", testInputKey).png());

    // A phrase to read aloud or show in a video
    String phrase = TestInputs.generateMediaTestCode("violence", testInputKey);
    System.out.println(text + "\n" + regional + "\n" + phrase);
  }
}

Set action on every instance to choose its outcome independently of the project policy, or on none to test the policy itself. paintTestImage(input, testInputKey) returns a TestInputs.TestImage: upload its png() bytes as the whole image, or encode its rgba() pixels (width() by height()) in another format. An image with anything else drawn on or around the test image, apart from a plain single-colour border, is moderated as ordinary content. A signal name stands for its image scenario, so "sexual.adult" stands for adult imagery rather than explicit text. A scenario too large for a test image throws sdk/invalid-argument; split it or use a text code.

Last updated

Signing in

Signing out

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies