package ztest
import "zgo.at/zstd/ztest"
Package ztest contains helper functions that are useful for writing tests.
Index ¶
- Variables
- func Body(a any) *bytes.Reader
- func Code(t *testing.T, recorder *httptest.ResponseRecorder, want int)
- func Diff(have, want string, opt ...DiffOpt) string
- func DiffMatch(have, want string, opt ...DiffOpt) string
- func ErrorContains(have error, want string) bool
- func HTTP(t *testing.T, r *http.Request, h http.Handler) *httptest.ResponseRecorder
- func MultipartForm(params ...map[string]string) (b *bytes.Buffer, contentType string, err error)
- func MustInline(t *testing.T, pkg string, funs ...string)
- func NewRequest(method, target string, body io.Reader) *http.Request
- func NormalizeIndent(in string) string
- func Parallel[TT any](t *testing.T, tt TT) TT
- func R(t *testing.T)
- func Read(t *testing.T, paths ...string) []byte
- func Replace(s string, patt ...string) string
- func TempFile(t *testing.T, name, data string) string
- func TempFiles(t *testing.T, nameData ...string) string
- type DiffOpt
Variables ¶
var ( DefaultHost = "example.com" DefaultContentType = "application/json" )
Default values for NewRequest()
Functions ¶
func Body ¶
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 ¶
Diff two strings and format as a unified diff.
func DiffMatch ¶
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 ¶
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 ¶
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 ¶
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 ¶
NewRequest creates a new request with some sensible defaults set.
func NormalizeIndent ¶
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 ¶
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 ¶
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 ¶
Read data from a file.
func Replace ¶
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 ¶
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 ¶
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 )
Source Files ¶
diff.go http.go ztest.go
Directories ¶
Path | Synopsis |
---|---|
ztest/fakeconn | Package fakeconn provides a "fake" net.Conn implementation. |
ztest/image | Package image contains helpers for testing image-related code. |
- Version
- v0.0.0-20240930202209-a63c3335042a (latest)
- Published
- Sep 30, 2024
- Platform
- linux/amd64
- Imports
- 17 packages
- Last checked
- 2 days ago –
Tools for package owners.