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: {retain_content: true})
mock.assets.retrieve(asset.id).classification.moderation.decision # => "allowed"
mock.assets.list(filter: 'classification.moderation.decision==allowed').count # => 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.

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_e5Gm2Rk8XqT3wLp9VbN4. 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']['decision'] = 'blocked'.

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 uploaded bytes (a multipart upload's parts joined in order), and text for a plain-text upload such as text.classify. Both are nil 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, or a decision built with CalmLens::MockDecision.of. A failed asset gets classification.failureReason processing-error. Without moderate:, queued uploads and retries 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, action, source and settings, 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).

pending_review(reason, uncertain_categories = []) leaves the decision waiting for human review, in classification.moderation.pendingReview: sampled, or uncertain with the categories that made it so. mock.decide clears it and assets.decide leaves it, as in CalmLens. Another reason, uncertain categories on a sampled review, an unknown category or a pending or failed decision 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 Hashes in the API's shape. The mock reports each result when the corresponding feature is enabled. OCR text appears in content.extractedText 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 Hashes 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.

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 raises CalmLens::NotFoundError (404 asset/not-found) for an unknown asset and sdk/invalid-argument for an asset that isn't processing:

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(upload.id).classification.moderation.decision # => "age-restricted"

What the mock simulates

  • Assets you upload can be retrieved, listed, searched, moved, updated and deleted, with null for fields that are not set, empty tags and metadata lists, and moderation fields that are null until a decision. A decided image reports ocr and person and face detection when its upload turned them on, and linkDetection unless it turned it off, each with only what the decision supplies (Moderation decisions): no text, codes, people or faces otherwise. Folders, multipart uploads (including content the client splits into parts, resumed with the same idempotency key) and lenses behave like the API's. assets.retrieve_by_external_id finds the asset with that external_id.
  • Idempotency keys: uploads and their parts, assets.decide, hash_lists.add_entry and assets.request_review honour request_options: {idempotency_key:} as CalmLens does: reusing a key returns the first response, with its status, and reusing it for a different request fails with 409 idempotency/key-reused. Other requests ignore it.
  • Content retention follows the API: new mock projects keep content by default. If retention is off, content is removed with removalReason retention once classification is completed. 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. A decided image's content.perceptualHash is the SHA-256 of its bytes, standing in for its image hash, with perceptualHashQuality 100, so hash_lists.add_entry(list_id, asset_id:) works. An image with exactly the bytes of a hash list entry's image matches it: classification.moderation.raw.hashMatches 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.
  • Folders and lenses: folder names are unique among siblings (case-sensitive) and listed by code point. ensure_lens changes a lens to the definition sent, and lenses.create refuses 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 (allow for personal information and profanity, block otherwise) and no rules, so policies.upgrade fails with 409 policy/preset-update-unavailable. Settings that leave out a category, or a category's action, allowances or restrictions, 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, requestId matching the x-request-id header, and a details object), so retrieving an asset that was never uploaded (mock.assets.retrieve('asset_e5Gm2Rk8XqT3wLp9VbN4')) raises CalmLens::NotFoundError with status 404.
  • 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 issue validation/too-small or validation/too-big, a sort with 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.decision==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=, raises CalmLens::BadRequestError with 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 score and matchedFields, rank by score and then newest first, and report semanticStatus disabled.
  • Waiting takes no real time: retries and decision checks don't sleep, and assets.wait_for_decision returns at once for a decided asset and raises sdk/timeout straight away for one whose moderation stays pending.
  • CDN access: like the CDN, every resource but display info of an asset whose content was removed returns 404 with 404 asset/not-found, as an unknown asset does. Content resources of blocked, purged and failed assets return 403 with 403 asset/not-available. Age-restricted assets requested without viewer_claims: {age_confirmed: 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. mock.fetch_cdn sends no key: without a grant, a private asset returns 404 with 404 asset/not-found whatever its state, including its placeholder and display info.
  • CDN responses carry the stored bytes with content-type, content-length, x-request-id, cache-tag, x-content-type-options and content-security-policy headers (and etag for images), 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). The placeholder resource is a classified image's ThumbHash as a 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. 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.
  • Served URLs: mock.serve_url(url, content:, type:) gives a URL content (a String of bytes or text) 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.
  • 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

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. mock.enqueue_event adds others. One 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. Every asset the mock returns has the event_sequence of its latest event, and mock.events.retrieve_asset(event) returns the stored asset:

cursor = mock.events.list.next_cursor
mock.enqueue_event(type: 'asset.allowed', asset_id: asset.id, actor: {type: 'user', id: nil})
mock.events.list(cursor: cursor).auto_paging_each.map(&: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). Every mock key has the ID CalmLens::MockServerClient::API_KEY_ID, so the events its requests record have that actor.id, and its assets.decide reviews that decided_by.id.

mock.assets.request_review queues a review with the reason reported and its note, sets the asset's classification.moderation.pendingReview and records asset.review-requested. While a review is waiting, it returns that review with last_response.status 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.

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 # => 200

mock.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. 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. times: fails that many requests instead of one, so a retry takes the same failure again until it is used up. mock.fail_requests takes the same arguments but times: and fails every matching request until mock.clear_failures, which also drops queued failures. 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. Failures queue in order, and each request takes the oldest one that matches it; once it is used up, 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/rate-limit-reached', retry_after: 30)
mock.assets.list # raises CalmLens::RateLimitError with status 429 and retry_after 30

mock.fail_requests('server/internal-error', operation: 'assets.retrieve')
mock.assets.retrieve(asset.id) # raises CalmLens::ServerError with status 500
mock.clear_failures

Retry backoff and deadline_ms run on the mock's clock, which only its waits move, so they take 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/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 (under Project settings → Processing → Test inputs in the portal). Every project recognises inputs signed with its own key. 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, phrase

Set 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.

Verify a blocked decision with the live API

Use a project API key with Upload assets permission. Set CALMLENS_API_KEY, CALMLENS_PROJECT_ID and the project's test input key as CALMLENS_TEST_INPUT_KEY on your server. Submit the generated code as the entire text. The response must have classification.test_input set to true before you count it as a test result.

require 'calmlens/testing'

client = CalmLens::ServerClient.new
begin
  text = CalmLens::TestInputs.generate_text_code(
    {instances: [{category: 'harassment', qualifiers: [], action: 'block'}]},
    ENV.fetch('CALMLENS_TEST_INPUT_KEY')
  )
  classification = client.text.classify(text: text).classification
  raise 'The API did not recognise the test input' unless classification.test_input
  raise 'Expected a blocked decision' unless classification.moderation.decision == 'blocked'
ensure
  client.close
end

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