Python testing

Use calmlens.testing to test your Python SDK integration offline. Keep calmlens.testing out of production imports.

Setup

from calmlens import CalmLensAPIError, CalmLensError
from calmlens.testing import MockCalmLensServerClient

client = MockCalmLensServerClient(project_id="proj_8fK2mQx7Lp4NvB3tRz9Y", timeout=5)
assert client.text.classify(text="Hello").classification.moderation.decision == "allowed"
assert client.requests[-1].path == "/projects/proj_8fK2mQx7Lp4NvB3tRz9Y/assets"

MockCalmLensServerClient is the real client with an in-memory API behind it, so every call goes through the real validation, encoding, error handling and retries. It accepts the real client's api_key, project_id, base_url, cdn_base_url, timeout, upload_timeout, connect_timeout, max_retries, max_response_bytes, part_size_bytes, app_info, logger and on_attempt; without them, it uses a mock key with no grants and the project ID project-1 (MOCK_PROJECT_ID). The in-memory API answers with the same status codes, error bodies and headers as CalmLens, including request IDs and idempotent replays. For async code, wrap it: AsyncCalmLensServerClient.from_client(MockCalmLensServerClient()).

Options

Configure moderation, IDs, the clock and storage in mock_options:

client = MockCalmLensServerClient(mock_options={
    "moderate": lambda moderation: "blocked" if "spam" in (moderation.content.text or "") else "allowed",
})
KeyEffect
moderateDecides each asset the mock moderates (see Moderation decisions).
create_idReturns new IDs. It receives the kind's prefix (asset, fldr, hl, hle, lens, evt or rev). By default, like the API, an ID is the prefix, _ and 20 random base62 characters, such as asset_e5Gm2Rk8XqT3wLp9VbN4.
nowReturns the current time in milliseconds. The default clock moves on by at least a millisecond per reading, so assets created in a row have increasing created_at values; a now you pass is used as is.
database_storage, image_storageThe stores behind the mock, such as an InMemoryMockDatabaseStorage you keep a reference to.

An unknown key raises sdk/invalid-config. The stores hold each record as the API's JSON, with camelCase keys, as to_dict() returns it. Inspect or seed them between calls:

from calmlens.testing import MockCalmLensServerClient

client = MockCalmLensServerClient(mock_options={
    "now": lambda: 123,
    "create_id": lambda prefix: f"{prefix}_00000000000000000001",
})
client.text.classify(text="Hello", external_id="c-1")
assert client.database_storage.assets["asset_00000000000000000001"]["createdAt"] == 123

Pass api_key=create_mock_api_key([{"actions": ["assets:download"], "folder_id": None, "include_subfolders": True}]), from calmlens.testing, for a key with specific grants, such as assets:download for private CDN reads, and change them later with client.set_api_key_grants([...]), as editing the key in the portal would: the key, and the idempotency keys it used, stay the same. The default key has no grants.

Moderation decisions

The mock doesn't run a moderation model, fetch remote URLs or transform media. mock_options["moderate"] decides each asset it moderates, given a MockModerationInput with:

  • asset: the stored asset, still processing, as an Asset.
  • content: the uploaded bytes, with multipart parts joined in order, 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: 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 status, pending, failed, allowed, limited, age-restricted, blocked or purged (which also removes the content), or a decision built with mock_decision. A failed asset gets classification.failureReason processing-error and can be retried. A classified asset with a preview gets a ThumbHash in content.preview, which goes when its content is removed. Without moderate, queued uploads and retries stay pending and everything else is allowed; default_moderate is that behaviour, for a moderate function to fall back on.

mock_decision(status) builds a decision with findings: .flag(category, score, qualifiers) records a category's score from 0 to 1 and, optionally, its qualifiers, as a dict of scores by name or a list of names, each scored 1, .not_evaluated(category) marks a category as not assessed, and .pending_review(reason, uncertain_categories=()) leaves the decision waiting for human review (sampled, or uncertain with the categories that made it so), which sets classification.moderation.pending_review. client.decide clears it, as the review queue does; assets.decide leaves it. Each returns the decision, so calls chain. 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 status, category or qualifier, qualifiers that are neither a dict nor a list of names, a score outside 0 to 1, a category used twice, findings or a pending review on a pending or failed decision, or a pending review with another reason, or with uncertain categories when sampled, raise sdk/invalid-argument.

Use .with_ocr(text, text_regions) and .with_link_detection(qr_codes, links) on a mock decision to supply findings for an image, as dicts in the API's shape. 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 dicts in the API's shape ({"box", "confidence"}, and an optional "ageRange" for a face). 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 ageEstimation. Without them, the mock reports no people or faces.

