testkit

package module
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2022 License: BSD-2-Clause Imports: 22 Imported by: 0

README

Test Kit

Go Report Card PkgGoDev

Package testkit provides all sorts of test helpers which take *testing.T instance and report errors if something goes wrong. See GoDoc for the documentation and examples.

Motivation

In my opinion constantly checking errors while setting up a test reduces its readability.

Example test:

func Test_MyFunction(t *testing.T) {
	// --- Given ---
	fil, err := ioutil.TempFile(t.TempDir(), "test_*.txt")
	if err != nil {
		t.Fatal(err)
	}
	defer fil.Close()

	content := []byte("line1\nline2\nend")
	if _, err := fil.Write(content); err != nil {
		t.Fatal(err)
	}

	// --- When ---

	// Do some operations on the test file.

	// --- Then ---
	chk, err := os.Open(fil.Name())
	if err != nil {
		t.Fatal(err)
	}

	got, err := ioutil.ReadAll(chk)
	if err != nil {
		t.Fatal(err)
	}

	expected := []byte{0, 1, 2, 3}
	if !bytes.Equal(expected, got) {
		t.Errorf("expected %v got %v", expected, got)
	}
}

The same test using testkit:


import (
    kit "github.com/rzajac/testkit"
)

func Test_MyFunction(t *testing.T) {
	// --- Given ---
	content := []byte("line1\nline2\nend")
	pth := kit.TempFileBuf(t, t.TempDir(), content)

	// --- When ---

	// Do some operations on the test file.

	// --- Then ---
	got := kit.ReadFile(t, pth)
	expected := []byte{0, 1, 2, 3}
	if !bytes.Equal(expected, got) {
		t.Errorf("expected %v got %v", expected, got)
	}
}

TempFileBuf creates and writes to temporary file from a buffer. Returns path to created file. It registers cleanup function with t removing the created file. Calls t.Fatal() on error. Similarly ReadFile is a wrapper around ioutil.ReadFile() which calls t.Fatal() on error.

License

BSD-2-Clause

Documentation

Overview

Package testkit provides all sorts of test helpers.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrTestError = errors.New("testkit test error")

ErrTestError is general error used in tests,it is returned by some helpers.

Functions

func AbsPath

func AbsPath(t T, pth string) string

AbsPath is a wrapper around filepath.Abs() which calls t.Fatal() on error.

func AssertErrPrefix

func AssertErrPrefix(t T, err error, prefix string)

AssertErrPrefix asserts error message has prefix.

func CloneHTTPRequest

func CloneHTTPRequest(t T, req *http.Request) *http.Request

CloneHTTPRequest clones HTTP request and body, URL.Host and URL.Scheme. Calls t.Fatal() on error.

func CreateDir

func CreateDir(t T, name string) string

CreateDir creates directory with name returns passed name, so it can be used in place.

MyFunction(CreateDir(t, "name"))

Calls t.Fatal() on error.

func CreateFile

func CreateFile(t T, name string) *os.File

CreateFile is a wrapper around os.Create() which calls t.Fatal() on error.

func CurrOffset added in v0.6.0

func CurrOffset(t T, s io.Seeker) int64

CurrOffset returns the current offset of the seeker. Calls t.Fatal() on error.

func ErrReader

func ErrReader(r io.Reader, n int, err error) io.Reader

ErrReader wraps reader r. The returned reader reads at most n bytes and returns error err. The ErrTestError will be used if err is set to nil. Error other than err will be returned if underlying reader returns an error before n bytes are read.

Example
r := bytes.NewReader([]byte{0, 1, 2, 3})
er := ErrReader(r, 2, nil)

got, err := ioutil.ReadAll(er)

fmt.Println(got)
fmt.Println(err)
Output:

[0 1]
testkit test error

func ErrWriter

func ErrWriter(w io.Writer, n int, err error) io.Writer

