got

package
v0.0.27 Latest Latest
Warning

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

Go to latest
Published: May 7, 2026 License: MIT, MIT Imports: 32 Imported by: 0

README

Overview

An enjoyable golang test framework.

Features

  • Pretty output using gop and diff
  • Fluent API design that takes the full advantage of IDE
  • Handy assertion helpers
  • Handy utils for testing
  • Value snapshot assertion
  • Customizable assertion error output

Guides

Read the example project to get started.

Got uses itself as the test framework, so the source code itself is the best doc.

Install the vscode extension for snippets like: gp, gt, and gsetup.

To ensure test coverage of your project, you can run the command below:

go test -race -coverprofile=coverage.out ./...
go run github.com/runZeroInc/go-rod/pkg/got/cmd/check-cov@latest

By default the check-cov requires 100% coverage, run it with the -h flag to see the help doc.

API reference

Link

Documentation

Overview

Package got is an enjoyable golang test framework.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultFlags

func DefaultFlags(flags ...string)

DefaultFlags will set the "go test" flag if not yet presented. It must be executed in the init() function. Such as the timeout:

DefaultFlags("timeout=10s")

func Each

func Each(t Testable, iteratee any) (count int)

Each runs each exported method Fn on type Ctx as a subtest of t. The iteratee can be a struct Ctx or:

iteratee(t Testable) (ctx Ctx)

Each Fn will be called like:

ctx.Fn()

If iteratee is Ctx, its G field will be set to New(t) for each test. Any Fn that has the same name with the embedded one will be ignored.

func EnsureCoverage

func EnsureCoverage(path string, min float64) error

EnsureCoverage via report file generated from, for example:

go test -coverprofile=coverage.out

Return error if any file's coverage is less than min, min is a percentage value.

func Parallel

func Parallel() (n int)

Parallel config of "go test -parallel"

func Setup

func Setup(init func(g G)) func(t Testable) G

Setup returns a helper to init G instance

Types

type AssertionCtx

type AssertionCtx struct {
	Type    AssertionErrType
	Details []any
	File    string
	Line    int
}

AssertionCtx holds the context of an assertion

type AssertionErrType

type AssertionErrType int

AssertionErrType enum

const (
	// AssertionEq type
	AssertionEq AssertionErrType = iota
	// AssertionNeqSame type
	AssertionNeqSame
	// AssertionNeq type
	AssertionNeq
	// AssertionGt type
	AssertionGt
	// AssertionGte type
	AssertionGte
	// AssertionLt type
	AssertionLt
	// AssertionLte type
	AssertionLte
	// AssertionInDelta type
	AssertionInDelta
	// AssertionTrue type
	AssertionTrue
	// AssertionFalse type
	AssertionFalse
	// AssertionNil type
	AssertionNil
	// AssertionNoArgs type
	AssertionNoArgs
	// AssertionNotNil type
	AssertionNotNil
	// AssertionNotNilable type
	AssertionNotNilable
	// AssertionNotNilableNil type
	AssertionNotNilableNil
	// AssertionZero type
	AssertionZero
	// AssertionNotZero type
	AssertionNotZero
	// AssertionRegex type
	AssertionRegex
	// AssertionHas type
	AssertionHas
	// AssertionLen type
	AssertionLen
	// AssertionErr type
	AssertionErr
	// AssertionPanic type
	AssertionPanic
	// AssertionIsInChain type
	AssertionIsInChain
	// AssertionIsKind type
	AssertionIsKind
	// AssertionCount type
	AssertionCount
	// AssertionSnapshot type
	AssertionSnapshot
)

type AssertionError

type AssertionError interface {
	Report(*AssertionCtx) string
}

AssertionError handler

func NewDefaultAssertionError

func NewDefaultAssertionError(theme gop.Theme, diffTheme diff.Theme) AssertionError

NewDefaultAssertionError handler

type AssertionErrorReport

type AssertionErrorReport func(*AssertionCtx) string

AssertionErrorReport is used to convert a func to AssertionError

func (AssertionErrorReport) Report

func (ae AssertionErrorReport) Report(ac *AssertionCtx) string

Report interface

