emutest

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 29 Imported by: ? 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 emutest starts an in-process gcpemu instance for Go tests (FR-CI-009). Every port is allocated dynamically and state is ephemeral unless WithDataDir says otherwise.

Start runs an Instance for one test; New and Close run one for a whole package, from TestMain. An Instance hands out client options for any Google client library (GRPCOptions, HTTPOptions) and ready-made Cloud Storage and Pub/Sub clients (Storage, PubSub).

Index

Examples

Constants

View Source
const ClusterOpTimeout = 16 * time.Minute

ClusterOpTimeout is how long tests wait for a GKE cluster operation. It is longer than the emulator's own bring-up waits added up (the k3s admin kubeconfig and the API server, twice when the server exits and is started again, the nodes and the add-ons' CRDs: 13m), with room for image setup, which has no deadline, so a slow bring-up fails with the emulator's error rather than the test's (#396).

View Source
const ClusterSlotsEnv = "GCPEMU_TEST_CLUSTERS"

ClusterSlotsEnv sets how many tests of the user's test binaries may run GKE clusters at once (default 2): every k3s server competes for CPU and disk, and too many on a CI runner crash the API server (#396).

Variables

This section is empty.

Functions

func HoldClusterSlot added in v0.9.0

func HoldClusterSlot(t testing.TB)

HoldClusterSlot waits for one of the cluster slots shared by the user's test binaries (ClusterSlotsEnv), up to the test's deadline, and holds it for the rest of the test. Tests that create GKE clusters call it before starting their emulator, and after t.Parallel, so a paused test holds none. Calling it again in the same test does nothing; a subtest that calls it takes a slot of its own.

func RequireRuntime

func RequireRuntime(t testing.TB)

RequireRuntime skips the test unless a container runtime is available (and GCPEMU_SKIP_CONTAINER_TESTS is unset), and makes a static gcpemu binary available for in-container agents.

Types

type Instance

type Instance struct {
	// contains filtered or unexported fields
}

Instance is a running test emulator.

func New added in v0.10.0

func New(ctx context.Context, svcs []string, opts ...Option) (*Instance, error)

New launches an Instance running svcs (plus their dependencies) that lives until Close, for sharing one Instance across a package's tests from TestMain. ctx bounds the start only. Unless WithDataDir is given, the Instance keeps its files in a Test data dir of its own that Close removes. Set GCPEMU_TEST_LOG=1 to see emulator logs, or GCPEMU_TEST_LOG_DIR to keep them in a file there.

func Start

func Start(t testing.TB, svcs []string, opts ...Option) *Instance

Start launches an Instance running svcs (plus their dependencies) and stops it when the test ends. Set GCPEMU_TEST_LOG=1 to see emulator logs, or GCPEMU_TEST_LOG_DIR to keep them in a file named after the test.

Example

Start runs an Instance for one test, and Storage connects a Cloud Storage client to it. In a test file, the function body is a TestXxx function's.

package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"testing"

	"github.com/linuxuser586/gcpemu/emutest"
)

func main() {
	asTest(func(t testing.TB) {
		inst := emutest.Start(t, []string{"gcs"})
		ctx := context.Background()
		b := inst.Storage(t).Bucket("example-bucket")
		if err := b.Create(ctx, "example-proj", nil); err != nil {
			t.Fatal(err)
		}
		w := b.Object("hello.txt").NewWriter(ctx)
		fmt.Fprint(w, "hello, emulator")
		if err := w.Close(); err != nil {
			t.Fatal(err)
		}
		r, err := b.Object("hello.txt").NewReader(ctx)
		if err != nil {
			t.Fatal(err)
		}
		defer r.Close()
		got, _ := io.ReadAll(r)
		fmt.Println(string(got))
	})
}

// asTest runs f as `go test` runs a test function, for examples, which get
// no testing.TB: f's cleanups run when it returns, and failing exits.
func asTest(f func(t testing.TB)) {
	t := &exampleTB{}
	defer func() {
		for i := len(t.cleanups) - 1; i >= 0; i-- {
			t.cleanups[i]()
		}
	}()
	f(t)
}

