Go testing
Use the calmlenstest package to test your Go SDK integration offline.
Setup
package main
import (
"context"
"fmt"
"log"
"calmlens.com/go/calmlens"
"calmlens.com/go/calmlens/calmlenstest"
)
func main() {
mock, err := calmlenstest.NewServerClient(calmlenstest.Options{ProjectID: "proj_8fK2mQx7Lp4NvB3tRz9Y"})
if err != nil {
log.Fatal(err)
}
asset, err := mock.Assets.Classify(context.Background(), calmlens.SubmitAssetOptions{
Name: "text",
Content: &calmlens.Content{Type: "text/plain", PlainText: calmlens.Ptr("Hello")},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(asset.Classification.Moderation.Decision)
}The mock embeds the real client, so your code receives the same types and errors as in production. Pass mock.ServerClient wherever your code expects a *calmlens.ServerClient. It accepts the same ProjectID, BaseURL, Timeout, UploadTimeout, MaxRetries, MaxResponseBytes, PartSizeBytes, AppInfo, Logger and OnAttempt options as the real client, and never reads the CALMLENS_ environment variables.
Options
The mock doesn't classify content, fetch remote URLs (other than those you register with mock.ServeURL) or transform media, and its signed asset URLs work only with the mock: mock.FetchCDN(ctx, url) fetches one of its CDN URLs as a browser would, without the API key. It serves /info, names assets by ID or ext: external ID, and refuses an expired grant with 403 signed-url/expired and /original under a URL not signed for it with 403 signed-url/original-not-granted. calmlenstest.Options adds controls for moderation, keys, URLs, IDs and the clock:
| Option | Effect |
|---|---|
Moderate | Decides each asset the mock moderates (see Moderation decisions). |
APIKey | Use calmlenstest.CreateMockAPIKey(grants) for a key with specific grants, such as assets:download for private CDN reads. The default key has no grants, and mock.SetAPIKeyGrants(grants) replaces them. |
CDNBaseURL | The base URL of CDN and signed asset URLs. |
CreateID, Now | Deterministic IDs (for assets, folders, hash lists, entries, lenses, events and reviews) and clock. The default clock advances at least 1 ms per reading, so assets created in a row have increasing createdAt values; a Now you supply is used as is. |
CreateID receives the object's ID prefix (asset, fldr, hl, hle, lens, evt or rev); by default the mock mints IDs like the API's, such as asset_e5Gm2Rk8XqT3wLp9VbN4. Pass DatabaseStorage and ImageStorage to seed or inspect stored data between calls, and use mock.WithStorage(func(db, images) { ... }) to read or change it safely while other goroutines send requests.
Moderation decisions
Options.Moderate decides each asset the mock moderates. It receives a calmlenstest.ModerationInput:
Asset: the stored asset, still processing.Content:Bytes, the uploaded bytes (a multipart upload's parts joined in order), andText, the bytes as a string for a plain-text upload such asText.Classify. Both arenilwhen there is no content, such as for a website.Trigger: why the asset is moderated:TriggerUpload,TriggerRetry(afterAssets.Retry) orTriggerComplete(see below).Queued:truewhen CalmLens would queue the work rather than answer with the decision: queued uploads, retries andTriggerComplete.
It returns a decision built with calmlenstest.NewDecision(status), where the status is OutcomePending, OutcomeFailed, OutcomeAllowed, OutcomeLimited, OutcomeAgeRestricted, OutcomeBlocked or OutcomePurged (which also removes the content). A failed asset gets FailureReason processing-error. Return nil, or leave Moderate unset, for the default: queued uploads and retries stay pending and everything else is allowed. Finished processing removes content unless the upload sets RetainContent.
Flag(category, score, qualifiers) records a category's score from 0 to 1 and, optionally, its qualifiers' scores, NotEvaluated(category) marks a category as not assessed, and PendingReview(reason, uncertainCategories...) leaves the decision waiting for human review, as PendingReview on the moderation report shows: calmlenstest.PendingReviewSampled, or calmlenstest.PendingReviewUncertain with the categories that made it so. All 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). Invalid inputs (an unknown status, category or qualifier; a score outside 0 to 1; a category added twice; findings or a pending review on a pending or failed decision; or a pending review with an invalid reason or uncertain categories on a sampled review) set decision.Err() to sdk/invalid-argument, which the request returns.
Use WithOCR(text, textRegions...) and WithLinkDetection(qrCodes, links) on a mock decision to supply findings for an image, as calmlens.TextRegion, calmlens.DetectedQRCode and calmlens.DetectedLink values. The mock reports each result when the corresponding feature is enabled. OCR text appears in Content.ExtractedText when the upload keeps its content.
Use WithPersonDetection(people...) and WithFaceDetection(faces...) to supply the people and faces an image holds, as calmlens.DetectedPerson and calmlens.DetectedFace values. The mock reports them when the upload turns person or face detection on, with a face's AgeRange only when it also turns on AgeEstimation. Without them, the mock reports no people or faces.
mock, err := calmlenstest.NewServerClient(calmlenstest.Options{
Moderate: func(input calmlenstest.ModerationInput) *calmlenstest.Decision {
if input.Content.Text != nil && strings.Contains(*input.Content.Text, "kill") {
return calmlenstest.NewDecision(calmlenstest.OutcomeBlocked).
Flag("violence", 0.92, map[string]float64{"violence-threat": 0.9})
}
return nil
},
})
if err != nil {
t.Fatal(err)
}
comment, err := mock.Text.Classify(ctx, calmlens.ClassifyTextOptions{Text: "I will kill you"})
// comment.Classification.Moderation.Decision is "blocked", and its policy's
// flagged categories are ["violence"].Moderate runs while the mock answers a request, so it must not call the mock. It decides queued uploads straight away too: return NewDecision(calmlenstest.OutcomePending) for them (input.Queued && input.Trigger == calmlenstest.TriggerUpload) to finish them later.
Finish processing
mock.CompleteProcessing(assetID, decision) finishes processing a pending asset as CalmLens would, with the decision you pass, or with the one Moderate returns for TriggerComplete when it is nil (allowed by default). It returns 404 asset/not-found for an unknown asset and sdk/invalid-argument for an asset that isn't processing:
upload, err := mock.Assets.Create(ctx, calmlens.SubmitAssetOptions{
Name: "photo.png",
Content: &calmlens.Content{Type: "image/png", Base64: calmlens.Ptr(pngBase64)},
}) // pending
if err != nil {
t.Fatal(err)
}
_, err = mock.CompleteProcessing(upload.ID, calmlenstest.NewDecision(calmlenstest.OutcomeAgeRestricted).Flag("sexual", 0.8, nil))What the mock simulates
- Errors use the API's codes, HTTP statuses, details and error body (
code,message,requestIdanddetails), for example 404 asset/not-found and 409 folder/not-empty (withhasAssetsandhasChildren), and every response has anX-Request-Id. An unknown route returns 404 request/route-not-found. Out-of-range page sizes (1 to 100), event limits (1 to 100), search page sizes (1 to 20) and search queries (1 to 200 characters) fail withvalidation/too-smallorvalidation/too-bigand the field indetails.path. Requests the client refuses before sending, such as multipart parts under 5 MiB, carry the status the API would answer with. - Lists apply
Filter(includingfolderId==) andSort. ASortwith an unknown or repeated field, or more fields than the list allows, fails with 400 validation/invalid-request andsortindetails.path. Filters accept the API's filter fields and operators, with;binding tighter than,and parentheses grouping, and*in an==or!=value matching any run of characters regardless of case. Any other field or operator, such as=like=, fails with 400 filter/invalid. Pages hold 50 assets by default and up to 100. Cursors resume after the last returned asset, so assets created or deleted between pages don't shift later pages, and a cursor only continues the query it came from. - Search works like keyword search in the API: every word of the query (case-insensitive, up to 8) must appear in the name, ID, external ID, description, tags, type, content format or extension, or moderation status. Results are ranked by the API's score, exact ID, external ID or name matches first, then newest first, and
MatchedFieldslists the fields that contain a query word. - Multipart uploads keep whether to wait for the decision, chosen at the start (not with
Assets.Create, waiting withAssets.Classify) unlessUploadAssetPartOptions.Waitoverrides it, check part numbers (answering an out-of-order part withdetails.expectedPartNumber), that multipart image uploads total at most 20 MiB, andTotalSizeInBytes. Content the client splits into parts is joined in order, and repeating a call with the sameIdempotencyKeyreplays the parts already stored and resumes the upload. - Idempotency keys are honoured by uploads,
Assets.Decide,HashLists.AddEntryandAssets.RequestReview, as CalmLens does: a repeated key replays the first response, with its status, and a key reused for a different request returns 409 idempotency/key-reused. A failed request frees its key, and keys must be 1 to 255 printable ASCII characters without a space at either end. Other requests ignore the key. - API key: every mock API key has the ID
calmlenstest.MockAPIKeyID, so the events its requests record have thatActor.ID, and itsAssets.Decidereviews thatDecidedBy.ID. - Review requests:
Assets.RetrieveByExternalIDfinds the asset with thatExternalID.Assets.RequestReviewqueues a review with the reasonreportedand its note, sets the asset'sClassification.Moderation.PendingReviewand 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 itsdetails.reason, as CalmLens does.mock.Decidesettles the review, so the asset can be reported again. - Upload presets: an upload naming
UploadPresetIDtakes the folder, visibility and, unless it sets its own, processing options of the preset fromUploadPresets.Ensure, and is refused as in the API: an unknown preset with 404 upload-preset/not-found, a disabled one with 403 upload-preset/disabled, another visibility or folder 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. - Lenses:
EnsureLensreturns an unchanged lens as it is and changes one whose definition differs, and a lens withoutActiveis served.Lenses.Listlists newest first,Lenses.Createrefuses an identifier already in use with 409 lens/identifier-taken, and an unknown lens ID fails with 404 lens/not-found. - Policies: the project starts on the organisation's own General policy, following automatic updates. The mock's presets have one release, with every category at its default action and no rules, and uploads are never decided by a policy. Settings missing a category, or a category's
action,allowancesorrestrictions, fail with 400 validation/invalid-request and the first missing field indetails.path. - Folders have unique names among siblings (case matters), list by name in code-point order (or by
createdAtwithSort) with their ancestors, page with cursors like the API, and refuse moves that would create a cycle. - Hash lists list newest first, 50 per page by default, with cursors, and live in
DatabaseStorage(HashListsandHashListEntries).AddEntryanswers201for a new entry and200with the existing entry for a hash already listed. WithAssetIDit takes the asset'scontent.perceptualHashandperceptualHashQuality, or fails with 409 hash-list/asset-not-hashed. Deleting a list deletes its entries. A decided image'scontent.perceptualHashis the SHA-256 of its bytes, standing in for its image hash, soAddEntrywithAssetIDworks. An image with exactly the bytes of an entry's image matches it:Classification.Moderation.Raw.HashMatcheslists the match with its list's action, and a block list blocks the image withSourcehash-listand records asset.hash-matched. Similar but different images never match in the mock. - Content removal: once processing finishes, content is removed with
RemovalReasonretention when retention is off, and a purged decision always removes it withRemovalReasonpolicy. A classified image gets a ThumbHash for itsplaceholder, which goes with its content. - Retries:
Assets.Retryneeds failed processing and content that was not removed. It moves the asset back to processing, then asksModerateagain. - Processing events: every completed upload adds asset.uploaded, then asset.classified and the automated
asset.<status>(whoseactoris automated) once it is decided, or asset.failed. - Lifecycle events: retrying an asset adds asset.retried, removing its content asset.content-removed and deleting it asset.deleted. Fields that are not set are
null. - Waiting takes no real time: retry backoff and
Assets.WaitForDecisiononly advance the mock client's clock.WaitForDecisionreturns a completed or failed asset, and returnssdk/timeoutstraight away for one that stays queued or processing. - CDN access: every resource but display info of an asset whose content was removed returns
404with 404 asset/not-found, as an unknown asset does. Content resources of blocked, purged and failed assets return403with 403 asset/not-available. Age-restricted assets requested withoutViewerClaims: &calmlens.ViewerClaims{AgeConfirmed: calmlens.Ptr(true)}return403with 403 viewer/age-confirmation-required, whatever the key. Private assets return403with 403 auth/permission-denied unless the key has assets:download.mock.FetchCDNsends no API key, so without a signed URL a private asset returns404with 404 asset/not-found whatever its state, including its placeholder and display info. - CDN responses from
CDN.Serveinclude the content type and length,Cache-Controlas the CDN sets it (public files usepublic, max-age=86400, must-revalidate, unsigned private files useprivate, no-cache, signed files expire with the grant or after one day, and embed pages and requests with viewer claims useprivate, no-store),Cache-Tag, the CDN's protection headers and, for images,ETag. A classified image'splaceholderis served 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. - Served URLs:
mock.ServeURL(url, content, contentType)gives an absolute URL content and a content type. A URL upload of it stores the content, passes it toModerateand takes itsTypefrom the content type, as an upload of those bytes would;text/htmlis a website. - Other URL uploads take their
typefrom the file extension of the URL's path, ignoring case, the query and the fragment, since the mock fetches nothing: image forjpg,jpeg,png,gif,webp,avif,heic,heif,bmp,tif,tiffandsvg; video formp4,m4v,mov,webm,mkvandavi; audio formp3,m4a,aac,wav,ogg,oga,opusandflac; multimedia-document forpdf,doc,docx,odt,ppt,pptx,odpandrtf; and plaintext-document fortxtandmd. Any other extension, such ashtml, or none gives a website.
Events and reviewer decisions
Events you add with mock.EnqueueEvent(...) are returned by Events.List and Events.ListAll after cursors taken earlier, 50 per page by default. An event with an AssetID takes that asset's next AssetSequence. Like CalmLens's events, it carries no copy of the asset, so Events.RetrieveAsset returns the stored asset as it is now. Every asset the mock returns, from its methods and from Decide, CompleteProcessing and Moderate, has the EventSequence its events have reached at that moment, as CalmLens's assets do. An unreadable cursor fails with 400 cursor/invalid.
Assets.Decide 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). The decision and note join Classification.Moderation.ManualReviews, and the matching event is added.
To simulate a reviewer's decision without those checks, mock.Decide(assetID, calmlenstest.OutcomeBlocked), with any decided outcome, applies a reviewer's decision: it changes the asset's moderation status, removes the content when purged (recording asset.content-removed first), and adds an asset.<decision> event whose actor is a user. The moderation report stays as it was, except that a pending review is settled, which Assets.Decide leaves waiting. OutcomePending and OutcomeFailed are not decisions and return sdk/invalid-argument. To finish processing as CalmLens's moderation would, use CompleteProcessing.
Recorded requests and failures
mock.Requests() returns every captured request, oldest first, with its method, path, parsed query, headers, decoded JSON body and Status, a pointer to the HTTP status the mock answered with (nil for a request that failed without a response); RawBody holds the exact bytes sent, including upload content. Path is relative to the API base URL, or to the CDN base URL when CDN is true, so it leaves out /v1, with each segment decoded, such as /projects/project-1/assets (project-1, calmlenstest.DefaultProjectID, is the default ProjectID). Requests that a queued failure fails are captured too. mock.ClearRequests() forgets the requests captured so far.
mock.FailNextRequest(failures...) queues failures. Each calmlenstest.RequestFailure fails one request, or Times requests, without changing anything else:
| Field | Effect |
|---|---|
Code | calmlenstest.FailureTransportError (sdk/transport-error), calmlenstest.FailureTimeout (sdk/timeout), or an API error code such as calmlens.CodeUploadLimitExceeded, answered with its HTTP status |
Err | Instead of Code, a network error: sdk/transport-error wrapping it, or sdk/timeout for context.DeadlineExceeded |
Operation | Limits the failure to the next request of one client method, such as "assets.create" or "cdn.serve" |
Details | The API error's details |
RetryAfter | A whole number of seconds, answered as the API error's Retry-After, so err.RetryAfter is set |
Times | How many requests it fails; zero fails one |
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. FailNextRequest returns sdk/invalid-argument and queues nothing for an unknown code or an operation that isn't a client method that sends requests, for example a misspelt one, and for Details or RetryAfter with a transport error or timeout, which they don't apply to, and for a negative Times. mock.FailRequests(failures...) fails every matching request until mock.ClearFailures(), which also drops queued failures.
err := mock.FailNextRequest(calmlenstest.RequestFailure{
Code: "upload/rate-limit-reached",
RetryAfter: calmlens.Ptr(30 * time.Second),
})
if err != nil {
t.Fatal(err)
}
_, err = mock.Assets.List(ctx, calmlens.ListAssetsOptions{})
// err is a *calmlens.Error with Status 429 and RetryAfter 30s.if err := mock.FailRequests(calmlenstest.RequestFailure{Code: "server/internal-error", Operation: "assets.retrieve"}); err != nil {
t.Fatal(err)
}
_, err = mock.Assets.Retrieve(ctx, calmlens.AssetIDOptions{AssetID: assetID})
// err is a *calmlens.Error with Status 500.
mock.ClearFailures()The mock's MaxRetries defaults to 0, unlike the real client, so a queued failure fails exactly one call; set MaxRetries to test retry handling. 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 reaches the mock. Retry backoff and Params.Deadline run on the mock's clock, which only its waits move, so they take no real time.
Webhook handlers
calmlens.ToWebhookEventPayload(event) returns the body a webhook delivers for an event from Events.List or mock.EnqueueEvent: the same event fields, with no envelope. Its RawJSON() is the exact JSON. calmlens.CreateWebhookHeaders(body, deliveryID, timestamp, secret) returns the headers of a signed delivery, as CalmLens sends them. Pass time.Now().Unix() as the timestamp, since handlers reject deliveries timestamped more than 5 minutes from the current time.
events := mock.EnqueueEvent(calmlens.Event{Type: calmlens.EventAssetAllowed, AssetID: calmlens.Ptr(asset.ID)})
body := calmlens.ToWebhookEventPayload(events[0]).RawJSON()
request := httptest.NewRequest(http.MethodPost, "/webhooks", bytes.NewReader(body))
request.Header = calmlens.CreateWebhookHeaders(body, "delivery-1", time.Now().Unix(), secret)
handleWebhook(httptest.NewRecorder(), request)calmlens.SignWebhookPayload(body, timestamp, secret) returns only the x-calmlens-signature value: v1= followed by the hex HMAC-SHA256 of <timestamp>.<body>, with the timestamp in Unix seconds.
Upload tokens
calmlenstest.SignUploadToken(apiKey, options, now, nonce) signs an upload token at a fixed time and nonce, so tests can compare exact tokens.
Generate test inputs
calmlenstest 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. GenerateTestTextCode(input, testInputKey) returns a text code to submit as the whole text: text with anything else around the code is moderated as ordinary content. GenerateMediaTestCode(signal, testInputKey) returns a phrase to read aloud or show in a video. A TestInput lists Instances (each with Category, Qualifiers and optional Score and Action), and optional RegionalActions and UnassessedCategories. TestInputPresets() returns fresh copies of the portal's presets, and TestInputForSignal(signal, calmlenstest.TestInputText) the scenario for one category. An invalid key or scenario returns a *calmlens.Error with code sdk/invalid-argument.
package main
import (
"fmt"
"log"
"os"
"calmlens.com/go/calmlens/calmlenstest"
)
func main() {
testInputKey := os.Getenv("CALMLENS_TEST_INPUT_KEY")
// Choose each instance's outcome: the strongest action wins
text, err := calmlenstest.GenerateTestTextCode(calmlenstest.TestInput{Instances: []calmlenstest.TestInstance{
{Category: "harassment", Qualifiers: []string{"harassment-abuse", "harassment-documentary"}, Action: "limit"},
{Category: "harassment", Qualifiers: []string{"harassment-threat"}, Action: "limit"},
{Category: "harassment", Qualifiers: []string{"harassment-abuse"}, Action: "block"},
}}, testInputKey)
if err != nil {
log.Fatal(err)
}
// Regional delivery outcomes without category findings
regional, err := calmlenstest.GenerateTestTextCode(calmlenstest.TestInputPresets().RegionalDelivery, testInputKey)
if err != nil {
log.Fatal(err)
}
// A test image to upload on its own: it survives JPEG, WebP and resizing
input, err := calmlenstest.TestInputForSignal("violence", calmlenstest.TestInputImage)
if err != nil {
log.Fatal(err)
}
image, err := calmlenstest.PaintTestImage(input, testInputKey)
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile("test-image.png", image.PNG, 0o644); err != nil {
log.Fatal(err)
}
// A phrase to read aloud or show in a video
phrase, err := calmlenstest.GenerateMediaTestCode("violence", testInputKey)
if err != nil {
log.Fatal(err)
}
fmt.Println(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. PaintTestImage(input, testInputKey) 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. Use TestInputForSignal(signal, calmlenstest.TestInputImage) for a signal's image scenario, which differs from the text one for sexual.adult. A scenario too large for a test image returns sdk/invalid-argument; split it or use a text code.