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"]["status"] == "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 and part_size_bytes; 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.

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_5Gm2Rk8XqT3wLp9VbN4c.
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 createdAt 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. Inspect or seed the stores 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([...]), 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: a copy of the stored asset, still processing.
  • 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), rerun (after assets.explain with rerun=True) 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 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, retries and reruns 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' scores, and .not_evaluated(category) marks a category as not assessed. Both return 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 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 used twice, or findings on a pending or failed decision raise sdk/invalid-argument.

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")
assert comment["classification"]["moderation"]["categories"]["violence"]["score"] == 0.92
assert comment["classification"]["moderation"]["flaggedCategories"] == ["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 records no review, so the asset can still be moderated again with assets.explain. It raises 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:

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"]["status"] == "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 matchedFields, best match first and then newest first, and semanticStatus 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 replay the first response, and a request that fails frees its key. A key reused for a different request raises 409 idempotency/key-reused; raw uploads are compared by their query, type 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.status 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 processingOptions.keepContentAfterProcessing is True; otherwise it is temporary and is removed (removalReason retention) once classification completes, after which cdn.serve answers 403 with 403 asset/not-available. Pass keepContentAfterProcessing: True to serve content 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 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. add_entry with an asset_id copies the asset's content.perceptualHash and perceptualHashQuality, which you seed through database_storage because the mock computes no hashes, and raises 409 hash-list/asset-not-hashed without one. Uploads are not matched against the lists.
  • 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. assets.explain with rerun=True records 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.
  • 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.
  • 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 with original=True (403 signed-url/original-not-granted). The mock serves a limited asset like an allowed one. Blocked, purged and failed assets, and assets whose content was removed, return 403 with 403 asset/not-available, whatever the key. Age-restricted assets requested without viewer_claims={"ageConfirmed": True} return 403 with 403 viewer/age-confirmation-required, whatever the key. Private assets 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 only when anyone may see the asset, otherwise private; max-age=31536000, immutable for images and max-age=3600 for other content), with the CDN's Cache-Tag and protection headers, and an ETag and Expires for images. The placeholder resource is a classified image's blurred PNG, public for every asset whatever its visibility or moderation status, and refused once the asset is purged or its content removed.

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 the asset_id of 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. The feed's cursors are positions in it, so an event added later reaches a nextCursor taken before it:

cursor = client.events.list()["nextCursor"]
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 manualReviews 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, with its method, url, path, decoded query, body, headers 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=...) fails the next request, or the next one that method sends, without running it:

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 fails with that error and its HTTP status, and an exception you pass is raised. A request counts for every method that sends it: a text.classify upload also counts as assets.classify, and assets.wait_for_decision polls as assets.retrieve. 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. Each queued failure fails one request, so a retry takes the next queued failure or reaches the in-memory API:

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

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 CalmLensAPIError 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, which is that event in the same shape, 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, options, now=..., nonce=...) 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. 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. 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 CalmLensValidationError 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

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