got

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2021 License: MIT Imports: 27 Imported by: 8

README

Overview

A dependency-free test framework for go projects. Examples:

Documentation

Overview

Example (Standlone)

It can even run without the Go test framework

package main

import (
	"fmt"

	"github.com/ysmood/got"
)

// It can even run without the Go test framework
func main() {
	tester := &T{}

	got.Each(tester, func(tt *T) t {
		return t{got.NewWith(tt, got.NoColor().NoDiff())}
	})

}

type t struct {
	got.G
}

func (t t) A() {
	t.Eq(1, 2)
}

func (t t) B() {
	t.Gt(1, 1)
}

// T is a an empty tester.
// You can config it to fit your specific requirements.
type T struct {
}

func (t *T) Run(name string, fn func(*T)) { fn(t) }

func (t *T) Logf(f string, args ...interface{}) { fmt.Printf(f+"\n", args...) }

func (t *T) Name() string { return "" }

func (t *T) Skipped() bool { return false }

func (t *T) Failed() bool { return false }

func (t *T) Helper() {}

func (t *T) Cleanup(func()) {}

func (t *T) SkipNow() {}

func (t *T) Fail() {}

func (t *T) FailNow() {}
Output:

1 ⦗not ==⦘ 2
1 ⦗not >⦘ 1

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultFlags added in v0.6.2

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 added in v0.0.3

func Each(t Testable, iteratee interface{}) (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 added in v0.8.7

func EnsureCoverage(path string, min float64) error

EnsureCoverage via report file generated from, for example:

go test -coverprofile=coverage.out

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

func Parallel added in v0.8.1

func Parallel() (n int)

Parallel config of "go test -parallel"

Types

type Assertions added in v0.4.1

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

Assertions helpers

func (Assertions) Count added in v0.8.4

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

Count asserts that the returned function will be called n times

func (Assertions) Desc added in v0.12.0

func (as Assertions) Desc(format string, args ...interface{}) Assertions

Desc returns a clone with the description for failure enabled

func (Assertions) E added in v0.4.1

func (as Assertions) E(args ...interface{})

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

func (Assertions) Eq added in v0.4.1

func (as Assertions) Eq(x, y interface{})

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 .

func (Assertions) Equal added in v0.4.1

func (as Assertions) Equal(x, y interface{})

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 added in v0.4.1

func (as Assertions) Err(args ...interface{})

Err asserts that the last item in args is error

func (Assertions) False added in v0.4.1

func (as Assertions) False(x bool)

False asserts that x is false.

func (Assertions) Gt added in v0.4.1

func (as Assertions) Gt(x, y interface{})

Gt asserts that x is greater than y.

func (Assertions) Gte added in v0.4.1

func (as Assertions) Gte(x, y interface{})

Gte asserts that x is greater than or equal to y.

func (Assertions) Has added in v0.4.1

func (as Assertions) Has(container, str string)

Has asserts that container contains str

func (Assertions) Is added in v0.4.1

func (as Assertions) Is(x, y interface{})

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 added in v0.4.1

func (as Assertions) Len(list interface{}, l int)

Len asserts that the length of list equals l

func (Assertions) Lt added in v0.4.1

func (as Assertions) Lt(x, y interface{})

Lt asserts that x is less than y.

func (Assertions) Lte added in v0.4.1

func (as Assertions) Lte(x, y interface{})

Lte asserts that x is less than or equal to b.

func (Assertions) Must added in v0.12.0

func (as Assertions) Must() Assertions

Must returns a clone with the FailNow enabled

func (Assertions) Neq added in v0.4.1

func (as Assertions) Neq(x, y interface{})

Neq asserts that x not equals y even when converted to the same type.

func (Assertions) Nil added in v0.4.1

func (as Assertions) Nil(args ...interface{})

Nil asserts that the last item in args is nil

func (Assertions) NotNil added in v0.4.1

func (as Assertions) NotNil(args ...interface{})

NotNil asserts that the last item in args is not nil

func (Assertions) NotZero added in v0.15.0

func (as Assertions) NotZero(x interface{})

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

func (Assertions) Panic added in v0.4.1

func (as Assertions) Panic(fn func())

Panic executes fn and asserts that fn panics

func (Assertions) Regex added in v0.4.1

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

Regex asserts that str matches the regex pattern

func (Assertions) True added in v0.4.1

func (as Assertions) True(x bool)

True asserts that x is true.

func (Assertions) Zero added in v0.15.0

func (as Assertions) Zero(x interface{})

Zero asserts x is zero value for its type.

type Context added in v0.3.3

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

Context helper

type G added in v0.2.0

type G struct {
	Testable
	Assertions
	Utils
}

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

func New added in v0.0.3

func New(t Testable) G

New G instance. It will respect https://no-color.org/

func NewWith added in v0.1.0

func NewWith(t Testable, opts Options) G

NewWith G with options

type Only added in v0.1.2

type Only struct{}

Only run tests with it

type Options added in v0.1.0

type Options struct {
	// Dump a value to human readable string
	Dump func(interface{}) string

	// Format keywords in the assertion message.
	// Such as color it for CLI output.
	Keyword func(string) string

	// Diff function for Assertions.Eq
	Diff func(a, b interface{}) string
}

Options for Assertion

func Defaults added in v0.1.0

func Defaults() Options

Defaults for Options

func NoColor added in v0.14.0

func NoColor() Options

NoColor defaults for Options

func (Options) NoDiff added in v0.14.0

func (opts Options) NoDiff() Options

NoDiff returns a clone with diff output disabled.

type ReqMIME added in v0.11.0

type ReqMIME string

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

type ResHelper added in v0.2.0

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

ResHelper of the request

func (*ResHelper) Bytes added in v0.2.0

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

Bytes body

func (*ResHelper) JSON added in v0.2.0

func (res *ResHelper) JSON() (v interface{})

JSON body

func (*ResHelper) String added in v0.2.0

func (res *ResHelper) String() string

String body

type Router added in v0.2.0

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 added in v0.2.0

func (rt *Router) Route(pattern, file string, value ...interface{}) *Router

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

func (*Router) URL added in v0.2.0

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

URL will prefix the path with the server's host

type Skip added in v0.1.2

type Skip struct{}

Skip the current test

type Testable added in v0.0.3

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 ...interface{}) // same as testing.common.Logf
	SkipNow()                                // same as testing.common.Skip
}

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

