testutil

package
v0.0.0-...-a798bc3 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BaseURL

func BaseURL() string

BaseURL returns the test server base address clients are constructed with.

func DatabaseUnderTest

func DatabaseUnderTest() config.DBType

DatabaseUnderTest returns the dialect a framework suite runs against: MySQL, the framework's primary dialect, unless the test binary is built with the gsttest_postgres or the gsttest_sqlite build tag. The tags are a contract between the suites' TestMain functions and the Makefile test target, which repeats them once per dialect. The public testutil knows nothing about them, so projects built on it keep full control of their own Server.Database.

The dialect is fixed when the test binary is built, not read from the environment when it runs, because go's test cache only tells runs apart by what it sees: a build tag makes each dialect a test binary of its own, with a cached result of its own, while a variable TestMain reads before m.Run installs the test log is invisible to the cache, which then replays one dialect's result for every other. Building with both tags declares the dialect twice and fails to compile.

Two mistakes stop the run instead of letting the suite run against MySQL once more under the impression it ran against another dialect. A misspelled tag selects no dialect, but the binary's build settings still carry it, so a binary that fell back to MySQL while built with one returns what the tag names instead, gsttest_postgre as postgre, which the test database setup then rejects like every dialect it has no preparation for. Setting the GST_TEST_DATABASE variable panics with the tag to build with instead; since go test replays a cached result without running TestMain at all, that stop comes once the suite actually runs, which it does after any change to what the suite tests.

func DecodeResp

func DecodeResp[RSP any](t *testing.T, resp *client.Envelope) RSP

DecodeResp asserts that resp carries a successful envelope and returns the decoded payload.

func DialGRPC

func DialGRPC(t *testing.T) *grpc.ClientConn

DialGRPC connects to the test server's gRPC listener, at GRPCTarget, in plaintext, the way the listener is served, and closes the connection when the test ends. A call made on it presents no credential of its own: a session id or a token travels in the call's context, see grpc.WithBearer.

func DownloadCSV

func DownloadCSV(t *testing.T, cli *client.Client, path string, opts ...client.RequestOption) [][]string

DownloadCSV downloads path as a CSV export through cli and parses the attachment into records, stripping a leading UTF-8 BOM if present. The helper sets the CSV format parameter itself; opts carry the remaining query parameters, such as filters.

func GRPCTarget

func GRPCTarget() string

GRPCTarget returns the address the test server's gRPC listener is dialed at, the target a grpc.NewClient takes. Like the HTTP port, the port is picked per test binary, so the target can be declared as a package-level variable; the listener itself comes up only when the test binary registers gRPC services, see Run, and a test binary that registered none is told so instead of dialing a port nothing listens on: GRPCTarget panics naming the import that registers them, the project's pb package in the test file declaring TestMain, the way main.go imports it.

func RequireCount

func RequireCount[T any, M interface {
	types.Model
	*T
}](t *testing.T, query M) int

RequireCount asserts that counting the rows matching the query succeeds and returns the count. A nil or zero-value query matches no rows: WithQuery keeps the framework's empty-query safety check, so a deliberate full-table count stays on the database chain.

func RequireDataFields

func RequireDataFields(t *testing.T, resp *client.Envelope, fields ...string)

RequireDataFields asserts that the raw envelope data carries every named top-level JSON field, guarding serialization contracts against fields silently vanishing behind omitempty.

func RequireError

func RequireError(t *testing.T, err error, statusCode int, msgContains ...string) client.Error

RequireError asserts that err is a server-side rejection with the given HTTP status code and that the message contains every msgContains entry. The rejection is returned by value for follow-up asserts, such as the raw body; the value form keeps ignoring it errcheck-clean.

func RequireFirst

func RequireFirst[T any, M interface {
	types.Model
	*T
}](t *testing.T, query M) M

RequireFirst asserts that at least one row matches the query and returns the first match. A nil or zero-value query matches no rows: WithQuery keeps the framework's empty-query safety check, so a deliberate full-table read stays on the database chain.

func RequireGet

func RequireGet[T any, M interface {
	types.Model
	*T
}](t *testing.T, id string) M

RequireGet asserts that the row with the given id exists and returns it.

func RequireList

func RequireList[T any, M interface {
	types.Model
	*T
}](t *testing.T, query M, orders ...types.Order) []M

RequireList asserts that listing the rows matching the query succeeds and returns them, sorted by orders when given. An empty result is a valid return; length assertions stay with the caller. A nil or zero-value query matches no rows: WithQuery keeps the framework's empty-query safety check, so a deliberate full-table read stays on the database chain.

func RequireNoRow

func RequireNoRow[T any, M interface {
	types.Model
	*T
}](t *testing.T, id string)

