xtest

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2022 License: Apache-2.0 Imports: 22 Imported by: 0

README

xtest

simple testing framework for go

example

package xtest

import (
	"errors"
	"fmt"
	"testing"
	"time"

    "github.com/pubgo/xerror"
	"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

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrXTest                     = xerror.New("grpcTest 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 DefaultPrinter = NewPrinter(os.Stdout, WithIndent("  "))

Default prints to os.Stdout with two space indentation.

View Source
var TickerInterval = time.Millisecond * 50

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

Functions

func Debug added in v0.2.0

func Debug(vs ...interface{})

Debug writes a representation of v to os.Stdout, separated by spaces.

func DebugS added in v0.2.0

func DebugS(v interface{}, options ...Option) string

DebugS returns a string representing v.

func Debugln added in v0.2.0

func Debugln(vs ...interface{})

Debugln prints v to os.Stdout, one per line.

func Fail added in v0.2.0

func Fail(err error) error

func InErrs

func InErrs(d error, ds ...error) (b bool)

InErrs ...

func Leak added in v0.2.0

func Leak(t ErrorReporter) func()

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

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

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

func LeakWithTimeout added in v0.2.0

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

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

func MemStatsPrint added in v0.2.0

func MemStatsPrint()

func Mock

func Mock(args ...interface{})

Mock ...

func MockBytes added in v0.2.0

func MockBytes(min, max int) []byte

MockBytes ...

func MockCheck added in v0.2.0

func MockCheck(args ...bool)

MockCheck ...

func MockDur added in v0.2.0

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

MockDur ...

func MockInt added in v0.2.0

func MockInt(min, max int) int

MockInt ...

func MockRegister

func MockRegister(fns ...interface{})

MockRegister ...

func MockString added in v0.2.0

func MockString(min, max int) string

MockString ...

func Ok added in v0.2.0

func Ok(err error) error

func Rand added in v0.2.1

func Rand(data ...interface{}) interface{}

func RandS added in v0.2.1

func RandS(strList ...string) string

func Run added in v0.2.0

func Run(t *testing.T, tests ...Test)

Types

type B added in v0.1.8

type B interface {
	StartTimer()
	StopTimer()
}

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

type Fixture added in v0.2.0

type Fixture struct {
	RunNum uint
	// contains filtered or unexported fields
}

func (*Fixture) Failed added in v0.2.0

func (t *Fixture) Failed() bool

func (*Fixture) InitHandlerParam added in v0.2.0

func (t *Fixture) InitHandlerParam(name string, fn func() interface{})

func (*Fixture) So added in v0.2.0

func (t *Fixture) So(
	actual interface{},
	assert func(actual interface{}, expected ...interface{}) string,
	expected ...interface{}) bool

type IBenchmark added in v0.2.0

type IBenchmark interface {
	CpuProfile(file string) IBenchmark
	MemProfile(file string) IBenchmark
	Do(fn func(b B)) IBenchmark
	String() string
}

func Benchmark added in v0.1.8

func Benchmark(n int) IBenchmark

func BenchmarkParallel added in v0.1.12

func BenchmarkParallel(n int, m int) IBenchmark

BenchmarkParallel

type Option added in v0.1.13

type Option func(o *Printer)

An Option modifies the default behaviour of a Printer.

func AlwaysIncludeType added in v0.1.13

func AlwaysIncludeType() Option

AlwaysIncludeType always includes explicit type information for each item.

func WithHide added in v0.2.0

func WithHide(ts ...interface{}) Option

Hide excludes the given types from representation, instead just printing the name of the type.

func WithIgnoreGoStringer added in v0.2.0

func WithIgnoreGoStringer() Option

IgnoreGoStringer disables use of the .GoString() method.

func WithIndent added in v0.2.0

func WithIndent(indent string) Option

Indent output by this much.

func WithNoIndent added in v0.2.0

func WithNoIndent() Option

NoIndent disables indenting.

func WithOmitEmpty added in v0.2.0

func WithOmitEmpty(omitEmpty bool) Option

OmitEmpty sets whether empty field members should be omitted from output.

type Printer added in v0.1.13

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

Printer represents structs in a printable manner.

func NewPrinter added in v0.2.0

func NewPrinter(w io.Writer, options ...Option) *Printer

New creates a new Printer on w with the given Fixture.

func (*Printer) Print added in v0.1.13

func (p *Printer) Print(vs ...interface{})

Print the values.

func (*Printer) Println added in v0.1.13

func (p *Printer) Println(vs ...interface{})

Println prints each value on a new line.

type Test added in v0.2.0

type Test interface {
	Setup()
	Teardown()
}

Directories

Path Synopsis
cmd
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