storetest

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package storetest builds store state for tests through the production write path: CreateJobSubmission for rows, LeaseTask and StartTaskAttempt for work in flight, CompleteTaskAttempt and RecordTaskFailure for work that ended. It is written only against store.Store, so the same helpers run on every backend.

States production cannot reach — an open attempt on a terminal task, a claim on a closed attempt — come from the backend's injectors, reached through InjectAttempt, InjectClaim and InjectorFor. Never use an injector for a state a production write can produce: a fixture that bypasses the real path drifts from it unnoticed.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ActiveWorkerCredential

func ActiveWorkerCredential(ctx context.Context, st store.WorkerCredentialStore, workerID string) (store.WorkerCredential, error)

ActiveWorkerCredential returns workerID's active credential — the one with a nil RevokedAt — or store.ErrNotFound if it has none. After a key rotation a worker has a revoked row and an active one; only the active one is returned.

It reads through ListActiveWorkerCredentials, the set `sqi-server worker list` shows. More than one active credential for a worker is an error: the schema's partial unique index forbids it.

func ClaimViolations

func ClaimViolations(t testing.TB, st store.Store) []string

ClaimViolations returns st's I3 violations, failing the test on error or when st has no checker. A wrapper that embeds store.Store has none: pass the store it wraps.

func Complete

func Complete(t testing.TB, st store.Store, attempt store.TaskAttempt, status store.TaskStatus)

Complete ends attempt the way a worker's report does, through store.TaskStore.CompleteTaskAttempt: its task reaches status (succeeded, failed or canceled) and the attempt the matching status, now. It fails the test unless the completion applied.

func FailAndRequeue

func FailAndRequeue(t testing.TB, st store.Store, req store.LeaseRequest, retryAfter time.Time) store.TaskAttempt

FailAndRequeue leases req.TaskID, which must be ready, records the attempt as failed and requeues the task to run again at retryAfter: one failed attempt behind a ready task, the way a worker-reported failure leaves it. It returns the failed attempt.

func InjectAttempt

func InjectAttempt(t testing.TB, st store.Store, attempt store.TaskAttempt) store.TaskAttempt

InjectAttempt injects attempt through st's injector, failing the test on error. A zero ID is filled with a fresh UUID and a zero StartedAt with now.

func InjectClaim

func InjectClaim(t testing.TB, st store.Store, claim store.UsageClaim) store.UsageClaim

InjectClaim injects an active claim through st's injector, failing the test on error. A zero ID is filled with a fresh UUID.

func InjectWorkerPower

func InjectWorkerPower(t testing.TB, st store.Store, id string, state store.PowerState, reason string)

InjectWorkerPower sets worker id's power state through st's injector, stamped now, failing the test on error.

func Lease

Lease leases req.TaskID through store.TaskStore.LeaseTask and returns the attempt it created, failing the test unless the lease landed. A zero AttemptID is filled with a fresh UUID and a zero Now with the current time.

func LeaseTo

func LeaseTo(workerID string) func(store.Task) store.LeaseRequest

LeaseTo is a SubmitLeasing lease function that leases every task to workerID.

func Postgres

func Postgres(t testing.TB) *postgres.Store

Postgres opens a store on a fresh database (see PostgresDSN), closed when the test ends. SQI_TEST_PG_FORCE_TX_RETRY=1 opens it with every transaction rehearsed once (postgres.Options.ForceTxRetry).

func PostgresAndDSN

func PostgresAndDSN(t testing.TB) (st *postgres.Store, dsn string)

PostgresAndDSN is Postgres, also returning the database's DSN, for a test that reaches the database without the store as well (a backup).

func PostgresDSN

func PostgresDSN(t testing.TB) string

PostgresDSN returns the DSN of a fresh, migrated database, dropped when the test ends. SQI_TEST_POSTGRES_DSN names an administrative connection to a server the tests may create databases on (make test-postgres provides one). Without it the test is skipped, unless SQI_TEST_REQUIRE_POSTGRES=1, when it fails: a skip verifies nothing, and CI must not pass on one.

