xtest

package module
v0.1.12 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2020 License: Apache-2.0 Imports: 14 Imported by: 0

README

xtest

simple testing framework for go

example

package xtest

import (
	"errors"
	"fmt"
	"github.com/pubgo/xerror"
	"testing"
	"time"

	"github.com/smartystreets/assertions/should"
	. "github.com/smartystreets/goconvey/convey"
	"github.com/smartystreets/gunit"
)

func TestXTest(t *testing.T) {
	gunit.Run(new(xtestFixture), t, gunit.Options.AllSequential())
}

type xtestFixture struct {
	*gunit.Fixture
}

func (t *xtestFixture) TestTick() {

	fn := TestFuncWith(func(args ...interface{}) {
		defer xerror.RespExit()

		i := 0
		for range Tick(args...) {
			i++
		}
		t.So(SliceOf(1, 10), should.Contain, i)
	})
	fn.In(10, -1)
	fn.In(time.Millisecond * 10)
	fn.Do()
}

func (t *xtestFixture) TestCount() {
	fn := TestFuncWith(func(n int) {
		defer xerror.RespExit()

		i := 0
		for range Count(n) {
			i++
		}
		t.So(SliceOf(0, 10), should.Contain, i)
	})
	fn.In(10, -1)
	fn.Do()
}

func TestRangeString(t *testing.T) {
	Convey("RangeString", t, func() {
		fn := TestFuncWith(func(min, max int) {
			Convey(fmt.Sprint("min=", min, "  max=", max), func() {
				defer xerror.Resp(func(err xerror.XErr) {
					switch err.Error() {
					case "invalid argument to Intn", "runtime error: makeslice: len out of range":
						So(err, ShouldNotEqual, "")
					default:
						xerror.Exit(err)
					}
				})

				dt := RangeString(min, max)
				So(len(dt) < max && len(dt) >= min, ShouldBeTrue)
			})
		})
		fn.In(-10, 0, 10)
		fn.In(-10, 0, 10, 20)
		fn.Do()
	})
}

func (t *xtestFixture) TestFuncCost() {
	fn := TestFuncWith(func(fn func()) {
		defer xerror.Resp(func(err xerror.XErr) {
			switch err := err.Unwrap(); err {
			case ErrParamIsNil:
			default:
				xerror.Exit(err)
			}
		})

		t.So(SliceOf(time.Duration(1), time.Duration(0)), should.Contain, CostWith(fn)/time.Millisecond)
	})
	fn.In(
		nil,
		func() {},
		func() { time.Sleep(time.Millisecond) },
	)
	fn.Do()
}

func (t *xtestFixture) TestTry() {
	e := errors.New("error")
	fn := TestFuncWith(func(fn func()) {
		defer xerror.Resp(func(err xerror.XErr) {
			switch err.Unwrap() {
			case ErrParamIsNil:
				t.So(fn, ShouldBeNil)
			case e:
			default:
				xerror.Exit(err)
			}
		})
		xerror.Panic(Try(fn))
	})
	fn.In(
		nil,
		func() {},
		func() { panic(e) },
	)
	fn.Do()
}

func (t *xtestFixture) TestTimeoutWith() {
	var err1 = errors.New("hello")
	fn := TestFuncWith(func(dur time.Duration, fn func()) {
		defer xerror.Resp(func(err xerror.XErr) {
			switch err.Unwrap() {
			case ErrParamIsNil:
				t.So(fn, ShouldBeNil)
			case ErrFuncTimeout:
				t.So(CostWith(fn), should.BeGreaterThan, dur)
			case ErrDurZero:
				t.So(dur, should.BeLessThan, 0)
			case err1:
			default:
				xerror.Exit(err)
			}
		})

		xerror.Panic(TimeoutWith(dur, fn))

	})
	fn.In(time.Duration(-1), time.Millisecond*10)
	fn.In(
		nil,
		func() {},
		func() {
			time.Sleep(time.Millisecond * 20)
		},
		func() {
			panic(err1)
		},
	)
	fn.Do()
}

func TestTimeoutWith(t *testing.T) {
	var err1 = errors.New("hello")
	var err2 = "hello"
	Convey("TimeoutWith", t, func() {
		fn := TestFuncWith(func(dur time.Duration, fn func()) {
			Convey(fmt.Sprint("dur=", dur, "  fn=", FuncSprint(fn)), func() {
				defer xerror.Resp(func(err xerror.XErr) {
					switch err.Unwrap() {
					case ErrParamIsNil:
						So(fn, ShouldBeNil)
					case ErrFuncTimeout:
						So(CostWith(fn), should.BeGreaterThan, dur)
					case ErrDurZero:
						So(dur, should.BeLessThan, 0)
					case err1:
						So(nil, ShouldBeNil)
					default:
						if err.Error() == err2 {
							So(nil, ShouldBeNil)
							return
						}
						xerror.Exit(err)
					}
				})

				xerror.Panic(TimeoutWith(dur, fn))
			})
		})
		fn.In(time.Duration(-1), time.Millisecond*10)
		fn.In(
			nil,
			func() {},
			func() {
				time.Sleep(time.Millisecond * 20)
			},
			func() {
				panic(err1)
			},
			func() {
				panic(err2)
			},
		)
		fn.Do()
	})
}

