Conformance blocks
Prove a custom executor, cache adapter, sink, auth resolver, framework adapter, generator or plugin meets its contract.
better-supabase/testing has a block per extension interface. A block runs every
check and resolves with a report, or throws a ConformanceError that lists
all failed checks. Blocks don't depend on a test runner, so they work in vitest,
node:test and bun.
import { testExecutor } from "better-supabase/testing";
import { it } from "vitest";
it("conforms", () =>
testExecutor(kyselyExecutor(db), {
betterSupabase: createSupabase(schema),
table: "tags",
create: { organizationId: ORG, name: "conformance" },
}));| Block | Checks |
|---|---|
testExecutor(executor, { betterSupabase, table?, create? }) | rows keyed by selection aliases, limits, counts, aborted errors, failures returned instead of thrown, rpc failures, and with create a create, read and delete round trip plus a delete({ where }) past maxAffected that fails with max_affected and deletes nothing |
testCacheAdapter(adapter, { table? }) | table and row targets, tenants, repeated and concurrent calls, unknown tables, no mutation of the target |
testEventSink(sink, { received? }) | empty and full batches, no mutation of events, and with received delivery of every event |
testQueueProvider(backend, { queue, dedupe? }) | API v1, payload round trip, claimed messages hidden for their lease, attempt counts, retry then dead letter at max_attempts, and with leases stale attempts rejected and lease extension; dedupe keys return the first id; with stats and listDead, the dead letter is counted and listed, and with retryDead it is claimable again |
testScheduleProvider(scheduler, { prefix, queue, tenant?, probe?, rejectsProbes? }) | API v1, a name, a schedule written once per name, rewritten and removed, false for a missing name, a tenant's schedules kept apart and removed with unscheduleTenant, a probe kept (or refused with rejectsProbes), and with dueSchedules and advanceSchedule a due schedule leased once and advanced only from the run it claimed |
testSupportSessionStore(store, { admin, targets }) | API v1, a started session has a UUID id, matches its input and only its admin sees it, a second start ends the first, ending works once and the ended session is listed, and expire (when present) leaves a running session alone |
testIncomingDestination(destination, { tenant, source? }) | API v1, a name, a repeated endpoint and message id reported as a duplicate with the first id, and another message id or endpoint accepted as new |
testNotificationChannel(channel, { email?, received? }) | API v1, a name, a frozen message sent without mutating it, a valid result, and with received delivery of the message |
testPaymentProvider(provider, { amount?, authorize?, webhook? }) | API v1, a name, a zero amount and a plain number refused, a created payment with its amount, reference and nothing captured or refunded, the same payment for a repeated idempotency key, not_found for an unknown id, get and cancel when present, and with authorize a full capture, a partial refund and an over-refund refused; with webhook a valid delivery parsed and a tampered one refused |
testFieldPack(pack, { subjects? }) | API v1, a lower case key and a whole version, at least one field, valid and unique field keys with known types, defineFieldPack, a JSON round trip, and (with subjects) registered subject types |
testTaxProvider(provider, { address, currency?, taxCategory?, expectTax? }) | API v1, a name, a mixed-currency cart and an address without a country refused, quote lines in cart order with shipping last and a total that adds up, an inclusive line, zero tax for an exempt customer, a commit under its reference, and a full and partial reversal with negative amounts, refusing more than the sale and an unknown line |
testShippingProvider(carrier, { from, to, service, currency?, webhook? }) | API v1, a name, a request without packages or with a bad country refused, a rate for the service in the asked currency, an unknown service refused, a label with a tracking number, a cost and a known format, the same label for a repeated idempotency key, tracking events oldest first, not_found for an unknown tracking number, a voided label, and with webhook a signed delivery read into updates with tracking numbers and a forged one refused |
testDomainProvider(provider, { hostname }) | API v1, a name, the hostname added and added again with the same result, its status, verify answering verified or verified: false without an error, records with a type, name and value and none once verified, a remove that returns true then false, and no status after removal |
testEInvoiceChannel(channel, { organizationId, document, invoice, recipient, unknownRecipient? }) | API v1, a key, a sent document returning a message id, and for each optional method the channel has: a participant found and an unknown one not, a state for a sent message with a reason when rejected, and received documents with a message id and XML |
testBlockList({ name, target, rows, sorts?, facets?, arrayFilter?, search? }) | a keyset page with hasMore and nextCursor that agree, the limit, a cursor walk that reads every row once in the order of one big page, each sort reversing with its direction, a list of sorts reported in sorted, an array filter equal to the union of its values, q, count against the page, seeded facet counts, and get for a known and an unknown id (the list contract) |
testStreamStore(store, { id?, timeoutMs? }) | API v1, a name, one open per stream, idempotent appends that refuse a gap, reads from any index that end once the stream closes, a live read that sees later appends, a cancel the writer sees, appends refused after close, a missing stream read as empty, and purge with a count |
testChatState(state, { message, id?, ttlMs? }) | subscriptions, one lock holder at a time with token-checked release and extension, lock and cache TTLs, setIfNotExists, list trimming, and a per-thread queue that keeps the newest entries, reports its depth and drops expired ones |
testChatAdapter(adapter, { threadId, dmUserId? }) | thread ids that round-trip, a posted message read back, parsed, edited and deleted, formatted text rendered, and for each optional method it has: a DM it opens, its channel info, a page of threads, and a scheduled message it cancels |
testCredentialProvider(provider, { ref, seed, userRef?, inbound? }) | API v1, invalid_input for a ref of another provider, a stored token with headers, a new value seen after storing it, separate credentials per user, revoke then not_found, and with inbound a signed request accepted and a tampered one refused |
testWebhookSigner(signer, { verify? }) | API v1, a name, string headers that are stable for the same input and change with the body, and with verify a signature the receiver accepts |
testWebhookTransport(transport, { url, received? }) | API v1, a name, an HTTP status and string body for a POST to url, and with received delivery of the body |
testWebhookSecretStore(store, { endpointId }) | API v1, secrets as strings, and with rotate a new secret listed first while the previous one keeps signing |
testAuthResolver(resolver, { invalid, valid?, unrelated? }) | undefined for requests without its credentials, invalid (never anon) for bad ones, the expected user for good ones, never throws |
testAdapter(name, { betterSupabase, serve, errorsInBody?, cookies? }) | a 401 without running the handler for a refused caller, data for an allowed one, a DbError answered with its status, no leaked message for other errors, bsb-primary-until after a write, pending event sends handed to waitUntil |
testGeneratorPlugin(generator, { meta, config?, model?, runtime? }) | apiVersion 2 with a version, relative unique paths inside the project, deterministic output, no mutation of the input, the same files from a structuredClone of the input (worker safe) and from the JSON round trip the cache makes |
testBlockTransportMiddleware(middleware) | API v1, a name, next called at most once, an unchanged request, and a rejection that keeps the database error's code and hint |
testAuthorizationProvider(provider, { postgres? }) | API v1, plain JSON, valid and unique scopes with a known tenantScope, templates that use only their placeholders, requires lists every function the templates call, permissions listed once at known scopes, and with versions the function, its grants and the authz: receive policy |
testAuthorizer(authorizer, { permissions, granted?, unknown? }) | API v1, a name, stable non-empty key() strings, a known outcome for every request without mutating it, evaluations that agree with evaluate and keep the order, decisions from the subject and never from a forged input, claims or memberships, a runtime.seed for another user or a version that is not live ignored, an unknown permission never granted, and with granted a grant through the same check the server runs |
testPlugin(plugin, { betterSupabase, table?, context?, create? }) | API v1, installs alone and next to the first-party plugins in either order, a known enforce, repository methods that never replace base ones, pure and deterministic context, transformQuery and beforeMutation, wrapExecutor keeps results intact, mapError returns a DbError or undefined |
testControllerBinding(name, { mount, settle?, disposes? }) | a framework binding over a block controller renders the initial snapshot and starts the work once, renders each change, passes the controller's actions through, and stops the work (and disposes the controller unless disposes: false) on unmount |
testRecordBinding(name, binding, { client, subject, subjects? }) | API v1, a non-empty read permission, non-empty event patterns, a load that settles for subject, and a count keyed by subjectKey with a whole number per record |
testRouteOptimizer(optimizer, { request? }) | API v1, a name, every requested stop answered once and no other id, finite non-negative totals, one stop answered as itself, and no stops answered with an empty order |
testPrescriptionGateway(gateway, { prescription }) | API v1, a key of 1 to 100 characters, a delivery answered with a reference of at most 200 characters, the same prescription delivered twice, and with cancel a prescription withdrawn |
testClinicalDecisionSupport(engine, { context }) | API v1, a key that is not built-in, well-formed alerts, the same fingerprints for the same context, and a context without medications answered |
testVulnerabilityFeed(feed, { cveId, unknownId? }) | API v1, a name, OSV records with the stored fields and nothing for an unknown id, EPSS scores between 0 and 1, and KEV entries keyed by CVE id with a date |
Inputs that should stay untouched are deep-frozen, so an implementation that mutates them fails with the check that caught it.
The first-party executors, adapters, generators and plugins run these blocks in the package's own test suite.
Controller bindings
testControllerBinding mounts the binding over a probe controller, the way
a component would. mount returns what the component renders (read), the
actions it got and an unmount; settle lets the framework apply pending
updates. The React, Vue, Svelte and Solid bindings of the blocks run it; a
binding for another framework runs it the same way.
import { testControllerBinding } from "better-supabase/testing";
import { it } from "vitest";
it("conforms", () =>
testControllerBinding("preact", {
mount: (create) => {
const view = renderHook(() => useController(create));
return {
read: () => view.result.current.state,
actions: view.result.current.actions,
unmount: view.unmount,
};
},
}));Last updated on