Documentation
¶
Overview ¶
Package nktest provides a Nakama test runner that makes it easy to build and test Nakama module plugins with complex, advanced game logic using nothing but "go test".
See also github.com/ascii8/nakama-go package for a web/realtime Nakama Go client.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"io"
"log"
"net/http"
"strconv"
)
func main() {
// create context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
urlstr := "http://127.0.0.1:7350/healthcheck"
req, err := http.NewRequestWithContext(ctx, "GET", urlstr, nil)
if err != nil {
log.Fatal(err)
}
// create client and execute request
cl := &http.Client{
Transport: &http.Transport{
DisableCompression: true,
},
}
res, err := cl.Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
// check response
if res.StatusCode != http.StatusOK {
log.Fatalf("status %d != 200", res.StatusCode)
}
// read response
buf, err := io.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println("healthcheck:", strconv.Itoa(res.StatusCode), http.StatusText(res.StatusCode), string(bytes.TrimSpace(buf)))
}
Output: healthcheck: 200 OK {}
Index ¶
- Variables
- func AlwaysPull(ctx context.Context) bool
- func Backoff(ctx context.Context, f func() error) error
- func Cancel() error
- func ConfigFilename(ctx context.Context) string
- func ConfigTemplate(ctx context.Context) string
- func ConsoleWriter(ctx context.Context) io.Writer
- func Debug(ctx context.Context) *zerolog.Event
- func DockerAuthName(ctx context.Context) string
- func DockerAuthScope(ctx context.Context, id string) string
- func DockerImageTags(ctx context.Context, id string) ([]string, error)
- func DockerRegistryURL(ctx context.Context) string
- func DockerToken(ctx context.Context, id string) (string, error)
- func DockerTokenURL(ctx context.Context) string
- func Err(ctx context.Context, err error) *zerolog.Event
- func GoEnvVar(goPath, name string) (string, error)
- func HostPortMap(ctx context.Context, id, svc string, containerPort, hostPort uint16) uint16
- func HttpClient(ctx context.Context) *http.Client
- func Info(ctx context.Context) *zerolog.Event
- func IsSubDir(a, b string) error
- func LocalAddr(l net.Listener) string
- func Logger(ctx context.Context) zerolog.Logger
- func Main(parent context.Context, m TestRunner, opts ...Option)
- func NakamaImageId(ctx context.Context) string
- func NakamaVersion(ctx context.Context) (string, error)
- func New(ctx, conn context.Context, opts ...Option)
- func NewConsoleWriter(w, cw io.Writer, field, value string) io.Writer
- func NoopWriter() io.Writer
- func ParsePortMapping(s string) (pntypes.PortMapping, error)
- func PluginbuilderImageId(ctx context.Context) string
- func PodRemoveTimeout(ctx context.Context) time.Duration
- func PodmanBuildMounts(mounts ...string) ([]pspec.Mount, error)
- func PodmanConn(ctx context.Context) context.Context
- func PodmanCreatePod(ctx context.Context, podName string, ids ...string) (string, string, error)
- func PodmanFollowLogs(ctx context.Context, id string) error
- func PodmanGetAddr(ctx context.Context, id, svc string) (string, string, error)
- func PodmanOpen(ctx context.Context) (context.Context, context.Context, error)
- func PodmanPodKill(ctx context.Context, name string) error
- func PodmanPullImages(ctx context.Context, ids ...string) error
- func PodmanRun(ctx context.Context, podId, id string, env map[string]string, mounts []string, ...) (string, error)
- func PodmanServiceWait(ctx context.Context, id, svc string, f func(string, string) error) error
- func PodmanWait(ctx context.Context, id string) error
- func PortMap(ctx context.Context) map[string]uint16
- func PostgresImageId(ctx context.Context) string
- func PostgresVersion(ctx context.Context) string
- func PrefixedWriter(w io.Writer, prefix string) io.Writer
- func QualifiedId(id string) string
- func ReadCachedFile(name string, ttl time.Duration) ([]byte, error)
- func Run() error
- func RunProxy(ctx context.Context, opts ...ProxyOption) (string, error)
- func SetVerbose(verbose bool)
- func ShortId(id string) string
- func Stdout(ctx context.Context) io.Writer
- func Transport(ctx context.Context, transport http.RoundTripper) http.RoundTripper
- func VersionCacheTTL(ctx context.Context) time.Duration
- func WithAlwaysPull(parent context.Context, alwaysPull bool) context.Context
- func WithAlwaysPullFromEnv(parent context.Context, name string) context.Context
- func WithBackoffMaxElapsedTime(parent context.Context, maxElapsedTime time.Duration) context.Context
- func WithBackoffMaxInterval(parent context.Context, maxInterval time.Duration) context.Context
- func WithConfigFilename(parent context.Context, configFilename string) context.Context
- func WithConfigTemplate(parent context.Context, configTemplate string) context.Context
- func WithConsoleWriter(parent context.Context, consoleWriter io.Writer) context.Context
- func WithDockerAuthName(parent context.Context, dockerAuthName string) context.Context
- func WithDockerAuthScope(parent context.Context, dockerAuthScope string) context.Context
- func WithDockerRegistryURL(parent context.Context, dockerRegistryURL string) context.Context
- func WithDockerTokenURL(parent context.Context, dockerTokenURL string) context.Context
- func WithHostPortMap(parent context.Context) context.Context
- func WithHttpClient(parent context.Context, httpClient *http.Client) context.Context
- func WithNakamaImageId(parent context.Context, nakamaImageId string) context.Context
- func WithNakamaVersion(parent context.Context, nakamaVersion string) context.Context
- func WithPluginbuilderImageId(parent context.Context, pluginbuilderImageId string) context.Context
- func WithPodRemoveTimeout(parent context.Context, podRemoveTimeout time.Duration) context.Context
- func WithPodmanConn(parent, conn context.Context) context.Context
- func WithPortMap(parent context.Context, id, svc string, port uint16) context.Context
- func WithPostgresImageId(parent context.Context, postgresImageId string) context.Context
- func WithPostgresVersion(parent context.Context, postgresVersion string) context.Context
- func WithStdout(parent context.Context, stdout io.Writer) context.Context
- func WithVersionCacheTTL(parent context.Context, versionCacheTTL time.Duration) context.Context
- type BuildConfig
- type BuildConfigOption
- func WithDefaultGoEnv() BuildConfigOption
- func WithDefaultGoVolumes() BuildConfigOption
- func WithEnv(env map[string]string) BuildConfigOption
- func WithGoEnv(env ...string) BuildConfigOption
- func WithGoEnvVolumes(volumes ...EnvVolumeInfo) BuildConfigOption
- func WithMounts(mounts ...string) BuildConfigOption
- func WithOut(out string) BuildConfigOption
- type EnvVolumeInfo
- type Option
- type PodmanConnInfo
- type Proxy
- type ProxyOption
- type RoundTripper
- type Runner
- func (r *Runner) BuildModule(ctx context.Context, id string, bc *BuildConfig) error
- func (r *Runner) BuildModules(ctx context.Context, id string) error
- func (r *Runner) ConsoleLocal() string
- func (r *Runner) ConsoleRemote() string
- func (r *Runner) GrpcLocal() string
- func (r *Runner) GrpcRemote() string
- func (r *Runner) HttpKey() string
- func (r *Runner) HttpLocal() string
- func (r *Runner) HttpRemote() string
- func (r *Runner) Name() string
- func (r *Runner) PodContainerId() string
- func (r *Runner) PodId() string
- func (r *Runner) PostgresLocal() string
- func (r *Runner) PostgresRemote() string
- func (r *Runner) Run(ctx context.Context) error
- func (r *Runner) RunNakama(ctx context.Context, id string) error
- func (r *Runner) RunPostgres(ctx context.Context, id string) error
- func (r *Runner) RunProxy(ctx context.Context, opts ...ProxyOption) (string, error)
- func (r *Runner) ServerKey() string
- type TestLogger
- type TestRunner
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( DefaultPrefixOut = "-> " DefaultPrefixIn = "<- " DefaultAlwaysPull = false DefaultPostgresImageId = "docker.io/library/postgres" DefaultNakamaImageId = "docker.io/heroiclabs/nakama" DefaultPluginbuilderImageId = "docker.io/heroiclabs/nakama-pluginbuilder" DefaultPostgresVersion = "latest" DefaultDockerRegistryURL = "https://registry-1.docker.io" DefaultDockerTokenURL = "https://auth.docker.io/token" DefaultDockerAuthName = "registry.docker.io" DefaultDockerAuthScope = "repository:%s:pull" DefaultVersionCacheTTL = 96 * time.Hour DefaultPodRemoveTimeout = 200 * time.Millisecond DefaultBackoffMaxInterval = 2 * time.Second DefaultBackoffMaxElapsedTime = 30 * time.Second DefaultConfigFilename = "config.yml" //go:embed config.yml.tpl DefaultConfigTemplate string )
Defaults.
var ContainerEmptyValue = "--------"
ContainerEmptyValue is the container empty value.
var ContainerIdFieldName = "container_id"
ContainerIdFieldName is the container field name used for logs.
var DefaultProxyReadSize = 10 * 1024 * 1024
DefaultProxyReadSize is the default websocket proxy read size.
var DefaultProxyWriteSize = 10 * 1024 * 1024
DefaultProxyWriteSize is the default websocket proxy write size.
var DefaultTransport http.RoundTripper = &http.Transport{ DisableCompression: true, }
DefaultTranpsort is the default http transport.
var TimeFormatValue = "2006-01-02 15:04:05"
TimeFormatValue is the time format.
Functions ¶
func AlwaysPull ¶ added in v0.5.0
AlwaysPull returns whether or not to always pull an image.
func Backoff ¶ added in v0.5.0
Backoff executes f until backoff conditions are met or until f returns nil, or the context is closed.
func ConfigFilename ¶ added in v0.5.0
ConfigFilename returns the config filename.
func ConfigTemplate ¶ added in v0.5.0
ConfigTemplate returns the config template.
func ConsoleWriter ¶ added in v0.7.0
ConsoleWriter returns the consoleWriter from the context.
func DockerAuthName ¶ added in v0.5.0
DockerAuthName returns the docker token auth name.
func DockerAuthScope ¶ added in v0.5.0
DockerAuthScope returns the docker token auth scope for a image id.
func DockerImageTags ¶ added in v0.5.0
DockerImageTags gets the docker registry tags for a image id.
func DockerRegistryURL ¶ added in v0.5.0
DockerRegistryURL returns the docker registry url.
func DockerToken ¶ added in v0.5.0
DockerToken generates a docker auth token for the repo id.
func DockerTokenURL ¶ added in v0.5.0
DockerTokenURL returns the docker token url.
func HostPortMap ¶ added in v0.5.0
HostPortMap returns the host port for the provided container id and service from the context.
func HttpClient ¶ added in v0.5.0
HttpClient returns the http client from the context.
func Main ¶ added in v0.5.0
func Main(parent context.Context, m TestRunner, opts ...Option)
Main is the main entry point that should be called from TestMain.
func NakamaImageId ¶ added in v0.5.0
NakamaImageId returns the nakama image id.
func NakamaVersion ¶ added in v0.5.0
NakamaVersion loads and caches the nakama version.
func NewConsoleWriter ¶ added in v0.7.1
NewConsoleWriter creates a zerolog console writer.
func ParsePortMapping ¶ added in v0.3.4
func ParsePortMapping(s string) (pntypes.PortMapping, error)
ParsePortMapping creates a port mapping from s.
func PluginbuilderImageId ¶ added in v0.5.0
PluginbuilderImageId returns the pluginbuilder image id.
func PodRemoveTimeout ¶ added in v0.6.1
PodRemoveTimeout returns the pod remove timeout.
func PodmanBuildMounts ¶
PodmanBuildMounts creates mount specs for a container.
func PodmanConn ¶ added in v0.5.0
PodmanConn returns the podman connection on the context.
func PodmanCreatePod ¶
PodmanCreatePod creates a pod network.
func PodmanFollowLogs ¶
PodmanFollowLogs follows the logs for a container.
func PodmanGetAddr ¶
PodmanGetAddr inspects id and returns the local and remote addresses.
func PodmanOpen ¶ added in v0.4.2
PodmanOpen opens a podman context. If no client exists in the current context, then a new context is created and merged with the parent context, otherwise ctx is passed through unchanged.
func PodmanPodKill ¶ added in v0.6.1
PodmanPodKill kills pod with matching name.
func PodmanPullImages ¶
PodmanPullImages grabs image ids when not present on the host or when AlwaysPull returns true.
func PodmanRun ¶
func PodmanRun(ctx context.Context, podId, id string, env map[string]string, mounts []string, entrypoint ...string) (string, error)
PodmanRun runs a container image id.
func PodmanServiceWait ¶
PodmanServiceWait waits for a container service to be available.
func PodmanWait ¶
PodmanWait waits until a container has stopped.
func PostgresImageId ¶ added in v0.5.0
PostgresImageId returns the postgres image id.
func PostgresVersion ¶ added in v0.5.0
PostgresVersion returns the postgres version.
func PrefixedWriter ¶
PrefixedWriter creates a new prefixed writer.
func QualifiedId ¶
QualifiedId fully qualifies a container image id.
func ReadCachedFile ¶
ReadCachedFile reads a cached file from disk, returns error if the file name on disk is past the ttl.
func RunProxy ¶ added in v0.5.1
func RunProxy(ctx context.Context, opts ...ProxyOption) (string, error)
RunProxy creates and runs a http proxy until the context is closed.
func SetVerbose ¶ added in v0.5.0
func SetVerbose(verbose bool)
SetVerbose sets the global verbose value.
func Transport ¶
func Transport(ctx context.Context, transport http.RoundTripper) http.RoundTripper
Transport creates a transport from the context.
func VersionCacheTTL ¶ added in v0.5.0
VersionCacheTTL returns the version cache ttl.
func WithAlwaysPull ¶
WithAlwaysPull sets the always pull flag on the context. When true, causes container images to be pulled regardless of if they are available on the host or not.
func WithAlwaysPullFromEnv ¶ added in v0.5.0
WithAlwaysPull sets the always pull flag from an environment variable on the context.
func WithBackoffMaxElapsedTime ¶
func WithBackoffMaxElapsedTime(parent context.Context, maxElapsedTime time.Duration) context.Context
WithBackofffMaxElapsedTime sets the max backoff elapsed time on the context. Used when waiting for services (ie, postgres, nakama) to start/become available.
func WithBackoffMaxInterval ¶
WithBackofffMaxInterval sets the max backoff interval on the context. Used when waiting for services (ie, postres, nakama) to start/become available.
func WithConfigFilename ¶
WithConfigFilename sets the config filename on the context.
func WithConfigTemplate ¶
WithConfigTemplate sets the config template on the context.
func WithConsoleWriter ¶ added in v0.7.1
WithConsoleWriter sets the console writer out on the context.
func WithDockerAuthName ¶
WithDockerAuthName sets the docker token auth name on the context. Used when generating auth tokens for the docker registry.
func WithDockerAuthScope ¶
WithDockerAuthScope sets a docker token auth scope mask on the context. Must include "%s" to interpolate the image id.
func WithDockerRegistryURL ¶
WithDockerRegistryURL sets the docker registry url on the context. Used for retrieving images.
func WithDockerTokenURL ¶
WithDockerTokenURL sets the docker token url on the context. Used for generating auth tokens when pulling images.
func WithHostPortMap ¶ added in v0.3.4
WithHostPortMap adds host port mappings for the postgres and nakama services (5432/tcp, 7349/tcp, 7350/tcp, 7351/tcp) to the context.
func WithHttpClient ¶
WithHttpClient sets the http client used on the context. Used for generating auth tokens for image repositories.
func WithNakamaImageId ¶
WithNakamaImageId sets the nakama image id on the context.
func WithNakamaVersion ¶
WithNakamaVersion sets the nakama image tag on the context.
func WithPluginbuilderImageId ¶
WithPluginbuilderImageId sets the pluginbuilder image id on the context.
func WithPodRemoveTimeout ¶ added in v0.6.1
WithPodRemoveTimeout sets the pod remove timeout on the context.
func WithPodmanConn ¶ added in v0.5.0
WithPodmanConn sets the podman conn used on the context.
func WithPortMap ¶ added in v0.3.4
WithPortMap adds a host port mapping for a service to the context.
func WithPostgresImageId ¶
WithPostgresImageId sets the postgres image id on the context.
func WithPostgresVersion ¶
WithPostgresVersion sets the postgres image tag on the context.
func WithStdout ¶
WithStdout sets the stdout on the context.
Types ¶
type BuildConfig ¶
type BuildConfig struct {
// contains filtered or unexported fields
}
BuildConfig is a nakama module build config.
type BuildConfigOption ¶
type BuildConfigOption func(*BuildConfig) error
BuildConfigOption is nakama module build config option.
func WithDefaultGoEnv ¶
func WithDefaultGoEnv() BuildConfigOption
WithDefaultGoEnv is a nakama module build config option to copy default host environment variables for Go.
Copies:
GONOPROXY GONOSUMDB GOPRIVATE GOPROXY GOSUMDB
func WithDefaultGoVolumes ¶
func WithDefaultGoVolumes() BuildConfigOption
WithGoVolumes is a nakama module build config option to mount the host's Go directories (GOCACHE, GOMODCACHE, and GOPATH) to the plugin builder container. Significantly speeds up build times.
func WithEnv ¶
func WithEnv(env map[string]string) BuildConfigOption
WithEnv is a nakama module build config option to set additional env variables used during builds.
func WithGoEnv ¶
func WithGoEnv(env ...string) BuildConfigOption
WithGoEnv is a nakama module build config option to copy the host Go environment variables.
func WithGoEnvVolumes ¶
func WithGoEnvVolumes(volumes ...EnvVolumeInfo) BuildConfigOption
WithGoVolumes is a nakama module build config option to mount the host's Go directories (ie, the Go environment's GOCACHE, GOMODCACHE, and GOPATH locations) to the plugin builder container. Significantly speeds up build times.
Note: use WithDefaultGoVolumes (see below).
func WithMounts ¶
func WithMounts(mounts ...string) BuildConfigOption
WithMounts is a nakama module build config option to set additional mounts used during builds.
func WithOut ¶
func WithOut(out string) BuildConfigOption
WithOut is a nakama module build config option to set the out name. When not specified, the name will be derived from the directory name of the module.
type EnvVolumeInfo ¶
EnvVolumeInfo holds information about an environment variable derived volume.
func NewEnvVolume ¶
func NewEnvVolume(key, target, sub string) EnvVolumeInfo
NewEnvVolume creates a new environment volume.
type Option ¶
type Option func(*Runner)
Option is a nakama test runner option.
func WithBuildConfig ¶
func WithBuildConfig(modulePath string, opts ...BuildConfigOption) Option
WithBuildConfig is a nakama test runner option to add a module path, and extra options to the build config.
func WithVolumeDir ¶
WithVolumeDir is a nakama test runner option to set the volume dir, where nakama and postgres data/configs are written. Default is <project root>/.cache. Must be a sub dir of the project root.
type PodmanConnInfo ¶ added in v0.4.2
type PodmanConnInfo struct {
Name string `json:"Name"`
URI string `json:"URI"`
Identity string `json:"Identity"`
Default bool `json:"Default"`
}
PodmanConnInfo holds information about a podman connection.
func BuildPodmanConnInfo ¶ added in v0.4.2
func BuildPodmanConnInfo(ctx context.Context) ([]PodmanConnInfo, error)
BuildPodmanConnInfo builds a list of potential podman connection info.
func PodmanSystemConnectionList ¶ added in v0.4.2
func PodmanSystemConnectionList(ctx context.Context) ([]PodmanConnInfo, error)
PodmanSystemConnectionList executes podman system connection list to retrieve the remote socket list.
type Proxy ¶
type Proxy struct {
// contains filtered or unexported fields
}
Proxy is a http and websocket logging proxy.
func NewProxy ¶
func NewProxy(opts ...ProxyOption) *Proxy
NewProxy creates a new http and websocket logging proxy.
type ProxyOption ¶
type ProxyOption func(*Proxy)
ProxyOption is a proxy option.
func WithAddr ¶
func WithAddr(addr string) ProxyOption
WithAddr is a proxy option to set the listen address.
func WithDialer ¶
func WithDialer(dialer websocket.Dialer) ProxyOption
WithDialer is a proxy option to set the websocket dialer.
func WithUpgrader ¶
func WithUpgrader(upgrader websocket.Upgrader) ProxyOption
WithUpgrader is a proxy option to set the websocket upgrader.
func WithWsPath ¶
func WithWsPath(wsPath string) ProxyOption
WithWsPath is a proxy option to set the websocket remote path.
type RoundTripper ¶ added in v0.5.0
type RoundTripper struct {
// contains filtered or unexported fields
}
RoundTripper is a logging transport.
func NewRoundTripper ¶ added in v0.5.0
func NewRoundTripper(req, res io.Writer, transport http.RoundTripper) *RoundTripper
NewRoundTripper creates a logging transport.
func (*RoundTripper) DisableReqBody ¶ added in v0.5.0
func (t *RoundTripper) DisableReqBody()
DisableReqBody disables logging the request body.
func (*RoundTripper) DisableResBody ¶ added in v0.5.0
func (t *RoundTripper) DisableResBody()
DisableResBody disables logging the response body.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner is a nakama test runner.
func WithCancel ¶ added in v0.5.0
func WithCancel(parent context.Context, t TestLogger) (context.Context, context.CancelFunc, *Runner)
WithCancel creates a new context for use within Test* funcs.
func (*Runner) BuildModule ¶
BuildModule builds a nakama plugin module.
func (*Runner) BuildModules ¶
BuildModules builds the nakama modules.
func (*Runner) ConsoleLocal ¶ added in v0.4.0
ConsoleLocal returns the console local address.
func (*Runner) ConsoleRemote ¶ added in v0.4.0
ConsoleRemote returns the console remote address.
func (*Runner) GrpcRemote ¶
GrpcRemote returns the grpc remote address.
func (*Runner) HttpRemote ¶
HttpRemote returns the http remote address.
func (*Runner) PodContainerId ¶ added in v0.6.0
PodContainerId returns the pod infrastructure container id.
func (*Runner) PostgresLocal ¶
PostgresLocal returns the postgres local address.
func (*Runner) PostgresRemote ¶
PostgresRemote returns the postgres remote address.
func (*Runner) Run ¶
Run handles building the nakama plugin and starting the postgres and nakama server containers.
func (*Runner) RunPostgres ¶
RunPostgres runs the postgres server.
type TestLogger ¶ added in v0.5.0
type TestLogger interface {
Logf(string, ...interface{})
}
TestLogger is the test log interface. Compatible with stdlib's testing.T.
type TestRunner ¶ added in v0.5.0
type TestRunner interface {
Run() int
}
TestRunner is the test runner interface. Compatible with stdlib's testing.M.