Each database is cloned from a template migrated once per schema; the template's name carries a hash of the migration files, so a changed schema gets a new template. Building the template is serialized across test processes with an advisory lock, because go test runs packages in parallel processes; cloning it is not.

func PostgresEmptyDSN

func PostgresEmptyDSN(t testing.TB) string

PostgresEmptyDSN is PostgresDSN for an empty database: created with a plain CREATE DATABASE, no sqi template and no migrations, for a test that fills it some other way (a pg_restore, say). It is dropped when the test ends, and skips or fails without SQI_TEST_POSTGRES_DSN as PostgresDSN does.

func PostgresEnabled

func PostgresEnabled() bool

PostgresEnabled reports whether a store matrix should include PostgreSQL: when SQI_TEST_POSTGRES_DSN is set, or when SQI_TEST_REQUIRE_POSTGRES=1 makes its absence a failure (which PostgresDSN then reports).

func PostgresWith

func PostgresWith(t testing.TB, opts postgres.Options) *postgres.Store

PostgresWith is Postgres with explicit options.

func RecordNewerSchema

func RecordNewerSchema(t testing.TB, db *sql.DB, driver string) int64

RecordNewerSchema records, in db's goose table, one more applied schema version than this binary knows, as a newer sqi-server's migration would have left it, and returns that version. driver is "sqlite" or "postgres".

func RequirePostgresTool

func RequirePostgresTool(t testing.TB, name string)

RequirePostgresTool skips the test when the PostgreSQL client tool name (pg_dump, pg_restore) is not on PATH, or fails it when SQI_TEST_REQUIRE_POSTGRES=1: a skip verifies nothing.

func Running

Running leases req.TaskID and starts the attempt, leaving the task running.

func SeedRunTimes

func SeedRunTimes(t testing.TB, st store.Store) map[string]*int64

SeedRunTimes seeds one job whose tasks cover every case of a task's stored run time (tasks.run_ms): measured, unmeasurable for each reason, and not succeeded at all. It returns each task's ID with the run_ms it must hold: the duration of its latest attempt (highest attempt_number, then greatest ID) in milliseconds, when the task succeeded and that attempt succeeded with an ended_at no earlier than its started_at; nil otherwise. A migration test seeds this, rewinds past the column, migrates up and compares.

func Start

func Start(t testing.TB, st store.Store, attempt store.TaskAttempt)

Start moves attempt's task to running through store.TaskStore.StartTaskAttempt at the attempt's start time, failing the test unless it started.

func Submit

Submit creates sub through store.JobStore.CreateJobSubmission, failing the test on error. Every status and field the submission carries is written as given; only created_at and updated_at are stamped by the store.

func SubmitLeasing

func SubmitLeasing(
	t testing.TB, st store.Store, sub store.JobSubmission, lease func(store.Task) store.LeaseRequest,
) (out store.JobSubmission, attempts map[string]store.TaskAttempt)

SubmitLeasing submits sub with each task that asks to be assigned or running submitted ready, then leases it in submission order through Lease (and, for running, starts it through Start). That is the only way production puts a task there: one submitted assigned or running has no attempt, a state no production write produces. lease returns the request each such task is leased with, given the task as submitted; SubmitLeasing sets its TaskID. The job's farm and queue must already exist, because the lease checks them, and a terminal job cannot hold leased work, so asking for one fails the test.

It returns the submission with each leased task as stored after its lease, and the attempt each leased task holds, by task ID.

Types

type AuditReader

type AuditReader interface {
	// ListAuditEntries returns the audit entries for entityType and entityID,
	// oldest first. Empty strings match any value.
	ListAuditEntries(ctx context.Context, entityType, entityID string) ([]store.AuditEntry, error)
}

AuditReader reads a backend's audit log. Nothing in production reads it, so store.Store does not carry it; both concrete stores implement it so tests can assert that an action was audited.

