Ruby testing
Use CalmLens::MockServerClient from calmlens/testing to test your Ruby SDK integration offline.
Setup
require 'calmlens/testing'
key = CalmLens::MockServerClient.create_api_key([{actions: ['assets:download'], folder_id: nil, include_subfolders: true}])
mock = CalmLens::MockServerClient.new(api_key: key)
asset = mock.assets.classify(name: 'note', content: {plain_text: 'hello', type: 'text/plain'}, processing_options: {keep_content_after_processing: true})
mock.assets.retrieve(asset_id: asset['id'])['classification']['moderation']['status'] # => "allowed"
mock.assets.list(filter: 'classification.moderation.status==allowed')['items'].length # => 1
mock.cdn.serve(asset_id: asset['id'], resource: 'original').body # => "hello"The mock runs the real client's validation, encoding, retries and error handling, then answers from an in-memory stand-in for the API and CDN. It accepts project_id: (project-1 by default), api_key:, now:, create_id:, moderate: and the real client's settings, such as part_size_bytes:. Its max_retries: defaults to 0, unlike the real client, so a failed request fails once; set it to test how your code handles retries.
Moderation decisions
The mock does not classify content. moderate: is a callable that decides each asset the mock moderates. It receives a CalmLens::MockModerationInput with:
asset: the stored asset, still processing.content: the uploadedbytes(a multipart upload's parts joined in order), andtextfor a plain-text upload such astext.classify. Both arenilwhen there is no content, such as for a website.trigger: why the asset is moderated:upload,retry(afterassets.retry),rerun(afterassets.explainwithrerun: true) orcomplete(see below).queued:truewhen CalmLens would queue the work rather than answer with the decision: queued uploads, retries, reruns andcomplete.
It returns a status, pending, failed, allowed, limited, age-restricted, blocked or purged, or a decision built with CalmLens::MockDecision.of. A failed asset gets classification.failureReason processing-error. Without moderate:, queued uploads, retries and reruns stay pending and everything else is allowed. The callable runs while the mock answers a request, so it must not call the mock itself.
CalmLens::MockDecision.of(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 CalmLens::InvalidArgumentError (sdk/invalid-argument).
moderate = lambda do |input|
if input.content.text&.include?('kill')
CalmLens::MockDecision.of('blocked').flag('violence', 0.92, 'violence-threat' => 0.9)
else
'allowed'
end
end
mock = CalmLens::MockServerClient.new(moderate: moderate)
comment = mock.text.classify(text: 'I will kill you')
comment.dig('classification', 'moderation', 'categories', 'violence', 'score') # => 0.92
comment.dig('classification', 'moderation', 'flaggedCategories') # => ["violence"]A moderate: callable decides queued uploads straight away too. Return pending for them (input.queued && input.trigger == 'upload') to finish them later.
Finish processing
mock.complete_processing(asset_id, decision = nil) finishes processing a pending asset as CalmLens would, with the decision you pass (a status or a MockDecision) 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 CalmLens::NotFoundError (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 = CalmLens::MockServerClient.new # without moderate:, queued uploads stay pending
upload = mock.assets.create(name: 'photo.png', content: {base64: png_base64, type: 'image/png'}) # pending
mock.complete_processing(upload['id'], CalmLens::MockDecision.of('age-restricted').flag('sexual', 0.8))
mock.assets.wait_for_decision(asset_id: upload['id']).dig('classification', 'moderation', 'status') # => "age-restricted"Options
api_key: decides CDN reads of private content. The default key has no grants; a key from MockServerClient.create_api_key with an assets:download grant for the asset's folder can read it, and mock.api_key_grants = [...] changes the grants for later requests.
The default clock follows the system time but moves forward at least 1 ms per reading, so assets created in a row have increasing createdAt and list and search in a predictable order. A now: clock you pass is used as is.
New objects get IDs like the API's: their kind's prefix, _ and 20 random base62 characters, such as asset_5Gm2Rk8XqT3wLp9VbN4c. For predictable IDs, pass create_id:, a callable that receives the prefix (asset, fldr, hl, hle, lens, evt or rev) and returns the ID.
Change records through mock.state to arrange a test, such as mock.state.assets[id]['classification']['moderation']['status'] = 'blocked'.
What the mock simulates
- Assets you upload can be retrieved, listed, searched, moved, updated and deleted, with
nullfor fields that are not set, emptytagsandmetadatalists, and moderation fields that arenulluntil a decision. A decided image reports what the features its upload ran found: nothing, asocrand person and face detection when turned on andlinkDetectionunless turned off. Folders, multipart uploads (including content the client splits into parts, resumed with the same idempotency key), idempotency keys and lenses behave like the API's. - Content retention follows the API: content is removed with
removalReasonretention once classification is completed, unless the upload setskeep_content_after_processing: true. A purged outcome removes it with policy. Removing content also removes a classified image's ThumbHash and average colour. - Hash lists keep their entries until the list is deleted.
hash_lists.add_entry(asset_id:)uses the asset'scontent.perceptualHashandperceptualHashQuality, which you can set throughmock.state. Uploads are not compared with hash lists. - Folders and lenses: folder names are unique among siblings (case-sensitive) and listed by code point.
ensure_lenschanges a lens to the definition sent, andlenses.createrefuses an identifier the project already has with 409 lens/identifier-taken. - Policies: the project starts on the organisation's own General preset policy, with mode
live. The mock's presets have one release, version 1, whose settings give every category its default action (allowfor personal information and profanity,blockotherwise) and no rules, sopolicies.upgradefails with 409 policy/preset-update-unavailable. Settings that leave out a category, or a category'saction,allowancesorrestrictions, are refused as the API refuses them. Uploads are never decided by a policy. - Errors use the API's codes, HTTP statuses and body shape (
code,message,requestIdmatching thex-request-idheader, and adetailsobject), so retrieving an asset that was never uploaded (mock.assets.retrieve(asset_id: 'asset_5Gm2Rk8XqT3wLp9VbN4c')) raisesCalmLens::NotFoundErrorwith status404. - Validation runs in the API's order, with schema errors as 400 validation/invalid-request and HTTP 400, listing each field and its issue in
details['issues']: out-of-range page sizes have the issuevalidation/too-smallorvalidation/too-big, asortwith an unknown or repeated field, or too many fields,validation/invalid-value, multipart parts must arrive in order with 5 MiB until the last, multipart images can total at most 20 MiB, idempotency keys are 1 to 255 printable characters, and a request that fails frees its idempotency key. - List filters work like the API's: the documented asset fields with
==,!=,>,>=,<,<=, and=in=and=out=with a(value,value)list, joined by;(and), which binds tighter than,(or), and grouped with parentheses, such as(name==a.png,name==b.png);classification.moderation.status==blocked.*in an==or!=value matches any run of characters, ignoring case, and a comparison never matches a missing value. Any other field or operator, such as=like=or=gt=, raisesCalmLens::BadRequestErrorwith 400 filter/invalid. The sort is applied. - List cursors resume after the last item returned (folders list by name unless
sort:says otherwise), so assets created or deleted between pages are neither repeated nor skipped, and a cursor only continues the query it came from. - Search runs keyword search like the API: every word of the query (case-insensitive, up to 8) must appear in the asset's name, ID, external ID, description, tags, type, content format or extension, or moderation status. Results carry the API's keyword
scoreandmatchedFields, rank by score and then newest first, and reportsemanticStatusdisabled. - Waiting takes no real time: retries and decision checks don't sleep, and
assets.wait_for_decisionreturns at once for a decided asset and raisessdk/timeoutstraight away for one whose moderation stays pending. - CDN access: like the CDN, blocked, purged and failed assets, and assets whose content was removed, return
403with 403 asset/not-available. Age-restricted assets requested withoutviewer_claims: {age_confirmed: true}return403with 403 viewer/age-confirmation-required, whatever the key. Private assets return403with 403 auth/permission-denied unless the key has assets:download. - CDN responses carry the stored bytes with
content-type,content-length,x-request-id,cache-tag,x-content-type-optionsandcontent-security-policyheaders (andetagandexpiresfor images), andcache-controlas the CDN sets it (publiconly when anyone may see the asset, otherwiseprivate;max-age=31536000, immutablefor images andmax-age=3600for other content;private, no-storewhen the request carries viewer claims). Theplaceholderresource is a classified image's ThumbHash as a PNG, public for every asset whatever its visibility or moderation, and refused once the asset is purged or its content removed. URLs fromcdn.sign_asset_urlare served,/infoincluded, until they expire, andmock.fetch_cdn(url)loads one as a browser would, without the API key.
Events and reviewer decisions
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. Deletes, content removals and retries add the asset.deleted, asset.content-removed and asset.retried events the API records. 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 complete_processing. mock.enqueue_event adds others; one with the asset_id: of a stored asset carries that asset as it is now, as CalmLens's events do:
cursor = mock.events.list['nextCursor']
mock.enqueue_event(type: 'asset.allowed', asset_id: asset['id'], actor: {type: 'user', id: nil})
mock.events.each(cursor: cursor).map { |event| event['type'] } # => ["asset.allowed"]mock.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 is the mock key's, and its event's actor is the key (api-key).
mock.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) and adds the matching asset.<decision> event whose actor is a user; pending and failed are not decisions and raise sdk/invalid-argument. It leaves the moderation report as it was. A reviewer's purge removes the content with removalReason requested and first adds an asset.content-removed event. To finish processing as CalmLens's moderation would, use complete_processing.
Recorded requests and failures
mock.requests returns copies of every request received, oldest first, with method, url, path, decoded query, headers, body and status. path is relative to the API or CDN base URL, so it leaves out /v1, with each segment decoded. status is the HTTP status the mock answered with, or nil for a request that failed without a response:
request = mock.requests.last
request.method # => "GET"
request.path # => "/assets/project-1/<asset id>/original"
request.status # => 200mock.clear_requests forgets the requests recorded so far.
mock.fail_next_request makes the next request fail without running, as if it never completed. Pass transport-error (sdk/transport-error), timeout (sdk/timeout), an API error code (that error and its HTTP status) or an exception for the transport to raise. operation: limits the failure to the next request one method sends, and an unknown method name 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:
mock.fail_next_request('timeout', operation: 'text.classify')
mock.text.classify(text: 'hello') # raises CalmLens::TimeoutError (sdk/timeout)
mock.text.classify(text: 'hello').dig('classification', 'moderation', 'status') # => "allowed"
mock.fail_next_request('upload/website-rate-limit-reached', retry_after: 30)
mock.assets.list # raises CalmLens::RateLimitError with status 429 and retry_after 30Retry backoff takes no real time.
Queued responses
Queued responses and errors answer the next requests in order, before the stand-in:
mock.enqueue(status: 429, body: {code: 'upload/website-rate-limit-reached', message: 'Slow down'}, headers: {'retry-after' => '0'})
mock.enqueue_raw(body: 'not json')
mock.enqueue_error(Net::ReadTimeout.new) # raises CalmLens::TimeoutError (sdk/timeout)
mock.enqueue_error(Errno::ECONNRESET.new) # raises CalmLens::ConnectionError (sdk/transport-error)Webhook handlers
CalmLens.to_webhook_event_payload(event) returns the body a webhook delivers for an event from events.list, which has the same fields as the event, and CalmLens.create_webhook_headers(payload:, delivery_id:, secret:) returns the headers of a signed delivery, using the current time unless you pass timestamp:. Use them together to call your handler as CalmLens would:
event = mock.enqueue_event(type: 'asset.allowed', asset_id: asset['id'])
body = JSON.generate(CalmLens.to_webhook_event_payload(event))
headers = CalmLens.create_webhook_headers(payload: body, delivery_id: 'dlv_3Vm8Qk2Xt7Lp9Rb4Nw6C', secret: secret)CalmLens.create_webhook_signature_header(payload:, timestamp:, secret:) builds only the x-calmlens-signature value.
Upload tokens
CalmLens::MockServerClient.sign_upload_token(api_key, {upload_preset_id: 'preset_4Lk8Qw2Xm9Rt5Vb3Nc7P'}, now:, nonce:) signs an upload token like upload_tokens.sign at a fixed time (epoch milliseconds) and nonce, for tests that compare exact tokens.
Generate test inputs
CalmLens::TestInputs generates authenticated test inputs from your project's secret test input key. CalmLens recognises them only in projects with Test inputs turned on. generate_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_code(signal, test_input_key) returns a phrase to read aloud or show in a video. A scenario is a hash of instances (each with category, qualifiers and optional score and action), and optional regional_actions and unassessed_categories, with string or symbol keys. Pass a category, such as 'violence', instead of a scenario for one instance of it. PRESETS holds the portal's presets, frozen. An invalid key or scenario raises CalmLens::InvalidArgumentError with code sdk/invalid-argument.
require 'calmlens/testing'
test_input_key = ENV.fetch('CALMLENS_TEST_INPUT_KEY')
# Choose each instance's outcome: the strongest action wins
text = CalmLens::TestInputs.generate_text_code({instances: [
{category: 'harassment', qualifiers: %w[harassment-abuse harassment-documentary], action: 'limit'},
{category: 'harassment', qualifiers: %w[harassment-threat], action: 'limit'},
{category: 'harassment', qualifiers: %w[harassment-abuse], action: 'block'},
]}, test_input_key)
# Regional delivery outcomes without category findings
regional = CalmLens::TestInputs.generate_text_code(CalmLens::TestInputs::PRESETS[:regional_delivery], test_input_key)
# A test image to upload on its own: it survives JPEG, WebP and resizing
image = CalmLens::TestInputs.paint_image('violence', test_input_key)
File.binwrite('test-image.png', image.png)
# A phrase to read aloud or show in a video
phrase = CalmLens::TestInputs.generate_media_code('violence', test_input_key)
puts text, regional, phraseSet action on every instance to choose its outcome independently of the project policy, or on none to test the policy itself. paint_image(scenario, test_input_key) returns a CalmLens::TestInputs::Image: upload its binary png 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.