ErrWriter wraps writer w in a writer which writes at most n bytes and returns error err. If err is set to nil then ErrTestError will be used. Error other than err will be returned if underlying writer returns an error before n bytes are written.

Example
dst := &bytes.Buffer{}
ew := ErrWriter(dst, 3, errors.New("my error"))

n, err := ew.Write([]byte{0, 1, 2})

fmt.Println(n)
fmt.Println(err)
fmt.Println(dst.Bytes())
Output:

3
my error
[0 1 2]

func FileSize

func FileSize(t T, fil *os.File) int64

FileSize returns file size. Calls t.Fatal() on error.

func FromJSON

func FromJSON(t T, data []byte, v interface{})

FromJSON is a wrapper around json.Unmarshal() which calls t.Fatal() on error.

func FromJSONReader

func FromJSONReader(t T, r io.Reader, v interface{})

FromJSONReader reads JSON from r and unmarshalls them to v. Calls t.Fatal() on error.

func FromXML added in v0.10.0

func FromXML(t T, data []byte, v interface{})

FromXML is a wrapper around xml.Unmarshal() which calls t.Fatal() on error.

func Getwd

func Getwd(t T) string

Getwd is a wrapper around os.Getwd() which calls t.Fatal() on error.

func HasNetConn

func HasNetConn() bool

HasNetConn returns true if the Internet connection is present.

func MD5File added in v0.5.0

func MD5File(t T, pth string) string

MD5File returns MD5 hash of the file. Calls t.Fatal() on error.

func MD5Reader added in v0.5.0

func MD5Reader(t T, r io.Reader) string

MD5Reader returns MD5 hash off everything in the reader. Calls t.Fatal() on error.

func ModTime

func ModTime(t T, name string) time.Time

ModTime calls os.Stat() and returns modification time. Calls t.Fatal() on error.

func NoNetworkSkip

func NoNetworkSkip(t T)

NoNetworkSkip skips test if there is no Internet connection.

func OpenFile

func OpenFile(t T, name string) *os.File

OpenFile is a wrapper around os.Open() which calls t.Fatal() on error.

func RandFileName

func RandFileName(dir, prefix, ext string) string

RandFileName returns random file name. If prefix is empty string it will be set to "file-". The extension wll be set to ".txt" if ext is empty string.

func RandStr

func RandStr(n int) string

RandStr returns random string of length n.

func ReadAll

func ReadAll(t T, r io.Reader) []byte

ReadAll is a wrapper around ioutil.ReadAll which calls t.Fatal() on error.

func ReadAllFromStart

func ReadAllFromStart(t T, rs io.ReadSeeker) []byte

ReadAllFromStart seeks to the beginning of rs and reads it till gets io.EOF or any other error. Then seeks back to the position where rs was before the call. Calls t.Fatal() on error.

func ReadAllString

func ReadAllString(t T, r io.Reader) string

ReadAllString is a wrapper around ioutil.ReadAll which returns string instead of byte slice. Calls t.Fatal() on error.

func ReadFile

func ReadFile(t T, filename string) []byte

ReadFile is a wrapper around ioutil.ReadFile() which calls t.Fatal() on error.

func Readdirnames

func Readdirnames(t T, fil *os.File) []string

Readdirnames returns slice returned by Readdirnames(0) called on fil instance. Calls t.Fatal() on error.

func RemoveFile added in v0.11.0

func RemoveFile(t T, pth string)

RemoveFile removes file or empty directory. Calls t.Fatal on error.

func ReplaceAllInFile

func ReplaceAllInFile(t T, filename, old, new string)

ReplaceAllInFile replaces all occurrences of old sting with new in the filename. Calls t.Fatal() on error.

func Seek added in v0.6.0

func Seek(t T, s io.Seeker, offset int64, whence int) int64

Seek sets the offset for the next Read or Write to offset, interpreted according to whence. Seek returns the new offset relative to the start of the s. Calls t.Fatal() on error.