// exampleTB is the part of testing.TB that examples use.
type exampleTB struct {
	testing.TB
	cleanups []func()
}

func (t *exampleTB) Helper()                   {}
func (t *exampleTB) Cleanup(f func())          { t.cleanups = append(t.cleanups, f) }
func (t *exampleTB) Fatal(args ...any)         { log.Fatal(args...) }
func (t *exampleTB) Fatalf(f string, a ...any) { log.Fatalf(f, a...) }
Output:
hello, emulator

func (*Instance) Close added in v0.10.0

func (i *Instance) Close(ctx context.Context) error

Close stops the Instance and removes the Test data dir of its own, if it has one, unless its containers, networks or volumes could not be removed; the next test process reclaims them then. Calling it again returns the first call's error.

func (*Instance) Endpoint

func (i *Instance) Endpoint(name string) string

Endpoint returns the address (host:port) of a named listener, e.g. "gateway", "gcs", "pubsub".

func (*Instance) EnvVars added in v0.10.0

func (i *Instance) EnvVars() map[string]string

EnvVars returns every client environment variable the Instance advertises (`gcpemu env`), such as STORAGE_EMULATOR_HOST and PUBSUB_EMULATOR_HOST.

func (*Instance) GRPCOptions added in v0.10.0

func (i *Instance) GRPCOptions() []option.ClientOption

GRPCOptions returns the client options that connect any gRPC client library (cloud.google.com/go/...) to the Instance: an Endpoint override for its API gateway, no authentication and an insecure transport.

Example

GRPCOptions connects any gRPC client library to the Instance. An Instance from New lives until Close, so TestMain can share one.

package main

import (
	"context"
	"fmt"
	"log"
	"path"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"

	"github.com/linuxuser586/gcpemu/emutest"
)

