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:

OptionEffect
ModerateDecides each asset the mock moderates (see Moderation decisions).
APIKeyUse 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.
CDNBaseURLThe base URL of CDN and signed asset URLs.
CreateID, NowDeterministic 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), and Text, the bytes as a string 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: TriggerUpload, TriggerRetry (after Assets.Retry), TriggerRerun (after Assets.Explain with Rerun) or TriggerComplete (see below).
  • Queued: true when CalmLens would queue the work rather than answer with the decision: queued uploads, retries, reruns and TriggerComplete.

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, requestId and details), for example 404 asset/not-found and 409 folder/not-empty (with hasAssets and hasChildren), and every response has an X-Request-Id. An unknown route returns 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 with validation/too-small or validation/too-big and the field in details.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 (including folderId==) and Sort. A Sort with an unknown or repeated field, or more fields than the list allows, fails with 400 validation/invalid-request and sort in details.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 MatchedFields lists 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 with Assets.Classify) unless UploadAssetPartOptions.Wait overrides it, check part numbers (answering an out-of-order part with details.expectedPartNumber), that multipart image uploads total at most 20 MiB, and TotalSizeInBytes. Content the client splits into parts is joined in order, and repeating a call with the same IdempotencyKey replays 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: EnsureLens returns an unchanged lens as it is and changes one whose definition differs. Lenses.List lists newest first, Lenses.Create refuses 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, allowances or restrictions, fail with 400 validation/invalid-request and the first missing field in details.path.
  • Folders have unique names among siblings (case matters), list by name in code-point order (or by createdAt with Sort) 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 (HashLists and HashListEntries). AddEntry answers 201 for a new entry and 200 with the existing entry for a hash already listed. With AssetID it takes the asset's content.perceptualHash and perceptualHashQuality, 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 RemovalReason retention unless the upload set KeepContentAfterProcessing, and a purged decision always removes it with RemovalReason policy. A classified image gets a ThumbHash for its placeholder, which goes with its content.
  • Retries and reruns: Assets.Retry needs failed processing and content that was not removed. It moves the asset back to processing, then asks Moderate again. Assets.Explain with Rerun 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 OutcomeFailed. A pending re-run waits for CompleteProcessing.
  • Processing events: every completed upload adds asset.uploaded, then asset.classified and the automated asset.<status> (whose actor is 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.WaitForDecision only advance the mock client's clock. WaitForDecision returns a completed or failed asset, and returns sdk/timeout straight away for one that stays queued or processing.
  • CDN access: blocked, purged and failed assets, and assets whose content was removed, return 403 with 403 asset/not-available. Age-restricted assets requested without ViewerClaims: &calmlens.ViewerClaims{AgeConfirmed: calmlens.Ptr(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.
  • CDN responses from CDN.Serve include the content type and length, 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), Cache-Tag, the CDN's protection headers and, for images, ETag and Expires. A classified image's placeholder is 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:

FieldEffect
Codecalmlenstest.FailureTransportError (sdk/transport-error), calmlenstest.FailureTimeout (sdk/timeout), or an API error code such as calmlens.CodeUploadLimitExceeded, answered with its HTTP status
ErrInstead of Code, a network error: sdk/transport-error wrapping it, or sdk/timeout for context.DeadlineExceeded
OperationLimits the failure to the next request of one client method, such as "assets.create" or "cdn.serve"
DetailsThe API error's details
RetryAfterA 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.

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