RequireNoRow asserts that no row with the given id is visible through the regular query path. A hard-deleted and a soft-deleted row both satisfy it; RequireSoftDeleted additionally pins that a soft-deleted row is kept.

func RequireSoftDeleted

func RequireSoftDeleted[T any, M interface {
	types.Model
	*T
}](t *testing.T, id string)

RequireSoftDeleted asserts that the row with the given id is soft-deleted: gone from the regular query path while WithDeleted still finds it. Both reads span every tenant, so a row filed under another tenant is judged by its deletion rather than kept out of sight by the tenant scope, and gorm's own soft-delete scope decides what counts as deleted, whatever column and zero value the model declares for it.

func Run

func Run(m *testing.M, s Server)

Run prepares what s declares, starts the test server, runs the tests and releases everything afterwards. The server listens for HTTP at BaseURL and, when the test binary registered gRPC services — a project's generated pb package registers them when imported, the way main.go imports it — for gRPC at GRPCTarget. It is the whole body of a test package's TestMain:

func TestMain(m *testing.M) {
	testutil.Run(m, testutil.Server{
		Database: config.DBMySQL,
		Redis:    true,
		Register: func() { iam.Register() },
		Routes:   router.Init,
	})
}

Run returns once the tests have run and everything is released, so a call TestMain defers runs; the test binary then exits with the result of the tests, which testing hands to os.Exit itself once TestMain returns. A setup that fails panics, which ends the binary after what came up before it is released.

func URL

func URL(path string) string

URL returns an absolute URL of the test server for path.

Types

type Server

type Server struct {
	// Database selects which database the tests run against. It defaults to
	// config.DBSqlite, the framework default, which needs no container.
	Database config.DBType

	// Redis prepares a redis container and points the framework at it. Modules
	// that keep sessions or cache entries need it.
	Redis bool

	// Clickhouse prepares a clickhouse database and points the framework
	// provider at it, next to whatever Database selects: clickhouse is an
	// analytical instance beside the default database, never a replacement
	// for it. Tests reach it through config.App.Clickhouse or the provider.
	Clickhouse bool

	// Kafka prepares a kafka container and points the framework provider at
	// it. Tests reach it through config.App.Kafka or the provider.
	Kafka bool

	// RocketMQ prepares a rocketmq container and points the framework
	// provider at it. Tests reach it through config.App.RocketMQ or the
	// provider.
	RocketMQ bool

	// Elasticsearch prepares an elasticsearch container and points the
	// framework provider at it. Tests reach it through
	// config.App.Elasticsearch or the provider.
	Elasticsearch bool

	// Minio prepares a minio bucket and points the framework provider at
	// it. Tests reach it through config.App.Minio or the provider.
	Minio bool

	// Register registers the modules under test. It runs before the framework
	// bootstraps, which is where module registration belongs. Registration
	// mirrors the framework's Register style and reports nothing.
	Register func()

	// Routes registers routes that need a bootstrapped framework, such as the
	// generated router.Init of a project — which the field accepts directly:
	// Routes: router.Init. It runs after the bootstrap and before Seed; a
	// returned error fails the test setup.
	Routes func() error

	// Seed plants baseline rows such as a root account. It runs after Routes,
	// once the framework is up and the database is reachable, but before the
	// server starts serving, so no request can observe a half prepared state.
	// A returned error fails the test setup.
	Seed func() error
}

Server declares what a test package needs before its tests can run. Every field is optional: the zero value prepares the framework defaults, which is an sqlite database and no cache, and registers nothing.

Directories

Path Synopsis
Package golist reads the packages of the module a test runs in through go list, for a test that reads the source of packages other than its own.
Package golist reads the packages of the module a test runs in through go list, for a test that reads the source of packages other than its own.
Package oteltest turns real OpenTelemetry tracing on inside one framework test and reads back the spans it exports.
Package oteltest turns real OpenTelemetry tracing on inside one framework test and reads back the spans it exports.
Package providertest runs the tests of a provider package against the external services they need, with the framework brought up as far as its provider stage and no further.
Package providertest runs the tests of a provider package against the external services they need, with the framework brought up as far as its provider stage and no further.
Package swap replaces process-wide values for the duration of one test.
Package swap replaces process-wide values for the duration of one test.
Package testcontainer prepares the services the framework's tests run against, in containers started through testcontainers-go.
Package testcontainer prepares the services the framework's tests run against, in containers started through testcontainers-go.
Package testlog keeps the framework's logs of a test process out of the test output and out of the package source tree, where log files changing with every run would make go's test cache rerun every test that reads or lists the tree.
Package testlog keeps the framework's logs of a test process out of the test output and out of the package source tree, where log files changing with every run would make go's test cache rerun every test that reads or lists the tree.

Jump to

Keyboard shortcuts

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