type Assertions

type Assertions struct {
	Testable

	ErrorHandler AssertionError
	// contains filtered or unexported fields
}

Assertions helpers

func (Assertions) Count

func (as Assertions) Count(n int) func()

Count asserts that the returned function will be called n times

func (Assertions) Desc

func (as Assertions) Desc(format string, args ...any) Assertions

Desc returns a clone with the format description. The description will be printed before the error message.

func (Assertions) E

func (as Assertions) E(args ...any)

E is a shortcut for Must().Nil(args...)

func (Assertions) Eq

func (as Assertions) Eq(x, y any)

Eq asserts that x equals y when converted to the same type, such as compare float 1.0 and integer 1 . For strict value and type comparison use Assertions.Equal . For how comparison works, see utils.SmartCompare .

func (Assertions) Equal

func (as Assertions) Equal(x, y any)

Equal asserts that x equals y. For loose type comparison use Assertions.Eq, such as compare float 1.0 and integer 1 .

func (Assertions) Err

func (as Assertions) Err(args ...any)

Err asserts that the last item in args is error

func (Assertions) False

func (as Assertions) False(x bool)

False asserts that x is false.

func (Assertions) Gt

func (as Assertions) Gt(x, y any)

Gt asserts that x is greater than y. For how comparison works, see utils.SmartCompare .

func (Assertions) Gte

func (as Assertions) Gte(x, y any)

Gte asserts that x is greater than or equal to y. For how comparison works, see utils.SmartCompare .

func (Assertions) Has

func (as Assertions) Has(container, item any)

Has asserts that container has item. The container can be a string, []byte, slice, array, or map. For how comparison works, see utils.SmartCompare .

func (Assertions) InDelta

func (as Assertions) InDelta(x, y any, delta float64)

InDelta asserts that x and y are within the delta of each other. For how comparison works, see utils.SmartCompare .

func (Assertions) Is

func (as Assertions) Is(x, y any)

Is asserts that x is kind of y, it uses reflect.Kind to compare. If x and y are both error type, it will use errors.Is to compare.

func (Assertions) Len

func (as Assertions) Len(list any, l int)

Len asserts that the length of list equals l

func (Assertions) Lt

func (as Assertions) Lt(x, y any)

Lt asserts that x is less than y. For how comparison works, see utils.SmartCompare .

func (Assertions) Lte

func (as Assertions) Lte(x, y any)

Lte asserts that x is less than or equal to b. For how comparison works, see utils.SmartCompare .

func (Assertions) Must

func (as Assertions) Must() Assertions

Must returns a clone with the FailNow enabled. It will exit the current goroutine if the assertion fails.

func (Assertions) Neq

func (as Assertions) Neq(x, y any)

Neq asserts that x not equals y even when converted to the same type. For how comparison works, see utils.SmartCompare .

func (Assertions) Nil

func (as Assertions) Nil(args ...any)

Nil asserts that the last item in args is nilable and nil

func (Assertions) NotNil

func (as Assertions) NotNil(args ...any)

NotNil asserts that the last item in args is nilable and not nil

func (Assertions) NotZero

func (as Assertions) NotZero(x any)

NotZero asserts that x is not zero value for its type.

func (Assertions) Panic

func (as Assertions) Panic(fn func()) (val any)

Panic executes fn and asserts that fn panics

func (Assertions) Regex

func (as Assertions) Regex(pattern, str string)

Regex asserts that str matches the regex pattern

func (Assertions) True

func (as Assertions) True(x bool)

True asserts that x is true.

func (Assertions) Zero

func (as Assertions) Zero(x any)

Zero asserts x is zero value for its type.

type Context

type Context struct {
	context.Context
	Cancel func()
}

Context helper

type G

type G struct {
	Testable
	Assertions
	Utils
	// contains filtered or unexported fields
}

G is the helper context, it provides some handy helpers for testing

func New

func New(t Testable) G

New G instance

func T

func T(t Testable) G

T is the shortcut for New

func (G) Snapshot

func (g G) Snapshot(name string, x any)