from calmlens.testing import MockCalmLensServerClient, MockModerationInput, mock_decision


def moderate(moderation: MockModerationInput):
    if moderation.content.text and "kill" in moderation.content.text:
        return mock_decision("blocked").flag("violence", 0.92, {"violence-threat": 0.9})
    return "allowed"


client = MockCalmLensServerClient(mock_options={"moderate": moderate})
comment = client.text.classify(text="I will kill you")
categories = comment.classification.moderation.categories
assert categories is not None and categories["violence"].score == 0.92
assert comment.classification.moderation.flagged_categories == ["violence"]

A moderate function decides queued uploads straight away too. Return pending for them (moderation.queued and moderation.trigger == "upload") to finish them later.

Finish processing

client.complete_processing(asset_id, decision=None) finishes processing a pending asset as CalmLens would, with the decision you pass or else the one moderate returns for the complete trigger (allowed by default). It raises 404 asset/not-found for an unknown asset and sdk/invalid-argument for an asset that isn't processing:

client = MockCalmLensServerClient()  # queued uploads stay pending
upload = client.assets.create(name="photo.png", content={"data": png_bytes, "type": "image/png"})  # pending

client.complete_processing(upload.id, mock_decision("age-restricted").flag("sexual", 0.8))
decided = client.assets.wait_for_decision(asset_id=upload.id)
assert decided.classification.moderation.decision == "age-restricted"