Documentation

Overview

Package leaktest provides tools to detect leaked goroutines in tests. To use it, call "defer leaktest.Check(t)()" at the beginning of each test that may use goroutines. copied out of the cockroachdb source tree with slight modifications to be more re-useable

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrXTest                     = xerror.New("xtest error")
	ErrParamIsNil                = ErrXTest.New("the parameter is nil")
	ErrFuncTimeout               = ErrXTest.New("the func is timeout")
	ErrParamTypeNotFunc          = ErrXTest.New("the type of the parameters is not func")
	ErrDurZero                   = ErrXTest.New("the duration time must more than zero")
	ErrInputParamsNotMatch       = ErrXTest.New("the input params of func is not match")
	ErrInputOutputParamsNotMatch = ErrXTest.New("the input num and output num of the callback func is not match")
	ErrFuncOutputTypeNotMatch    = ErrXTest.New("the  output type of the callback func is not match")
	ErrForeachParameterNil       = ErrXTest.New("the parameter of [Foreach] must not be nil")
)
View Source
var TickerInterval = time.Millisecond * 50

TickerInterval defines the interval used by the ticker in Check* functions.

Functions

func Check

func Check(t ErrorReporter) func()

Check snapshots the currently-running goroutines and returns a function to be run at the end of tests to see whether any goroutines leaked, waiting up to 5 seconds in error conditions

func CheckContext added in v0.1.12

func CheckContext(ctx context.Context, t ErrorReporter) func()

CheckContext is the same as Check, but uses a context.Context for cancellation and timeout control

func CheckTimeout added in v0.1.12

func CheckTimeout(t ErrorReporter, dur time.Duration) func()

CheckTimeout is the same as Check, but with a configurable timeout

func CostWith

func CostWith(fn func()) (dur time.Duration)

func Count

func Count(n int) <-chan int

Count ...

func FuncSprint added in v0.1.2

func FuncSprint(args ...interface{}) string

func PrintMemStats added in v0.1.8

func PrintMemStats()

func Range

func Range(min, max int) int

Range ...

func RangeBytes

func RangeBytes(min, max int) []byte

RangeBytes ...

func RangeDur

func RangeDur(min, max time.Duration) time.Duration

RangeDur ...

func RangeString

func RangeString(min, max int) string

RangeString ...

func SliceOf

func SliceOf(args ...interface{}) []interface{}

func TestFuncWith

func TestFuncWith(fn interface{}) *xtest

func Tick

func Tick(args ...interface{}) <-chan time.Time

Tick 简单定时器 Example: Tick(100, time.Second)

func TimeoutWith

func TimeoutWith(dur time.Duration, fn func()) error

func Try

func Try(fn func()) (e error)

func Wrap

func Wrap(fn interface{}) func(...interface{}) func(...interface{}) (err error)

Types

type B added in v0.1.8

type B struct {
	N int
	M uint32

	T string
	// contains filtered or unexported fields
}

func Benchmark added in v0.1.8

func Benchmark(n int) *B

func BenchmarkParallel added in v0.1.12

func BenchmarkParallel(n int, m int) *B

Benchmark benchmarks a single function. It is useful for creating custom benchmarks that do not use the "go test" command.

If f depends on testing flags, then Init must be used to register those flags before calling Benchmark and before calling flag.Parse.

If f calls Run, the result will be an estimate of running all its subbenchmarks that don't call Run in sequence in a single benchmark.

func (*B) AllocBytes added in v0.1.12

func (b *B) AllocBytes() uint64

func (*B) CpuProfile added in v0.1.12

func (b *B) CpuProfile(file string) *B

func (*B) Do added in v0.1.12

func (b *B) Do(fn func(b *B)) *B

func (*B) MemProfile added in v0.1.12

func (b *B) MemProfile(file string) *B

func (*B) StartTimer added in v0.1.8

func (b *B) StartTimer()

StartTimer starts timing a test. This function is called automatically before a benchmark starts, but it can also be used to resume timing after a call to StopTimer.

func (*B) StopTimer added in v0.1.8

func (b *B) StopTimer()

StopTimer stops timing a test. This can be used to pause the timer while performing complex initialization that you don't want to measure.

func (*B) String added in v0.1.12

func (b *B) String() string

type ErrorReporter added in v0.1.12

type ErrorReporter interface {
	Errorf(format string, args ...interface{})
}

ErrorReporter is a tiny subset of a testing.TB to make testing not such a massive pain

Directories

Path Synopsis
cmd
internal
Package goparse contains logic for parsing Go files.
Package goparse contains logic for parsing Go files.

Jump to

Keyboard shortcuts

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