type Injector

type Injector interface {
	InjectTaskAttempt(ctx context.Context, attempt store.TaskAttempt) (store.TaskAttempt, error)
	InjectClaim(ctx context.Context, claim store.UsageClaim) (store.UsageClaim, error)
	// InjectWorkerPowerState sets a registered worker's power state, time and
	// reason as given, with no transition checks.
	InjectWorkerPowerState(ctx context.Context, workerID string, state store.PowerState, at time.Time, reason string) error
}

Injector writes rows as given, with no state checks. Both concrete stores implement it; store.Store does not. It exists only to build states production cannot reach.

On both backends a zero attempt CreatedAt or claim ClaimedAt is stamped now, and a claim is always written active: its ReleasedAt is ignored.

func InjectorFor

func InjectorFor(t testing.TB, st store.Store) Injector

InjectorFor returns st's injectors, failing the test when st has none. A wrapper that embeds store.Store has none: pass the store it wraps.

type InvariantChecker

type InvariantChecker interface {
	// ClaimInvariantViolations returns the IDs of active claims whose attempt
	// is missing or not running, or whose task is terminal. Empty means I3
	// holds.
	ClaimInvariantViolations(ctx context.Context) ([]string, error)
}

InvariantChecker runs a backend's diagnostic for invariant I3 ("an active usage claim exists iff its attempt is open"). Both concrete stores implement it; store.Store does not.

type JobSeed

type JobSeed struct {
	// Sub is the submission built so far, for a test that needs a field the
	// methods do not set.
	Sub store.JobSubmission
}

JobSeed is one job's whole graph — the job, its steps and its tasks — which JobSeed.Submit writes with a single CreateJobSubmission. A job starts pending at priority 50 with no steps and no tasks, every row named after its ID; the chained methods add to it, and a row is written in whatever status it is given, exactly as CreateJobSubmission writes it.

A task asked for assigned or running is not written that way: submit it with JobSeed.SubmitLeasing, which leases it, so it carries the attempt and the worker a real lease makes.

func NewJob

func NewJob(id, farmID, queueID string) *JobSeed

NewJob starts a pending job at priority 50, named after its ID.

func (*JobSeed) As

func (j *JobSeed) As(status store.JobStatus) *JobSeed

As sets the job's status, stamping the timestamps a job in that status carries: started_at once it has run, completed_at once it is terminal.

func (*JobSeed) Step

func (j *JobSeed) Step(id string, status store.StepStatus) *JobSeed

Step adds a step in the given status, named after its ID and ordered after the steps before it, or sets the status of the step the job already holds under that ID.

func (*JobSeed) StepRow

func (j *JobSeed) StepRow(step store.Step) *JobSeed

StepRow adds the given step, filling in its job, its name (its ID) when it has none, and empty dependencies.

func (*JobSeed) Submit

func (j *JobSeed) Submit(t testing.TB, st store.Store) store.JobSubmission

Submit writes the whole graph through Submit and returns what the store wrote.

func (*JobSeed) SubmitLeasing

func (j *JobSeed) SubmitLeasing(
	t testing.TB, st store.Store, workerID string,
) (out store.JobSubmission, attempts map[string]store.TaskAttempt)

SubmitLeasing writes the whole graph through SubmitLeasing, leasing each assigned or running task to workerID.

func (*JobSeed) Task

func (j *JobSeed) Task(id, stepID string, status store.TaskStatus) *JobSeed

Task adds a task of stepID in the given status. A task and its step are one submission, so a pending step is added when the job holds none by that ID; call Step first to give the step another status. Step IDs are unique across jobs, as in the store, so two jobs in one test name different steps.

func (*JobSeed) TaskRow

func (j *JobSeed) TaskRow(task store.Task) *JobSeed

TaskRow adds the given task, filling in its job, its name (its ID) when it has none and empty parameters, and adding its step as Task does.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL