xtest

package module
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2020 License: Apache-2.0 Imports: 11 Imported by: 0

README

xtest

simple testing framework for go

example

package xtest_test

import (
	"errors"
	"github.com/pubgo/xtest"
	"github.com/smartystreets/assertions/should"
	"github.com/smartystreets/gunit"
	"testing"
	"time"
)

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

type xtestFixture struct {
	*gunit.Fixture
}

func (t *xtestFixture) TestTick() {
	fn := xtest.TestFuncWith(func(args ...interface{}) {
		i := 0
		for range xtest.Tick(args...) {
			i++
		}
		t.So(xtest.SliceOf(1, 10), should.Contain, i)
	})
	fn.In(10, -1)
	fn.In(time.Millisecond * 10)
	t.So(fn.Do(), should.Equal, nil)
}

func (t *xtestFixture) TestCount() {
	fn := xtest.TestFuncWith(func(n int) {
		i := 0
		for range xtest.Count(n) {
			i++
		}
		t.So(xtest.SliceOf(0, 10), should.Contain, i)
	})
	fn.In(10, -1)
	t.So(fn.Do(), should.Equal, nil)

}

func (t *xtestFixture) TestRangeString() {
	fn := xtest.TestFuncWith(func(min, max int) {
		defer func() {
			err := recover()
			if err == nil {
				return
			}

			switch err := err.(type) {
			case error:
				t.Println(err.Error())
				t.So(xtest.SliceOf("invalid argument to Intn", "runtime error: makeslice: len out of range"), should.Contain, err.Error())
			case string:
				t.So("invalid argument to Intn", should.Equal, err)
			default:
				panic(err)
			}
		}()

		dt := xtest.RangeString(min, max)
		t.Assert(len(dt) < max && len(dt) >= min)
	})
	fn.In(-10, 0, 10)
	fn.In(-10, 0, 10, 20)
	t.So(fn.Do(), should.Equal, nil)
}

func (t *xtestFixture) TestMockRegister() {
	fn := xtest.TestFuncWith(func(fns ...interface{}) {
		defer func() {
			err := recover()
			if err == nil {
				return
			}
			switch err := err.(type) {
			case error:
				t.So(xtest.SliceOf(xtest.ErrParamIsNil, xtest.ErrParamTypeNotFunc), should.Contain, err)
			default:
				panic(err)
			}
		}()

		xtest.MockRegister(fns...)
	})
	fn.In(
		nil,
		"hello",
		func() {},
	)
	t.So(fn.Do(), should.Equal, nil)
}

func (t *xtestFixture) TestFuncCost() {
	fn := xtest.TestFuncWith(func(fn func()) {
		defer func() {
			err := recover()
			if err == nil {
				return
			}
			t.So(err, should.HaveSameTypeAs, errors.New(""))
			err = err.(error)
			t.So(err, should.Equal, xtest.ErrParamIsNil)
		}()

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

func (t *xtestFixture) TestTry() {
	e := errors.New("error")
	fn := xtest.TestFuncWith(func(fn func()) {
		err := xtest.Try(fn)
		xtest.AssertErrs(err, nil, xtest.ErrParamIsNil, e)
		switch err {
		case xtest.ErrParamIsNil:
			t.So(fn, should.Equal, nil)
		}
	})
	fn.In(
		nil,
		func() {},
		func() { panic("error") },
	)
	t.So(fn.Do(), should.Equal, nil)
}

func (t *xtestFixture) TestTimeoutWith() {
	var err1 = errors.New("hello")
	fn := xtest.TestFuncWith(func(dur time.Duration, fn func())  {
		err := xtest.TimeoutWith(dur, fn)
		xtest.AssertErrs(err, nil, xtest.ErrParamIsNil, xtest.ErrFuncTimeout, xtest.ErrDurZero, err1)

		switch err {
		case xtest.ErrParamIsNil:
			t.So(fn, should.Equal, nil)
		case xtest.ErrFuncTimeout:
			t.So(xtest.CostWith(fn), should.BeGreaterThan, dur)
		case xtest.ErrDurZero:
			t.So(dur, should.BeLessThan, 0)
		}
	})
	fn.In(time.Duration(-1), time.Millisecond*10)
	fn.In(
		nil,
		func() {},
		func() {
			time.Sleep(time.Millisecond * 20)
		},
		func() {
			panic(err1)
		},
	)
	t.So(fn.Do(), should.Equal, nil)
}

Documentation

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")
)

Functions

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
	// contains filtered or unexported fields
}

func (*B) ReportAllocs added in v0.1.8

func (b *B) ReportAllocs()

ReportAllocs enables malloc statistics for this benchmark. It is equivalent to setting -test.benchmem, but it only affects the benchmark function that calls ReportAllocs.

func (*B) ResetTimer added in v0.1.8

func (b *B) ResetTimer()

ResetTimer zeroes the elapsed benchmark time and memory allocation counters and deletes user-reported metrics. It does not affect whether the timer is running.

func (*B) SetBytes added in v0.1.8

func (b *B) SetBytes(n int64)

SetBytes records the number of bytes processed in a single operation. If this is called, the benchmark will report ns/op and MB/s.

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.

type BenchmarkResult added in v0.1.8

type BenchmarkResult struct {
	N         int           // The number of iterations.
	T         time.Duration // The total time taken.
	Bytes     int64         // Bytes processed in one iteration.
	MemAllocs uint64        // The total number of memory allocations.
	MemBytes  uint64        // The total number of bytes allocated.

	// Extra records additional metrics reported by ReportMetric.
	Extra map[string]float64
}

BenchmarkResult contains the results of a benchmark run.

func Benchmark added in v0.1.8

func Benchmark(n int, f func(b *B)) BenchmarkResult

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 (BenchmarkResult) AllocedBytesPerOp added in v0.1.8

func (r BenchmarkResult) AllocedBytesPerOp() int64

AllocedBytesPerOp returns the "B/op" metric, which is calculated as r.MemBytes / r.N.

func (BenchmarkResult) AllocsPerOp added in v0.1.8

func (r BenchmarkResult) AllocsPerOp() int64

AllocsPerOp returns the "allocs/op" metric, which is calculated as r.MemAllocs / r.N.

func (BenchmarkResult) MemString added in v0.1.8

func (r BenchmarkResult) MemString() string

MemString returns r.AllocedBytesPerOp and r.AllocsPerOp in the same format as 'go test'.

func (BenchmarkResult) NsPerOp added in v0.1.8

func (r BenchmarkResult) NsPerOp() int64

NsPerOp returns the "ns/op" metric.

func (BenchmarkResult) String added in v0.1.8

func (r BenchmarkResult) String() string

String returns a summary of the benchmark results. It follows the benchmark result line format from https://golang.org/design/14313-benchmark-format, not including the benchmark name. Extra metrics override built-in metrics of the same name. String does not include allocs/op or B/op, since those are reported by MemString.

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