Snapshot asserts that x equals the snapshot with the specified name, name should be unique under the same test case. It will create a new snapshot file if the name is not found. The snapshot file will be saved to ".got/snapshots/{TEST_NAME}". To update the snapshot, just change the name of the snapshot or remove the corresponding snapshot file. It will auto-remove the unused snapshot files after the test. The snapshot files should be version controlled. The format of the snapshot file is json.

type Only

type Only struct{}

Only run tests with it

type ReqMIME

type ReqMIME string

ReqMIME option type, it should be like ".json", "test.json", "a/b/c.jpg", etc

type ResHelper

type ResHelper struct {
	*http.Response
	// contains filtered or unexported fields
}

ResHelper of the request

func (*ResHelper) Bytes

func (res *ResHelper) Bytes() *bytes.Buffer

Bytes parses body as *bytes.Buffer and returns the result

func (*ResHelper) Err

func (res *ResHelper) Err() error

Err of request protocol

func (*ResHelper) JSON

func (res *ResHelper) JSON() (v any)

JSON parses body as json and returns the result

func (*ResHelper) String

func (res *ResHelper) String() string

String parses body as string and returns the result

func (*ResHelper) Unmarshal

func (res *ResHelper) Unmarshal(v any)

Unmarshal body to v as json, it's like json.Unmarshal.

type Router

type Router struct {
	HostURL *url.URL
	Server  *http.Server
	Mux     *http.ServeMux
	// contains filtered or unexported fields
}

Router of a http server

func (*Router) Route

func (rt *Router) Route(pattern, file string, value ...any) *Router

Route on the pattern. Check the doc of http.ServeMux for the syntax of pattern. It will use Utils.HandleHTTP to handle each request.

func (*Router) URL

func (rt *Router) URL(path ...string) string

URL will prefix the path with the server's host

type Skip

type Skip struct{}

Skip the current test

type Testable

type Testable interface {
	Name() string                    // same as testing.common.Name
	Skipped() bool                   // same as testing.common.Skipped
	Failed() bool                    // same as testing.common.Failed
	Cleanup(func())                  // same as testing.common.Cleanup
	FailNow()                        // same as testing.common.FailNow
	Fail()                           // same as testing.common.Fail
	Helper()                         // same as testing.common.Helper
	Logf(format string, args ...any) // same as testing.common.Logf
	SkipNow()                        // same as testing.common.Skip
}

Testable interface. Usually, you use *testing.T as it.

type Utils

type Utils struct {
	Testable
}

Utils for commonly used methods

func (Utils) Chdir

func (ut Utils) Chdir(dir string)

Chdir is like os.Chdir but will restore the dir after test.

func (Utils) Context

func (ut Utils) Context() Context

Context that will be canceled after the test

func (Utils) DoAfter

func (ut Utils) DoAfter(d time.Duration, do func()) (cancel func())

DoAfter d duration if the test is still running

func (Utils) Error

func (ut Utils) Error(args ...any)

Error is the same as [testing.common.Error]

func (Utils) Errorf

func (ut Utils) Errorf(format string, args ...any)

Errorf is the same as [testing.common.Errorf]

func (Utils) Fatal

func (ut Utils) Fatal(args ...any)

Fatal is the same as [testing.common.Fatal]

func (Utils) Fatalf

func (ut Utils) Fatalf(format string, args ...any)

Fatalf is the same as [testing.common.Fatalf]

func (Utils) Go

func (ut Utils) Go(f func())

Go runs f in a goroutine and wait for it to finish before the test ends.

func (Utils) HandleHTTP

func (ut Utils) HandleHTTP(file string, value ...any) func(http.ResponseWriter, *http.Request)

HandleHTTP handles a request. If file exists serve the file content. The file will be used to set the Content-Type header. If the file doesn't exist, the value will be encoded by Utils.Write and used as the response body.

func (Utils) JSON

func (ut Utils) JSON(src any) (v any)

JSON from string, []byte, or io.Reader

func (Utils) Log

func (ut Utils) Log(args ...any)

Log is the same as [testing.common.Log]

func (Utils) MkdirAll

func (ut Utils) MkdirAll(perm fs.FileMode, path string)

MkdirAll is like os.MkdirAll but will remove the dir after test and fail the test if error. The default perm is 0755.