func main() {
	ctx := context.Background()
	inst, err := emutest.New(ctx, []string{"secrets"})
	if err != nil {
		log.Fatal(err)
	}
	defer inst.Close(ctx)

	sm, err := secretmanager.NewClient(ctx, inst.GRPCOptions()...)
	if err != nil {
		log.Fatal(err)
	}
	defer sm.Close()
	s, err := sm.CreateSecret(ctx, &secretmanagerpb.CreateSecretRequest{
		Parent:   "projects/example-proj",
		SecretId: "api-key",
		Secret:   &secretmanagerpb.Secret{Replication: &secretmanagerpb.Replication{Replication: &secretmanagerpb.Replication_Automatic_{Automatic: &secretmanagerpb.Replication_Automatic{}}}},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(path.Base(s.Name))
}
Output:
api-key

func (*Instance) GatewayURL

func (i *Instance) GatewayURL() string

GatewayURL returns "http://<gateway>".

func (*Instance) HTTPOptions added in v0.10.0

func (i *Instance) HTTPOptions(api string) ([]option.ClientOption, error)

HTTPOptions returns the client options that connect the REST client library of the API named api (google.golang.org/api/<api>: "storage", "compute", "dns", "sqladmin", …) to the Instance: an Endpoint override for the API's path on the API gateway, and no authentication. It fails when the Instance does not serve api.

func (*Instance) Internal added in v0.10.0

func (i *Instance) Internal() *instance.Instance

Internal returns the running emulator. It is for gcpemu's own tests only: instance.Instance is internal to gcpemu and carries no compatibility promise.

func (*Instance) PubSub added in v0.10.0

func (i *Instance) PubSub(t testing.TB, project string) *pubsub.Client

PubSub returns a Pub/Sub client for project connected to the Instance, closed when the test ends. The test fails if the Instance does not run pubsub.

func (*Instance) Setenv

func (i *Instance) Setenv(t testing.TB)

Setenv sets every client environment variable the Instance advertises for the duration of the test.

func (*Instance) Storage added in v0.10.0

func (i *Instance) Storage(t testing.TB) *storage.Client

Storage returns a Cloud Storage client connected to the Instance, closed when the test ends. It reads through the JSON API, which the API gateway serves. The test fails if the Instance does not run gcs.

type Option

type Option struct {
	// contains filtered or unexported fields
}

Option customises an Instance before it starts.

func WithConfig added in v0.10.0

func WithConfig(f func(*config.Config)) Option

WithConfig edits the Instance's configuration directly. It is for gcpemu's own tests only: config.Config is internal to gcpemu, and the knobs it reaches carry no compatibility promise.

func WithConsole added in v0.10.0

func WithConsole() Option

WithConsole serves the Web console under /console, as an Instance does by default.

func WithDataDir added in v0.10.0

func WithDataDir(dir string) Option

WithDataDir runs a Persistent Instance in dir instead of an Ephemeral one: its state is kept in dir, and an Instance started later in the same dir finds it there. The Instance never removes dir, and its networks and volumes outlive the test until `gcpemu prune` removes them. For a dir the test owns (a Test data dir), use WithTestDataDir.

func WithDeterministic

func WithDeterministic() Option

WithDeterministic enables deterministic IDs and the fake clock.

func WithExternal added in v0.12.0

func WithExternal(api, addr string) Option

WithExternal delegates the API named api ("firestore", "spanner", …), which no Service serves, to the External emulator at addr (host:port), as `gcpemu start --external api=addr` does. An addr of "managed" has the Instance run Google's emulator for firestore, datastore, spanner or bigtable itself, which needs a container runtime (see RequireRuntime).

func WithIAMMode

func WithIAMMode(mode string) Option

WithIAMMode sets the IAM enforcement level: "off", "audit" (the default) or "enforce".

func WithLogOutput added in v0.15.0

func WithLogOutput(w io.Writer) Option

WithLogOutput also writes the Instance's log, at info level and above, to w, from before it starts. The Instance writes to w from many goroutines, one record per Write call, so w must be safe for concurrent use. Set GCPEMU_TEST_LOG=1 to see the log on stderr as well.

func WithOffline added in v0.10.0

func WithOffline() Option

WithOffline never reaches the internet: images are not pulled and nothing is read through from Google.

func WithOperationLatency added in v0.10.0

func WithOperationLatency(serviceID string, d time.Duration) Option

WithOperationLatency makes the Operations of the Service serviceID ("compute", "gke", "sql", …, or "*" for every Service) complete after d instead of at once.

func WithSQLHostClients added in v0.8.0

func WithSQLHostClients() Option

WithSQLHostClients has Cloud SQL instances with a public IP serve host clients on a loopback address on a VM runtime (ADR 0005), as gcpemu does, for tests that dial the address an instance reports (the Cloud SQL connector, pgx or psql to its PRIMARY IP). Without it they serve none, and the host reaches each instance only on its published port (GCPEMU_SQL_<INSTANCE>). On a host without loopback aliases every instance would serve on 127.0.0.1, so the Instance then holds a lock shared by the user's test binaries for as long as it runs, and their instances must serve one at a time.

func WithSeed added in v0.10.0

func WithSeed(path string) Option

WithSeed applies the Seed file at path before the Instance reports ready, as `gcpemu start --seed` does.

func WithStrictProjects added in v0.10.0

func WithStrictProjects() Option

WithStrictProjects refuses requests for a project that was not declared, in a Seed file or by creating it, instead of creating it on first use.

func WithTestDataDir added in v0.13.0

func WithTestDataDir(t testing.TB, dir string) Option

WithTestDataDir runs a Persistent Instance in dir, as WithDataDir does, for a Test data dir that t owns, such as t.TempDir(). When t ends, after its Instances have stopped, the containers, networks and volumes of the Instance in dir are removed, as an Ephemeral Instance's are when it stops; Instances started again in dir during t still find them. A failure to remove them fails t.

Jump to

Keyboard shortcuts

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