What the mock simulates

  • Lists return 50 items unless page_size says otherwise, and honour filters (with ; binding tighter than ,, and parentheses for grouping) and sort; folders list by name unless sort says otherwise, and policies oldest first. Their cursors resume after the last item returned, so assets created or deleted between pages are neither skipped nor repeated, and a cursor only continues the query it came from.
  • Search works like the API's keyword search: every word of the query must appear, case-insensitively, in an asset's name, ID, external ID, description, tags, type, content format or extension, or moderation status. A query uses at most 8 distinct words. Results carry the API's keyword scores and matched_fields, best match first and then newest first, and semantic_status is disabled whatever the mode.
  • Validation: out-of-range page sizes, sort fields and search queries fail with 400 validation/invalid-request, listing the field and its issue, such as validation/too-small, in details["issues"].
  • Idempotency keys are honoured by uploads, assets.decide, hash_lists.add_entry and assets.request_review, as CalmLens does, and ignored by other requests. They replay the first response, with its status, and a request that fails frees its key. A key reused for a different request raises 409 idempotency/key-reused; file uploads are compared by their query, their options and length, not their bytes. Keys must be 1 to 255 printable ASCII characters without a space at either end, or the request fails with 400 idempotency/invalid-key.
  • Filters work like the API's: the documented asset fields, such as classification.moderation.decision and content.format, with ==, !=, >, >=, <, <=, =in= and =out=, combined with ;, , and parentheses. * in an == or != value matches any run of characters, ignoring case. Any other field or operator, such as =like= or =gt=, raises 400 filter/invalid. Assets list newest first by default.
  • Content retention: like CalmLens, content is stored when retention is on, as it is by default for new mock projects. When it is off, it is temporary and is removed (removal_reason retention) once classification completes, after which cdn.serve answers 404 with 404 asset/not-found, as for an unknown asset. Retain content to serve it after a decision.
  • Folders have unique names among siblings (case-sensitive). Deleting a folder that isn't empty raises 409 folder/not-empty with hasAssets and hasChildren in details.
  • Lenses: an unchanged definition returns the saved lens, and a changed one changes it in place. lenses.create raises 409 lens/identifier-taken for an identifier the project already has, and the lens methods raise 404 lens/not-found for an unknown lens ID.
  • Policies: the project starts on the organisation's own General preset policy, in mode 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, so policies.upgrade raises 409 policy/preset-update-unavailable. Settings that don't define every category, each with its action, allowances and restrictions, raise 400 validation/invalid-request. Uploads are never decided by a policy.
  • Hash lists and their entries live in database_storage.hash_lists and database_storage.hash_list_entries; deleting a list deletes its entries. A decided image's content.perceptual_hash is the SHA-256 of its bytes, standing in for its image hash, so add_entry(asset_id=...) copies it; other assets have none and raise 409 hash-list/asset-not-hashed. An image with exactly the bytes of an entry's image matches it: classification.moderation.raw.hash_matches lists the match 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.
  • Review requests: assets.retrieve_by_external_id finds the asset with that externalId. 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, or whose content is purged or removed, with 409 asset/not-reviewable and its details["reason"], as CalmLens does. client.decide settles the review, so the asset can be reported again.
  • API key: the mock's key has the ID MOCK_API_KEY_ID (from calmlens.testing), so the events its requests record have that actor.id, and its assets.decide reviews that decided_by.id.
  • Lifecycle events: every upload adds asset.uploaded to the events feed, then asset.classified and the automated asset.<status> (whose actor is automated) once it is decided, or asset.failed. Deleting an asset, removing its content and retrying it record asset.deleted, asset.content-removed and asset.retried events.
  • Waiting takes no real time: assets.wait_for_decision reads the stored asset, returns a completed or failed asset, and raises sdk/timeout straight away for one that stays queued or processing. Retry waits and deadline_ms run on the mock's clock, which only its waits move.
  • CDN: cdn.serve and cdn.get_asset_info answer like the CDN, by asset ID or ext: external ID, and client.fetch_cdn(url) fetches one of its URLs as a browser would, without the API key, such as a signed asset URL with a resource appended. Signed asset URLs work until they expire (403 signed-url/expired), and serve /original only when signed for it (403 signed-url/original-not-granted). The mock serves a limited asset like an allowed one. A private asset fetched without a grant or the API key, as a browser would with client.fetch_cdn, returns 404 with 404 asset/not-found whatever its state, like an unknown asset. Every resource but display info of an asset whose content was removed returns 404 with 404 asset/not-found too, whatever the key. For content resources requested with the API key, a grant or a public asset, blocked, purged and failed assets return 403 with 403 asset/not-available, and age-restricted assets requested without viewer_claims={"age_confirmed": True} return 403 with 403 viewer/age-confirmation-required. For the API key, private assets then return 403 with 403 auth/permission-denied unless the key has assets:download. Unknown assets return 404 with 404 asset/not-found.
  • CDN headers: served content has 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), with the CDN's Cache-Tag and protection headers, and an ETag for images. The placeholder resource is a classified image's blurred PNG. A public asset's placeholder is served to anyone whatever its decision, blocked included, so a page can show it in the asset's place; a private asset's requires a signed URL or download permission; purged assets, assets with removed content and assets under a safety hold have no placeholder.
  • Served URLs: client.serve_url(url, 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.
  • 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

client.enqueue_event(type, facts=..., asset_id=..., severity=..., title=..., actor=...) adds an event to the feed that events.list and events.iter return. Its actor is the mock's API key unless you pass one. An event with an asset_id takes that asset's next asset_sequence, which the asset's event_sequence then reports, and changes nothing else about the asset; events.retrieve_asset(event) returns the stored asset. Every asset the mock returns has the event_sequence of its latest event. It returns the event as an Event; facts and actor take the API's JSON ({"key": ..., "value": ...}, {"type": ..., "id": ...}). The feed's cursors are positions in it, so an event added later reaches a next_cursor taken before it:

cursor = client.events.list().next_cursor
client.enqueue_event("asset.allowed", actor={"type": "automated", "id": None})
assert client.events.list(cursor=cursor).items[0].type == "asset.allowed"

assets.decide validates and records a decision as the API does. It refuses a note that is empty or longer than 1,499 characters, a purge without confirm_purge=True, anything but a block or purge while moderation is pending (409 asset/decision-not-allowed), the asset's current status (409 asset/decision-unchanged), anything but a block once purged (409 asset/content-purged) and an asset that is still uploading or processing (409 asset/processing). The review and its event name the mock key as the reviewer.

client.decide(asset_id, "blocked") is a test hook for a reviewer's decision, without those checks or a note. It applies the decision (allowed, limited, age-restricted, blocked or purged; purged also removes the content) and adds the matching asset.<decision> event, whose actor is a user, with asset-type, asset-name and note (None) facts. The review joins manual_reviews, a pending_review is cleared and the rest of the report stays as it was; pending and failed are not decisions and raise sdk/invalid-argument. To finish processing as CalmLens's moderation would, use complete_processing.

Recorded requests and failures

client.requests records each request, oldest first, as a MockRequest with its method, url, path, decoded query, body (the API's JSON, as sent), headers (with get_header(name) for a case-insensitive lookup) and status. path is relative to the API or CDN base URL, so it leaves out /v1, with each segment decoded, such as /assets/<id> or /projects/project-1/assets. status is the HTTP status the in-memory API answered with, or None for a request that failed without a response. client.requests returns copies, and repr leaves out the headers. client.clear_requests() forgets the requests recorded so far.

client.fail_next_request(failure, operation=..., times=...) fails the next request, or the next one that method sends, without running it, or the next times of them:

client.fail_next_request("timeout", operation="text.classify")

"transport-error" and "timeout" fail like a network failure (sdk/transport-error and sdk/timeout), an API error code, such as server/internal-error for a 500, fails with that error and its HTTP status, and an exception you pass is raised. A request counts for every method that sends it, so assets.wait_for_decision polls count as assets.retrieve. 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. An operation that isn't a client method that sends requests raises sdk/invalid-argument.

For an API error, details sets the error's details and retry_after answers with a Retry-After of that many whole seconds, so you can test code that reads error.details or error.retry_after. They apply only to an API error: passing either with "transport-error", "timeout" or an exception raises sdk/invalid-argument, as does times that isn't a positive whole number. Failures queue in order, and each request takes the oldest one that matches it, so a retry takes the same failure again until its times are used up, then the next queued failure or the in-memory API:

client.fail_next_request("upload/rate-limit-reached", retry_after=30)
try:
    client.assets.list()
except CalmLensAPIError as error:
    assert (error.status, error.retry_after) == (429, 30)

client.fail_requests(failure, operation=...) fails every matching request until client.clear_failures(), which also drops the failures fail_next_request queued:

client.fail_requests("server/internal-error", operation="assets.retrieve")
try:
    client.assets.retrieve(asset_id=asset_id)
except CalmLensAPIError as error:
    assert error.status == 500
client.clear_failures()

enqueue_error also fails the next request and leaves storage unchanged: a CalmLensError becomes an API error response with the matching HTTP status, and a network exception fails like a real connection: TimeoutError as sdk/timeout, and other OSErrors and http.client errors as sdk/transport-error, with the exception as __cause__.

client.enqueue_error(TimeoutError("timed out"))  # next call raises CalmLensTimeoutError ("sdk/timeout")
client.enqueue_error(CalmLensError("asset/not-found"))  # next call raises CalmLensNotFoundError with status 404

The mock's max_retries defaults to 0, unlike the real client, so a failed request fails once; pass max_retries to test retry handling. Retry waits take no real time.

Webhook handlers

These helpers come from calmlens. to_webhook_event_payload(event) returns the body a webhook delivers for an event from events.list (or enqueue_event), which is that event's JSON, and create_webhook_headers(payload, delivery_id, secret) the headers of a signed delivery, using the current time unless you pass timestamp=. Use them together to call your handler as CalmLens would. create_webhook_signature_header(payload, timestamp, secret) builds only the x-calmlens-signature value.

is_test_webhook_event(event) is True for events carrying the test fact that test sends from the portal and the CLI add.

Upload tokens

calmlens.testing.sign_upload_token(api_key, now=..., nonce=..., upload_preset_id=..., external_id=..., expires_in=...) signs an upload token at a fixed time and nonce, to compare with a known token.

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. A scenario is a SignedTestInput dict with the API's field names: instances (each with category, qualifiers and optional score and action), and optional regionalActions and unassessedCategories. Pass a category, such as "violence", instead of a scenario for one instance of it. TEST_INPUT_PRESETS holds the portal's presets (clean, limited, adult_text, regional_delivery and others); copy one with copy.deepcopy before changing it. An invalid key or scenario raises CalmLensInvalidArgumentError with code sdk/invalid-argument.

import os
from calmlens.testing import TEST_INPUT_PRESETS, generate_media_test_code, generate_test_text_code, paint_test_image

test_input_key = os.environ["CALMLENS_TEST_INPUT_KEY"]

# Choose each instance's outcome: the strongest action wins
text = generate_test_text_code({"instances": [
    {"category": "harassment", "qualifiers": ["harassment-abuse", "harassment-documentary"], "action": "limit"},
    {"category": "harassment", "qualifiers": ["harassment-threat"], "action": "limit"},
    {"category": "harassment", "qualifiers": ["harassment-abuse"], "action": "block"},
]}, test_input_key)

# Regional delivery outcomes without category findings
regional = generate_test_text_code(TEST_INPUT_PRESETS["regional_delivery"], test_input_key)

# A test image to upload on its own: it survives JPEG, WebP and resizing
image = paint_test_image("violence", test_input_key)
with open("test-image.png", "wb") as file:
    file.write(image.png)

# A phrase to read aloud or show in a video
phrase = generate_media_test_code("violence", test_input_key)
print(text, regional, phrase, sep="\n")

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 PaintedTestImage: 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 raises sdk/invalid-argument; 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