type Utils added in v0.4.2

type Utils struct {
	Testable
}

Utils for commonly used methods

func (Utils) Context added in v0.4.2

func (ut Utils) Context() Context

Context that will be canceled after the test

func (Utils) DoAfter added in v0.8.2

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

DoAfter d duration if the test is still running

func (Utils) Error added in v0.4.2

func (ut Utils) Error(args ...interface{})

Error is the same as testing.common.Error

func (Utils) Errorf added in v0.4.2

func (ut Utils) Errorf(format string, args ...interface{})

Errorf is the same as testing.common.Errorf

func (Utils) Fatal added in v0.4.2

func (ut Utils) Fatal(args ...interface{})

Fatal is the same as testing.common.Fatal

func (Utils) Fatalf added in v0.4.2

func (ut Utils) Fatalf(format string, args ...interface{})

Fatalf is the same as testing.common.Fatalf

func (Utils) HandleHTTP added in v0.4.2

func (ut Utils) HandleHTTP(file string, value ...interface{}) 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 G.Write(value) and used as the response body.

func (Utils) JSON added in v0.4.2

func (ut Utils) JSON(src interface{}) (v interface{})

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

func (Utils) Log added in v0.4.2

func (ut Utils) Log(args ...interface{})

Log is the same as testing.common.Log

func (Utils) Open added in v0.4.2

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. path will be joined with filepath.Join so that it's cross-platform

func (Utils) PanicAfter added in v0.7.0

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

PanicAfter d duration if the test is still running

func (Utils) Parallel added in v0.4.2

func (ut Utils) Parallel() Utils

Parallel is the same as testing.T.Parallel

func (Utils) Read added in v0.4.2

func (ut Utils) Read(r io.Reader) *bytes.Buffer

Read all from r

func (Utils) Req added in v0.4.2

func (ut Utils) Req(method, url string, options ...interface{}) *ResHelper

Req the url. 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 Utils.ReqMIME, it will be used to set the Content-Type header. Other option type will be treat as request body, it will be encoded by Utils.Write .

func (Utils) Run added in v0.12.0

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

Run f as a subtest

func (Utils) Serve added in v0.4.2

func (ut Utils) Serve() *Router

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

func (Utils) Skip added in v0.4.2

func (ut Utils) Skip(args ...interface{})

Skip is the same as testing.common.Skip

func (Utils) Skipf added in v0.4.2

func (ut Utils) Skipf(format string, args ...interface{})

Skipf is the same as testing.common.Skipf

func (Utils) Srand added in v0.4.2

func (ut Utils) Srand(l int) string

Srand generates a random string with the specified length

func (Utils) Timeout added in v0.4.2

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

Timeout context that will be canceled after the test

func (Utils) ToJSON added in v0.10.0

func (ut Utils) ToJSON(obj interface{}) *bytes.Buffer

ToJSON convert obj to JSON bytes

func (Utils) ToJSONString added in v0.10.0

func (ut Utils) ToJSONString(obj interface{}) string

ToJSONString convert obj to JSON string

func (Utils) Write added in v0.4.2

func (ut Utils) Write(obj interface{}) (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.

Directories

Path Synopsis
cmd
fixtures
lib
gop
benchmark Module
example Module

Jump to

Keyboard shortcuts

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