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.decision, Some(AssetModerationDecision::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.

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

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) or Complete (see below).
  • queued: true when CalmLens would queue the work rather than answer with the decision: queued uploads, retries 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 and retries 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, action, source and settings (the decision's action, with no rules), 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.

pending_review(reason, uncertain_categories) leaves a decided asset waiting for human review: classification.moderation.pendingReview holds the reason (sampled, or uncertain with the categories that made it so) and the time the decision was applied. mock.decide clears it, and assets().decide leaves it, as in the API. It fails with sdk/invalid-argument on a Pending or Failed decision, for any other reason, for a sampled reason with uncertain categories, and for an unknown category.

Use with_ocr(text, text_regions) and with_link_detection(qr_codes, links) on a mock decision to supply findings for an image, as TextRegion, DetectedQrCode and DetectedLink values. The mock reports each result when the corresponding feature is enabled. OCR text appears in content.extracted_text when the upload keeps its content.

Use with_person_detection(people) and with_face_detection(faces) to supply the people and faces an image holds, as DetectedPerson and DetectedFace values. The mock reports them when the upload turns person or face detection on, with a face's age_range only when it also turns on age estimation. Without them, the mock reports no people or faces.

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 fails with 404 asset/not-found for an unknown asset and sdk/invalid-argument for an asset that isn't processing.

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, 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 400 validation/invalid-request.
CDNcdn().serve returns stored bytes with their content type, Cache-Tag, the CDN's protection headers (and, for images, ETag), and Cache-Control as the CDN sets it (public files use public, max-age=86400, must-revalidate, unsigned private files use private, no-cache, signed files expire with the grant or after one day, and embed pages and requests with viewer claims use private, no-store). Every resource but display info of an asset whose content was removed gets 404 asset/not-found, as an unknown asset does, whatever the key. Content resources of blocked, purged and failed assets get 403 asset/not-available whatever the key. Age-restricted ones requested without .viewer_claims(ViewerClaims::new().age_confirmed(true)) 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; a public asset's is served to anyone whatever its decision, blocked included, so a page can show it in the asset's place, while a private asset's needs a signed URL or Download assets. 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. Without a grant or the API key, a private asset gets 404 asset/not-found whatever its state, including its placeholder and display info.
ErrorsThe API's codes, statuses, details and request IDs (in the x-request-id header and the error body's requestId), including 400 validation/invalid-request errors that list each field's issue in details.issues. Uploads, parts, assets().decide, hash_lists().add_entry and assets().request_review honour an Idempotency-Key, as CalmLens does: reusing it returns the first response with its status, reusing it for a different request fails with 409 idempotency/key-reused, and a request that failed frees its key. Other requests ignore it.
EventsEvery upload adds asset.uploaded, then asset.classified and the automated asset.<status> (whose actor is automated) once it is decided, or asset.failed. The mock's API key has the ID testing::MOCK_API_KEY_ID, so the events its requests record have that actor.id, and its assets().decide reviews that decided_by.id. Every asset the mock returns, from a request or a helper such as decide, has the event_sequence of its latest event at that moment.
WaitingRetry backoff, RequestOptions::deadline and wait_for_decision run on a virtual clock (mock.elapsed()), which only the mock's waits move, 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.

Additional simulated 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 retain_content. 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.
  • An upload with an API key that names upload_preset_id takes the folder, visibility and (unless the upload sets its own) processing options that upload_presets().ensure stored, as in the API. An unknown preset fails with 404 upload-preset/not-found, a disabled one with 403 upload-preset/disabled, a different folder or visibility with 400 upload-preset/field-not-allowed, and a type or size the preset doesn't accept with 415 upload/unsupported-type or 413 upload/too-large.
  • A decided image's content.perceptual_hash is the SHA-256 of its bytes, standing in for its image hash, so hash_lists().add_entry with an asset_id works; other asset types have none. An image with exactly the bytes of a hash list entry's image matches it: classification.moderation.raw lists the match under hashMatches with its list's action, and a block list blocks the image with source hash-list and records asset.hash-matched. Similar but different images never match in the mock. 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 400 validation/invalid-request. Uploads are never decided by a policy.
  • A completed image's classification.link_detection is evaluated unless the upload turns link detection off, and ocr, person_detection and face_detection are evaluated when the upload turns them on. The mock reads nothing in an image, so each reports only what the decision supplies (Moderation decisions): no text, codes, people or faces otherwise.
  • 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_e5Gm2Rk8XqT3wLp9VbN4. create_id receives the prefix: asset, fldr, hl, hle, lens, evt or rev.
  • mock.serve_url(url, MockServedUrl::new(content, content_type)) gives a URL content, bytes or a string, and a content type. A URL upload of it stores the content, passes it to moderate and takes its type from the content type, as an upload of those bytes would; text/html is a website, which stores nothing. A relative URL or an empty content type fails with sdk/invalid-argument.
  • Other URL uploads take their type from the file extension of the URL's path, ignoring case, the query and the fragment, since the mock fetches nothing: image for jpg, jpeg, png, gif, webp, avif, heic, heif, bmp, tif, tiff and svg; video for mp4, m4v, mov, webm, mkv and avi; audio for mp3, m4a, aac, wav, ogg, oga, opus and flac; multimedia-document for pdf, doc, docx, odt, ppt, pptx, odp and rtf; and plaintext-document for txt and md. Any other extension, such as html, or none gives a website.

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 an asset takes the asset's next asset_sequence; 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().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, except that a pending review is cleared. wait_for_decision reads the stored asset, so it sees the decision.

assets().retrieve_by_external_id finds the asset with that external_id. assets().request_review queues a review with the reason reported and its note, sets the asset's classification.moderation.pending_review and records asset.review-requested. While a review is waiting, it returns that review with HTTP 200. It refuses an asset that isn't decided yet, a child asset, or one whose content is purged or removed, with 409 asset/not-reviewable and its details.reason, as CalmLens does. mock.decide settles the review, so the asset can be reported again.

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 method, named as you call it, such as assets().create, assets().upload_part, cdn().serve or ensure_lenses; an unknown name fails with sdk/invalid-argument. times(n) fails that many requests instead of one, so a retry takes the same failure again until it is used up. mock.fail_requests(failure, options) fails every matching request until mock.clear_failures(), which also drops queued failures. Both classify methods upload, but a failure for one never fails the other: a text upload is text().classify's request, and a file or URL upload assets().classify's. 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. Failures queue in order, and each request takes the oldest one that matches it; once used up, a retry takes the next queued failure or reaches the in-memory API.

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

mock.fail_requests(MockFailure::TransportError, MockFailureOptions::new())?;
assert!(mock.assets().list(ListAssets::new()).await.is_err());
mock.clear_failures();

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::new()).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, Some(AssetModerationDecision::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 (under Project settings → Processing → Test inputs in the portal). Every project recognises inputs signed with its own key. 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

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