ztest

package
v0.0.0-...-d785515 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: MIT Imports: 17 Imported by: 1

Documentation

Overview

Package ztest contains helper functions that are useful for writing tests.

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultHost        = "example.com"
	DefaultContentType = "application/json"
)

Default values for NewRequest()

Functions

func Body

func Body(a any) *bytes.Reader

Body returns the JSON representation as an io.Reader. This is useful for creating a request body. For example:

NewRequest("POST", "/", ztest.Body(someStruct{
    Foo: "bar",
}))

func Code

func Code(t *testing.T, recorder *httptest.ResponseRecorder, want int)

Code checks if the error code in the recoder matches the desired one, and will stop the test with t.Fatal() if it doesn't.

func Diff

func Diff(have, want string, opt ...DiffOpt) string

Diff two strings and format as a unified diff.

func DiffMatch

func DiffMatch(have, want string, opt ...DiffOpt) string

DiffMatch formats a unified diff, but accepts various patterns in the want string:

%(YEAR)      current year in UTC
%(MONTH)     current month in UTC
%(DAY)       current day in UTC
%(UUID)      UUID format (any version).

%(ANY)       any text: .+?
%(ANY 5)     any text of exactly 5 characters: .{5}?
%(ANY 5,)    any text of at least 5 characters: .{5,}?
%(ANY 5,10)  any text between 5 and 10 characters: .{5,10}?
%(ANY 10)    any text at most 10 characters: .{,10}?
%(NUMBER)    any number; also allows length like ANY.

%(..)        any regular expression, but \ is not allowed.

func ErrorContains

func ErrorContains(have error, want string) bool

ErrorContains checks if the error message in have contains the text in want.

This is safe when have is nil. Use an empty string for want if you want to test that err is nil.

func HTTP

HTTP sets up a HTTP test. A GET request will be made if r is nil.

For example:

rr := ztest.HTTP(t, nil, MyHandler)

Or for a POST request:

r, err := zhttp.NewRequest("POST", "/v1/email", nil)
if err != nil {
    t.Fatal(err)
}
rr := ztest.HTTP(t, r, MyHandler)

func MultipartForm

func MultipartForm(params ...map[string]string) (b *bytes.Buffer, contentType string, err error)

MultipartForm writes the keys and values from params to a multipart form.

The first input parameter is used for "multipart/form-data" key/value strings, the optional second parameter is used creating file parts.

Don't forget to set the Content-Type from the return value:

r.Header.Set("Content-Type", contentType)

func MustInline

func MustInline(t *testing.T, pkg string, funs ...string)

MustInline issues a t.Error() if the Go compiler doesn't report that this function can be inlined.

The first argument must the the full package name (i.e. "zgo.at/zstd/zint"), and the rest are function names to test:

ParseUint128         Regular function
Uint128.IsZero       Method call
(*Uint128).Parse     Pointer method

The results are cached, so running it multiple times is fine.

Inspired by the test in cmd/compile/internal/gc/inl_test.go

func NewRequest

func NewRequest(method, target string, body io.Reader) *http.Request

NewRequest creates a new request with some sensible defaults set.

func NormalizeIndent

func NormalizeIndent(in string) string

NormalizeIndent removes tab indentation from every line.

This is useful for "inline" multiline strings:

  cases := []struct {
      string in
  }{
      `
	 	    Hello,
	 	    world!
      `,
  }

This is nice and readable, but the downside is that every line will now have two extra tabs. This will remove those two tabs from every line.

The amount of tabs to remove is based only on the first line, any further tabs will be preserved.

func Parallel

func Parallel[TT any](t *testing.T, tt TT) TT

Parallel signals that this test is to be run in parallel.

This is identical to testing.T.Parallel() but also returns the table test to capture it in the loop:

tests := []struct {
   ...
}

for _, tt := range tests {
   t.Run("", func(t *testing.T) {
     tt := ztest.Parallel(t, tt)
   })
}

Just saves one line vs.

t.Run("", func(t *testing.T) {
  tt := tt
  t.Parallel()
})

func R

func R(t *testing.T)

R recovers a panic and cals t.Fatal().

This is useful especially in subtests when you want to run a top-level defer. Subtests are run in their own goroutine, so those aren't called on regular panics. For example:

func TestX(t *testing.T) {
    clean := someSetup()
    defer clean()

    t.Run("sub", func(t *testing.T) {
        panic("oh noes")
    })
}

The defer is never called here. To fix it, call this function in all subtests:

t.Run("sub", func(t *testing.T) {
    defer test.R(t)
    panic("oh noes")
})

See: https://github.com/golang/go/issues/20394

func Read

func Read(t *testing.T, paths ...string) []byte

Read data from a file.

func Replace

func Replace(s string, patt ...string) string

Replace pieces of text with a placeholder string.

This is use to test output which isn't stable, for example because it contains times:

ztest.Replace("Time: 1161 seconds", `Time: (\d+) s`)

Will result in "Time: AAAA seconds".

The number of replacement characters is equal to the input, unless the pattern contains "+" or "*" in which case it's always replaced by three characters.

func TempFile

func TempFile(t *testing.T, name, data string) string

TempFile creates a new temporary file and returns the path.

The name is the filename to use; a "*" will be replaced with a random string, if it doesn't then it will create a file with exactly that name. If name is empty then it will use "ztest.*".

The file will be removed when the test ends.

func TempFiles

func TempFiles(t *testing.T, nameData ...string) string

TempFiles creates multiple temporary files in the same directory.

The return value is the temporary directory name.

Example:

TempFiles(t, "go.mod", "module test", "name1*.go", "package test")

Types

type DiffOpt

type DiffOpt int
const (
	// Normalize whitespace: remove all whitespace at the start and end of every
	// line.
	DiffNormalizeWhitespace DiffOpt = iota + 1

	// Treat arguments as JSON: format them before diffing.
	DiffJSON

	// Treat arguments as XML: format them before diffing.
	DiffXML
)

Directories

Path Synopsis
Package fakeconn provides a "fake" net.Conn implementation.
Package fakeconn provides a "fake" net.Conn implementation.
Package image contains helpers for testing image-related code.
Package image contains helpers for testing image-related code.

Jump to

Keyboard shortcuts

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