func (Utils) Open

func (ut Utils) Open(create bool, path string) (f *os.File)

Open a file. Override it if create is true. Directories will be auto-created. If the directory and file doesn't exist, it will be removed after the test.

func (Utils) PanicAfter

func (ut Utils) PanicAfter(d time.Duration) (cancel func())

PanicAfter d duration if the test is still running

func (Utils) Parallel

func (ut Utils) Parallel() Utils

Parallel is the same as testing.T.Parallel

func (Utils) PathExists

func (ut Utils) PathExists(path string) bool

PathExists checks if path exists

func (Utils) RandBytes

func (ut Utils) RandBytes(l int) []byte

RandBytes generates a random byte array with the specified length

func (Utils) RandInt

func (ut Utils) RandInt(min, max int) int

RandInt generates a random integer within [min, max)

func (Utils) RandStr

func (ut Utils) RandStr(l int) string

RandStr generates a random string with the specified length

func (Utils) Read

func (ut Utils) Read(value any) *bytes.Buffer

Read all from value. If the value is string and it's a file path, the file content will be read, or the string will be returned. If the value is io.Reader, the reader will be read. If the value is []byte, the value will be returned. Others will be converted to string and returned.

func (Utils) Render

func (ut Utils) Render(value any, data any) *bytes.Buffer

Render template. It will use Utils.Read to read the value as the template string.

func (Utils) Req

func (ut Utils) Req(method, url string, options ...any) *ResHelper

Req is a helper method to send http request. It will handle errors automatically, so you don't need to check errors. The method is the http method, default value is "GET". If an option is http.Header, it will be used as the request header. If an option is ReqMIME, it will be used to set the Content-Type header. If an option is context.Context, it will be used as the request context. Other option type will be treat as request body, it will be encoded by Utils.Write. Some request examples:

Req("GET", "http://example.com")
Req("GET", "http://example.com", context.TODO())
Req("POST", "http://example.com", map[string]any{"a": 1})
Req("POST", "http://example.com", http.Header{"Host": "example.com"}, ReqMIME(".json"), map[string]any{"a": 1})

func (Utils) Run

func (ut Utils) Run(name string, f func(t G)) bool

Run f as a sub-test

func (Utils) Serve

func (ut Utils) Serve() *Router

Serve http on a random port. The server will be auto-closed after the test.

func (Utils) ServeWith

func (ut Utils) ServeWith(network, address string) *Router

ServeWith specified network and address

func (Utils) Setenv

func (ut Utils) Setenv(key, value string)

Setenv is like os.Setenv but will restore the env after test.

func (Utils) Skip

func (ut Utils) Skip(args ...any)

Skip is the same as [testing.common.Skip]

func (Utils) Skipf

func (ut Utils) Skipf(format string, args ...any)

Skipf is the same as [testing.common.Skipf]

func (Utils) Timeout

func (ut Utils) Timeout(d time.Duration) Context

Timeout context that will be canceled after the test

func (Utils) ToJSON

func (ut Utils) ToJSON(obj any) *bytes.Buffer

ToJSON convert obj to JSON bytes

func (Utils) ToJSONString

func (ut Utils) ToJSONString(obj any) string

ToJSONString convert obj to JSON string

func (Utils) Write

func (ut Utils) Write(obj any) (writer func(io.Writer))

Write obj to the writer. Encode obj to []byte and cache it for writer. If obj is not []byte, string, or io.Reader, it will be encoded as JSON.

func (Utils) WriteFile

func (ut Utils) WriteFile(path string, content any)

WriteFile at path with content, it uses Utils.Open to open the file.

Directories

Path Synopsis
cmd
check-cov command
Package main ...
Package main ...
fixtures
coverage
Package coverage ...
Package coverage ...
lib
diff
Package diff ...
Package diff ...
got-vscode-extension/snippets command
Package main ...
Package main ...
lcs
Package lcs ...
Package lcs ...
mock
Package mock provides a simple way to stub struct methods.
Package mock provides a simple way to stub struct methods.
utils
Package utils ...
Package utils ...

Jump to

Keyboard shortcuts

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