func SetEnv added in v0.8.0

func SetEnv(t T, key, value string)

SetEnv sets environment variable key to value and registers cleanup function with t to set the environment variable to what it was.

func TempDir

func TempDir(t T, dir string, prefix string) string

TempDir is a wrapper around ioutil.TempDir() which calls t.Fatal() on error.

func TempFile

func TempFile(t T, dir, pattern string) *os.File

TempFile is a wrapper around ioutil.TempFile() which calls t.Fatal() on error. It registers cleanup function with t removing the created file.

func TempFileBuf added in v0.7.0

func TempFileBuf(t T, dir string, b []byte) string

TempFileBuf creates and writes to temporary file from buffer b. Returns path to created file. It registers cleanup function with t removing the created file. Calls t.Fatal() on error.

func TempFileRdr added in v0.7.0

func TempFileRdr(t T, dir string, r io.Reader) string

TempFileRdr creates and writes to temporary file from reader r. Returns path to created file. It registers cleanup function with t removing the created file. Calls t.Fatal() on error.

func ToJSON

func ToJSON(t T, v interface{}) []byte

ToJSON is a wrapper around json.Marshal() which calls t.Fatal() on error.

func ToJSONReader

func ToJSONReader(t T, v interface{}) io.Reader

ToJSONReader marshals v to JSON and returns io.Reader for it. Calls t.Fatal() on error.

func ToXML added in v0.10.0

func ToXML(t T, v interface{}) []byte

ToXML is a wrapper around xml.Marshal() which calls t.Fatal() on error.

func Wait

func Wait(max time.Duration, fn func() bool)

Wait waits till fn returns true but no longer then timeout max.

func WaitTh

func WaitTh(max, th time.Duration, fn func() bool)

WaitTh waits for fn to return true but no longer then timeout max. The calls to fn are throttled with th.

Types

type HTTPServer

type HTTPServer struct {
	// contains filtered or unexported fields
}

HTTPServer represents very simple HTTP server recording all the requests it receives, responding with responses added with Rsp() method.

The server instance provides methods to analyse the received requests.

func NewHTTPServer

func NewHTTPServer(t T) *HTTPServer

NewHTTPServer returns new instance of HTTPServer and registers call to Close in test cleanup. The server will fail the test if during cleanup the number of expected responses does not match the number of seen requests.

func (*HTTPServer) Body

func (tst *HTTPServer) Body(n int) []byte

Body returns body of the nth received request. Calls t.Fatal() if n is greater than number or received requests.

func (*HTTPServer) BodyString added in v0.14.0

func (tst *HTTPServer) BodyString(n int) string

BodyString returns body of the nth received request. Calls t.Fatal() if n is greater than number or received requests.

func (*HTTPServer) Close

func (tst *HTTPServer) Close() error

Close stops the test server and does cleanup. May be called multiple times.

func (*HTTPServer) Headers

func (tst *HTTPServer) Headers(n int) http.Header

Headers returns headers for given request index. Calls t.Fatal() if n is greater than number or received requests.

func (*HTTPServer) ReqCount

func (tst *HTTPServer) ReqCount() int

ReqCount returns number of requests recorded by test server.

func (*HTTPServer) Request

func (tst *HTTPServer) Request(n int) *http.Request

Request returns clone of the nth received request. Calls t.Fatal() if n is greater than number or received requests.

func (*HTTPServer) Rsp

func (tst *HTTPServer) Rsp(status int, rsp []byte) *HTTPServer

Rsp adds response with status and body to the list of responses to return.

Every time the server receives a request it returns predefined response. The responses are returned to the order they were added. The rsp can be set to nil in which case no response body will send. The t.Fatal() will be called if there are no more responses.

func (*HTTPServer) URL

func (tst *HTTPServer) URL() string

URL returns URL for the test server.

func (*HTTPServer) Values

func (tst *HTTPServer) Values(n int) url.Values

