Rust testing

Use calmlens::testing to test your Rust SDK integration offline, with an in-memory CalmLens or queued responses.

Setup

The mock is behind the testing feature, so enable it for tests only:

cargo add --dev calmlens --features testing

MockServerClient::in_memory(options) runs an in-memory CalmLens behind the real 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, retries and error handling.

use calmlens::{models::*, testing::{MockOptions, MockOutcome, MockServerClient}};

#[tokio::test]
async fn hides_blocked_posts() -> calmlens::Result<()> {
    let mock = MockServerClient::in_memory(MockOptions::new())?;
    let asset = mock
        .assets()
        .create(SubmitAsset::new("photo.png", Content::bytes(b"png".to_vec(), "image/png")))
        .await?; // pending
    mock.complete_processing(&asset.id, Some(MockOutcome::Blocked.into()))?;
    let current = mock.assets().retrieve(AssetId::new(&asset.id)).await?;
    assert_eq!(current.classification.moderation.status, AssetModerationStatus::Blocked);
    Ok(())
}

When the code under test takes a ServerClient, pass it mock.client(). The returned client answers from the same mock and records its requests in the same log. With the blocking feature, mock.blocking()? returns a blocking::ServerClient wired to the same mock.

Options

OptionEffect
moderateDecides each asset the mock moderates (see Moderation decisions).
api_keyA key from create_mock_api_key(&[MockApiKeyGrant::download()]) for private CDN reads. The default key has none; change it later with mock.set_api_key_grants(&grants).
create_id, nowDeterministic IDs and timestamps. The default clock moves on by at least a millisecond per reading, so assets created in a row get increasing created_at.
project_id, api_base_url, cdn_base_urlThe mock's project and URLs. The project defaults to project-1, as for MockServerClient::new().
max_retriesRetries of repeatable requests; 0 by default.
upload_timeout, max_response_bytes, part_size_bytesThe client's binary upload timeout, largest response body and part size, as on ServerClient::builder. Content larger than the part size goes to the in-memory API in parts, which replays parts it already has, so a repeated upload with the same idempotency_key resumes.

Moderation decisions

The mock doesn't classify content. MockOptions::moderate decides each asset the mock moderates. It receives a MockModerationInput with:

  • asset: the stored asset, still processing.
  • content: the uploaded bytes, and text for a plain-text upload such as text().classify. Both are None when there is no content, such as for a website.
  • trigger: why the asset is moderated: MockModerationTrigger::Upload, Retry (after assets().retry), Rerun (after assets().explain with rerun) or 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 MockOutcome (Pending, Failed, Allowed, Limited, AgeRestricted, Blocked or Purged), a MockDecision, or a calmlens::Result of either, so it can use ?. An error it returns fails the request that triggered it. A Failed asset gets the failure reason processing-error, and Purged also removes the content. Without moderate, queued uploads, retries and reruns stay pending and everything else is allowed; input.default_decision() returns that default.

