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 ¶
- Constants
- func HoldClusterSlot(t testing.TB)
- func RequireRuntime(t testing.TB)
- type Instance
- func (i *Instance) Close(ctx context.Context) error
- func (i *Instance) Endpoint(name string) string
- func (i *Instance) EnvVars() map[string]string
- func (i *Instance) GRPCOptions() []option.ClientOption
- func (i *Instance) GatewayURL() string
- func (i *Instance) HTTPOptions(api string) ([]option.ClientOption, error)
- func (i *Instance) Internal() *instance.Instance
- func (i *Instance) PubSub(t testing.TB, project string) *pubsub.Client
- func (i *Instance) Setenv(t testing.TB)
- func (i *Instance) Storage(t testing.TB) *storage.Client
- type Option
- func WithConfig(f func(*config.Config)) Option
- func WithConsole() Option
- func WithDataDir(dir string) Option
- func WithDeterministic() Option
- func WithExternal(api, addr string) Option
- func WithIAMMode(mode string) Option
- func WithOffline() Option
- func WithOperationLatency(serviceID string, d time.Duration) Option
- func WithSQLHostClients() Option
- func WithSeed(path string) Option
- func WithStrictProjects() Option
Examples ¶
Constants ¶
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).
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
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 ¶
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
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 temporary directory that Close removes. Set GCPEMU_TEST_LOG=1 to see emulator logs.
func Start ¶
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.
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
Close stops the Instance and removes its temporary data dir. Calling it again returns the first call's error.
func (*Instance) Endpoint ¶
Endpoint returns the address (host:port) of a named listener, e.g. "gateway", "gcs", "pubsub".
func (*Instance) EnvVars ¶ added in v0.10.0
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 ¶
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
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
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 ¶
Setenv sets every client environment variable the Instance advertises for the duration of the test.
type Option ¶
type Option struct {
// contains filtered or unexported fields
}
Option customises an Instance before it starts.
func WithConfig ¶ added in v0.10.0
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 it is even under CI=true.
func WithDataDir ¶ added in v0.10.0
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.
func WithDeterministic ¶
func WithDeterministic() Option
WithDeterministic enables deterministic IDs and the fake clock.
func WithExternal ¶ added in v0.12.0
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 ¶
WithIAMMode sets the IAM enforcement level: "off", "audit" (the default) or "enforce".
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
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
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.