Go testing
Use the calmlenstest package to test your Go SDK integration offline.
Setup
package main
import (
"context"
"fmt"
"log"
calmlens "github.com/CalmLens/sdks/go"
"github.com/CalmLens/sdks/go/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.Status)
}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 and PartSizeBytes options as the real client.
Outcomes and options
The mock doesn't classify content, fetch remote URLs 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 without original access 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_5Gm2Rk8XqT3wLp9VbN4c. 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),TriggerRerun(afterAssets.ExplainwithRerun) orTriggerComplete(see below).Queued:truewhen CalmLens would queue the work rather than answer with the decision: queued uploads, retries, reruns 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, retries and reruns stay pending and everything else is allowed. Finished processing removes content unless the upload sets KeepContentAfterProcessing.
Flag(category, score, qualifiers) records a category's score from 0 to 1 and, optionally, its qualifiers' scores, and NotEvaluated(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 added twice, or findings on a pending or failed decision make decision.Err() an sdk/invalid-argument error, which the request using the decision returns.
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.Status 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 records no review, so the asset can still be moderated again with Assets.Explain. It returns 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:
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 returnsrequest/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 replay the first response, 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.
- Lenses:
EnsureLensreturns an unchanged lens as it is and changes one whose definition differs.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. Uploads are not matched against the lists. - Content removal: once processing finishes, content is removed with
RemovalReasonretention unless the upload setKeepContentAfterProcessing, and a purged decision always removes it withRemovalReasonpolicy. A classified image gets a ThumbHash for itsplaceholder, which goes with its content. - Retries and reruns:
Assets.Retryneeds failed processing and content that was not removed. It moves the asset back to processing, then asksModerateagain.Assets.ExplainwithRerunadds asset.rerun-requested and returns the asset unchanged: it keeps its decision until the oneModeratereturns replaces it, and keeps it when that isOutcomeFailed. A pending re-run waits forCompleteProcessing. - Processing events: every completed upload adds asset.uploaded, then asset.classified and the automated
asset.<status>(whoseactorisautomated) 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: blocked, purged and failed assets, and assets whose content was removed, return
403with 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. - CDN responses from
CDN.Serveinclude the content type and length,Cache-Controlas the CDN sets it (publiconly when anyone may see the asset, otherwiseprivate;max-age=31536000, immutablefor images andmax-age=3600for other content),Cache-Tag, the CDN's protection headers and, for images,ETagandExpires. A classified image'splaceholderis served as a PNG for every image whatever its visibility or moderation status, and refused once the image is purged or its content removed.
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 the AssetID of a stored asset carries that asset, as CalmLens's events do. An asset.<status> event carries the moderation status it announces, as CalmLens sends it once the asset has that status. 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. 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 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 |
It 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.
err := mock.FailNextRequest(calmlenstest.RequestFailure{
Code: "upload/website-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.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. Each queued failure fails one request, so a retry takes the next queued failure or reaches the mock.
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. Marshal its Raw field to get 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, err := json.Marshal(calmlens.ToWebhookEventPayload(events[0]).Raw)
if err != nil {
t.Fatal(err)
}
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. CalmLens recognises them only in projects with Test inputs turned on. 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"
"github.com/CalmLens/sdks/go/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.