MockDecision::new(status) builds a decision with findings: flag(category, score, qualifiers) records a category's score from 0 to 1 and its qualifiers' scores, and not_evaluated(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 flagged_categories lists the categories the decision acted on (categories scored 0.5 or more, unless the status is Allowed). An unknown category or qualifier, a score outside 0 to 1, a category used twice, or findings on a Pending or Failed decision fail with sdk/invalid-argument.

use calmlens::{models::*, testing::*};

let mock = MockServerClient::in_memory(MockOptions::new().moderate(|input: &MockModerationInput| {
    if input.content.text.as_deref().is_some_and(|text| text.contains("kill")) {
        MockDecision::new(MockOutcome::Blocked).flag("violence", 0.92, &[("violence-threat", 0.9)])
    } else {
        Ok(input.default_decision())
    }
}))?;
let comment = mock.text().classify(ClassifyText::new("I will kill you")).await?;
assert_eq!(comment.classification.moderation.flagged_categories, vec![ClassificationCategory::Violence]);

A moderate callback decides queued uploads straight away too. Return MockOutcome::Pending for them (input.queued with the Upload trigger) to finish them later. The callback runs while the mock answers a request, so it must not call the mock.

Finish processing

mock.complete_processing(asset_id, decision) finishes processing a pending asset as CalmLens would, with Some(decision) or else the one moderate returns for the Complete trigger (allowed by default). 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.

mock.with_storage(|storage| ...) reads or changes the stored assets, folders, events and content directly.

What the mock simulates

SimulatedBehaviour
Assets and foldersCreate, retrieve, list (filters with ;, , and parenthesised groups, including folderId, sort and cursors that resume after the last item returned), list children, update, move, delete, delete content, retry, explain, decide, keyword search (every query word must match a searchable field, ranked by the API's keyword score) and signed URLs. Folders list by name (or by createdAt with sort), hash lists, entries and lenses newest first, and policies oldest first, all with cursors. Every list returns 50 items unless page_size says otherwise, and an unknown or repeated sort field fails with validation/invalid-request.
CDNcdn().serve returns stored bytes with their content type, Cache-Tag, the CDN's protection headers (and, for images, ETag and Expires), and 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). Blocked, purged and failed assets, and assets whose content was removed, get 403 asset/not-available whatever the key. Age-restricted ones requested without viewer_claims: Some(ViewerClaims { age_confirmed: Some(true), ..Default::default() }) get 403 viewer/age-confirmation-required whatever the key, and private ones are served only to a key with Download assets. A classified image's placeholder resource is a small PNG of its ThumbHash. URLs from cdn().sign_asset_url are served, /info included, until they expire, and mock.fetch_cdn(url) loads one as a browser would, without the API key.
ErrorsThe API's codes, statuses, details and request IDs (in the x-request-id header and the error body's requestId), including validation/invalid-request errors that list each field's issue in details.issues; idempotency keys replay the first response.
EventsEvery upload adds asset.uploaded, then asset.classified and the automated asset.<status> (whose actor is automated) once it is decided, or asset.failed.
WaitingRetry backoff and wait_for_decision advance a virtual clock (mock.elapsed()) instead of taking real time, so an asset that stays queued or processing fails with sdk/timeout at once. This applies to MockServerClient::new() and from_builder too.

More of the mock's behaviour:

  • Filters work like the API's: the documented asset fields with ==, !=, >, >=, <, <=, =in= and =out=, ; binding tighter than ,, and * in an == or != value matching any run of characters regardless of case. Any other field or operator, such as =like= or =gt=, fails with 400 filter/invalid. A list cursor continues only the query it came from, and assets created or deleted between pages are neither repeated nor skipped.
  • Keyword search requires every query word to appear in the name, ID, external ID, description, tags, type, content format or extension, or moderation status, and ranks by score, then newest first.
  • Batches apply at once, in request order; mock assets have no safety holds.
  • Finished processing removes the content unless the upload sets keep_content_after_processing. A Purged decision removes it with the reason policy. The moderation input's bytes joins multipart parts in order, and is None once the content is removed.
  • Hash list entries can be added from a stored asset's content.perceptualHash, but uploads aren't matched against hash lists. Lenses are stored and can be listed, created, changed and deleted, but the mock doesn't classify or transform content.
  • The project starts on the organisation's own General preset policy, Live. The mock's presets have one release, version 1, whose settings give every category its default action (allow for personal information and profanity, block otherwise) and no rules; upgrade therefore fails with 409 policy/preset-update-unavailable. Settings missing a category, or a category's action, allowances or restrictions, fail with validation/invalid-request. Uploads are never decided by a policy.
  • A completed image's classification.link_detection is evaluated with no QR codes or links unless the upload turns link detection off, and ocr, person_detection and face_detection are evaluated with nothing found when the upload turns them on. The mock reads no text, codes, people or faces.
  • The CDN also refuses assets still uploading with 403 asset/not-available, and sends x-content-type-options: nosniff and a sandboxing content-security-policy.
  • Queued responses carry an x-request-id unless you set one, and a declared content-length over max_response_bytes fails as it would over the network.
  • with_storage exposes assets, folders, hash_lists, hash_list_entries, content and events in the API's JSON shape. New objects get IDs like the API's: their kind's prefix, _ and 20 random base62 characters, such as asset_5Gm2Rk8XqT3wLp9VbN4c. create_id receives the prefix: asset, fldr, hl, hle, lens, evt or rev.

Events and reviewer decisions

mock.enqueue_event(event) adds an event to the feed that events().list returns after cursors taken earlier, 50 per page by default; an event about a stored asset carries the asset's snapshot, and an asset.<status> event the moderation status it announces; an unreadable cursor fails with 400 cursor/invalid. Deleting an asset or its content and retrying it add asset.deleted, asset.content-removed and asset.retried events, as the API does. assets().explain with rerun 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 complete_processing.

assets().decide(DecideAsset) works as in the API: it validates the decision and note, refuses an asset that is still uploading or processing with 409 asset/processing, lets an undecided asset only be blocked or purged (409 asset/decision-not-allowed), refuses the asset's current status with 409 asset/decision-unchanged, and lets purged content only be blocked (409 asset/content-purged).

To simulate a reviewer's decision without those checks, mock.decide(asset_id, decision) takes an AssetModerationDecision, such as AssetModerationDecision::Blocked (Allowed, Limited, AgeRestricted, Blocked or Purged; an unknown value fails with sdk/invalid-argument), records it in the asset's manual_reviews and adds the matching asset.<decision> event, whose actor is a user, with severity low for allowed and limited, high otherwise. A purged decision removes the content and first adds asset.content-removed. The report stays as moderation left it. wait_for_decision reads the stored asset, so it sees the decision.

Recorded requests and failures

requests() and last_request() return the captured requests with their method, url, path, decoded query (query_param(name)), headers (header(name)), body, json() and response_status, the status the mock answered with (None when the request failed without a response). path is relative to the API (or CDN) base URL, with each segment decoded, such as /projects/project-1/events. Streamed uploads are captured too. clear_requests() forgets the requests captured so far, and mock.sleeps() returns the waits between retries and decision checks.

mock.fail_next_request(failure, MockFailureOptions::new()) fails the next request without running it: MockFailure::TransportError (sdk/transport-error), MockFailure::Timeout (sdk/timeout) or MockFailure::Api(code), that API error with its HTTP status. MockFailureOptions::operation("assets.create") limits the failure to the next request of that operation, named by the JavaScript SDK's method names, such as assets.create or assets.uploadPart; an unknown name fails with sdk/invalid-argument. For an API error, details(map) sets the error's details and retry_after(seconds) answers with a Retry-After header, so you can test code that reads error.details() or error.retry_after(). A transport error or timeout has no response, so either option with one fails with sdk/invalid-argument. A call that fails queues nothing. Each queued failure fails one request, so a retry takes the next queued failure or reaches the in-memory API.

mock.fail_next_request(
    MockFailure::Api(ErrorCode::WebsiteRateLimitExceeded),
    MockFailureOptions::new().retry_after(30),
)?;
let error = mock.assets().list(ListAssets::default()).await.unwrap_err();
assert_eq!(error.retry_after(), Some(std::time::Duration::from_secs(30)));

Both mocks turn retries off by default, unlike the real client, so each call uses one response. Set max_retries on MockOptions to test retries with the in-memory mock, and build a queued mock like a real client: MockServerClient::from_builder(ServerClient::builder(key, project).max_retries(2)).

Queued responses

MockServerClient::new() answers requests from a queue instead, for exact request and error tests. Queued responses also take precedence in an in-memory mock. With MockServerClient::new(), an empty queue fails with sdk/transport-error without making network calls.

use calmlens::{models::*, testing::MockServerClient};

#[tokio::test]
async fn reports_timeouts() -> calmlens::Result<()> {
    let mock = MockServerClient::new()?;
    mock.enqueue_timeout();
    let error = mock.events().list(ListEvents::default()).await.unwrap_err();
    assert!(error.is_timeout());
    let request = mock.last_request().unwrap();
    assert_eq!(request.path, "/projects/project-1/events");
    Ok(())
}
MethodQueues
enqueue(status, model)A JSON response from a model or serde_json::Value
enqueue_api_error(code, message)The API's error for code, with the HTTP status the API uses for it
enqueue_response(MockResponse)A response with headers, such as a CDN response with content-type or a 429 with retry-after
enqueue_raw(status, bytes)A raw body
enqueue_timeout(), enqueue_hang(), enqueue_transport_error(message), enqueue_error(error)A failure; enqueue_hang() times out when the attempt's timeout passes on the mock's clock
use calmlens::{models::*, testing::MockServerClient, ServerClient};

async fn moderate_bio(client: ServerClient, bio: &str) -> calmlens::Result<Asset> {
    client.assets().classify(SubmitAsset::text(bio)).await
}

#[tokio::test]
async fn allows_bios() -> calmlens::Result<()> {
    let mock = MockServerClient::new()?;
    mock.enqueue(
        200,
        Asset::new("asset-1", AssetClassificationStatus::Completed, AssetModerationStatus::Allowed),
    );
    let asset = moderate_bio(mock.client(), "Hello").await?;
    assert_eq!(asset.id, "asset-1");
    assert_eq!(mock.requests().len(), 1);
    Ok(())
}

Webhook handlers

Build a delivery body from an event with WebhookEventPayload::from_event, the same conversion CalmLens applies before sending: the body is the event in the shape events().list returns, with no data envelope. Sign it with calmlens::create_webhook_headers(body, delivery_id, timestamp, secret), which returns all of a delivery's headers (pass the current Unix time, since handlers reject deliveries more than 5 minutes old), or build only the signature with calmlens::create_webhook_signature_header(body, timestamp, secret). Both are in the crate root, not calmlens::testing, and need no feature.

Upload tokens

To compare whole upload tokens, sign them with calmlens::testing::sign_upload_token(api_key, options, now_ms, nonce).

Generate test inputs

calmlens::testing generates authenticated test inputs from your project's secret test input key. CalmLens recognises them only in projects with Test inputs turned on. generate_test_text_code(scenario, test_input_key) returns a text code to submit as the whole text: text with anything else around the code is moderated as ordinary content. generate_media_test_code(signal, test_input_key) returns a phrase to read aloud or show in a video. The scenario is a &TestInput, which lists instances (each a TestInputInstance with category, qualifiers and optional score and action) and optional regional_actions and unassessed_categories, or a category name such as "violence" for one instance of it. TestInputPreset holds the portal's presets. An invalid key or scenario returns an error with ErrorCode::InvalidArgument.

use calmlens::testing::{
    generate_media_test_code, generate_test_text_code, paint_test_image, TestInput, TestInputInstance,
    TestInputPreset,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let test_input_key = std::env::var("CALMLENS_TEST_INPUT_KEY")?;
    let harassment = |qualifiers: &[&str], action: &str| TestInputInstance {
        category: "harassment".into(),
        qualifiers: qualifiers.iter().map(|qualifier| qualifier.to_string()).collect(),
        action: Some(action.into()),
        ..Default::default()
    };

    // Choose each instance's outcome: the strongest action wins
    let text = generate_test_text_code(
        &TestInput {
            instances: vec![
                harassment(&["harassment-abuse", "harassment-documentary"], "limit"),
                harassment(&["harassment-threat"], "limit"),
                harassment(&["harassment-abuse"], "block"),
            ],
            ..Default::default()
        },
        &test_input_key,
    )?;

    // Regional delivery outcomes without category findings
    let regional = generate_test_text_code(
        &TestInputPreset::RegionalDelivery.input(),
        &test_input_key,
    )?;

    // A test image to upload on its own: it survives JPEG, WebP and resizing
    let image = paint_test_image("violence", &test_input_key)?;
    std::fs::write("test-image.png", &image.png)?;

    // A phrase to read aloud or show in a video
    let phrase = generate_media_test_code("violence", &test_input_key)?;
    println!("{text}\n{regional}\n{phrase}");
    Ok(())
}

Set action on every instance to choose its outcome independently of the project policy, or on none to test the policy itself. paint_test_image(scenario, test_input_key) returns a 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 stands for its image scenario, so "sexual.adult" stands for adult imagery rather than explicit text. A scenario too large for a test image returns ErrorCode::InvalidArgument; 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