Values returns URL query values of the nth received request. Calls t.Fatal() if n is greater than number or received requests.

type T

type T interface {
	// Cleanup registers a function to be called when the test and all its
	// subtests complete. Cleanup functions will be called in last added,
	// first called order.
	Cleanup(func())

	// Error is equivalent to Log followed by Fail.
	Error(args ...interface{})

	// Errorf is equivalent to Logf followed by Fail.
	Errorf(format string, args ...interface{})

	// Fatal is equivalent to Log followed by FailNow.
	Fatal(args ...interface{})

	// Fatalf is equivalent to Logf followed by FailNow.
	Fatalf(format string, args ...interface{})

	// Helper marks the calling function as a test helper function.
	// When printing file and line information, that function will be skipped.
	// Helper may be called simultaneously from multiple goroutines.
	Helper()

	// Setenv calls os.Setenv(key, value) and uses Cleanup to
	// restore the environment variable to its original value
	// after the test.
	//
	// This cannot be used in parallel tests.
	Setenv(key, value string)

	// Skip is equivalent to Log followed by SkipNow.
	Skip(args ...interface{})

	// TempDir returns a temporary directory for the test to use.
	// The directory is automatically removed by Cleanup when the test and
	// all its subtests complete.
	// Each subsequent call to t.TempDir returns a unique directory;
	// if the directory creation fails, TempDir terminates the test by calling Fatal.
	TempDir() string

	// Log formats its arguments using default formatting, analogous to Println,
	// and records the text in the error log. For tests, the text will be printed only if
	// the test fails or the -test.v flag is set. For benchmarks, the text is always
	// printed to avoid having performance depend on the value of the -test.v flag.
	Log(args ...interface{})

	// Logf formats its arguments according to the format, analogous to Printf, and
	// records the text in the error log. A final newline is added if not provided. For
	// tests, the text will be printed only if the test fails or the -test.v flag is
	// set. For benchmarks, the text is always printed to avoid having performance
	// depend on the value of the -test.v flag.
	Logf(format string, args ...interface{})
}

T is a subset of testing.TB interface. It's primarily used to test the testkit package but can be used to implement custom actions to be taken on errors.

type TMock added in v0.12.0

type TMock struct {
	mock.Mock
}

TMock is an autogenerated mock type for the T type

func (*TMock) Cleanup added in v0.12.0

func (_m *TMock) Cleanup(_a0 func())

Cleanup provides a mock function with given fields: _a0

func (*TMock) Error added in v0.12.0

func (_m *TMock) Error(args ...interface{})

Error provides a mock function with given fields: args

func (*TMock) Errorf added in v0.12.0

func (_m *TMock) Errorf(format string, args ...interface{})

Errorf provides a mock function with given fields: format, args

func (*TMock) Fatal added in v0.12.0

func (_m *TMock) Fatal(args ...interface{})

Fatal provides a mock function with given fields: args

func (*TMock) Fatalf added in v0.12.0

func (_m *TMock) Fatalf(format string, args ...interface{})

Fatalf provides a mock function with given fields: format, args

func (*TMock) Helper added in v0.12.0

func (_m *TMock) Helper()

Helper provides a mock function with given fields:

func (*TMock) Log added in v0.16.0

func (_m *TMock) Log(args ...interface{})

Log provides a mock function with given fields: args

func (*TMock) Logf added in v0.17.0

func (_m *TMock) Logf(format string, args ...interface{})

Logf provides a mock function with given fields: format, args

func (*TMock) Setenv added in v0.12.0

func (_m *TMock) Setenv(key string, value string)

Setenv provides a mock function with given fields: key, value

func (*TMock) Skip added in v0.12.0

func (_m *TMock) Skip(args ...interface{})

Skip provides a mock function with given fields: args

func (*TMock) TempDir added in v0.12.0

func (_m *TMock) TempDir() string

TempDir provides a mock function with given fields:

Jump to

Keyboard shortcuts

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