asserts

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2022 License: BSD-3-Clause Imports: 12 Imported by: 0

Documentation

Overview

Package asserts helps writing convenient and powerful unit tests. One part of those are assertions to compare expected and obtained values. Additional text output for failing tests can be added.

In the beginning of a test function a new assertion instance is created with:

assert := asserts.NewTesting(t, shallFail)

Inside the test an assert looks like:

assert.Equal(obtained, expected, "obtained value has to be like expected")

If shallFail is set to true a failing assert also lets fail the Go test. Otherwise the failing is printed but the tests continue.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MakeMultiWaitChan

func MakeMultiWaitChan(size int) chan any

MakeMultiWaitChan is a simple one-liner to create a sized buffered signal channel for the wait assertion.

func MakeWaitChan

func MakeWaitChan() chan any

MakeWaitChan is a simple one-liner to create the buffered signal channel for the wait assertion.

func NewValidation

func NewValidation() (*Asserts, Failures)

NewValidation creates a new Asserts instance which collections validation failures. The returned Failures instance allows to test an access them.

func TypedValue

func TypedValue(value any) string

TypedValue returns a value including its type.

func ValueDescription

func ValueDescription(value any) string

ValueDescription returns a description of a value as string.

Types

type Asserts

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

Asserts provides a number of convenient test methods.

func New

func New(f Failer) *Asserts

New creates a new Asserts instance.

func NewPanic

func NewPanic() *Asserts

NewPanic creates a new Asserts instance which panics if a test fails.

func NewTesting

func NewTesting(f Failable, mode FailMode) *Asserts

NewTesting creates a new Asserts instance for use with the testing package. The *testing.T has to be passed as failable, the argument. shallFail controls if a failing assertion also lets fail the Go test.

func (*Asserts) About

func (a *Asserts) About(obtained, expected, extent float64, msgs ...string) bool

About tests if obtained and expected are near to each other (within the given extent).

func (*Asserts) AnyError added in v0.5.0

func (a *Asserts) AnyError(obtained any, msgs ...string) bool

AnyError tests if the obtained error or ErrorProne.Err() is not nil.

func (*Asserts) Assignable

func (a *Asserts) Assignable(obtained, expected any, msgs ...string) bool

Assignable tests if the types of expected and obtained are assignable.

func (*Asserts) Case

func (a *Asserts) Case(obtained string, upperCase bool, msgs ...string) bool

Case tests if obtained string is uppercase or lowercase.

func (*Asserts) Contains added in v0.4.0

func (a *Asserts) Contains(part, full any, msgs ...string) bool

Contains tests if the obtained data is part of the expected string, array, or slice.

func (*Asserts) Different

func (a *Asserts) Different(obtained, expected any, msgs ...string) bool

Different tests if obtained and expected are different.

func (*Asserts) Empty

func (a *Asserts) Empty(obtained any, msgs ...string) bool

Empty tests if the len of the obtained string, array, slice map, or channel is 0.

func (*Asserts) Equal

func (a *Asserts) Equal(obtained, expected any, msgs ...string) bool

Equal tests if obtained and expected are equal.

func (*Asserts) ErrorContains

func (a *Asserts) ErrorContains(obtained any, part string, msgs ...string) bool

ErrorContains tests if the obtained error contains a given string.

func (*Asserts) ErrorMatch

func (a *Asserts) ErrorMatch(obtained any, regex string, msgs ...string) bool

ErrorMatch tests if the obtained error as string matches a regular expression.

func (*Asserts) Fail

func (a *Asserts) Fail(msgs ...string) bool

Fail always fails.

func (*Asserts) Failf added in v0.7.0

func (a *Asserts) Failf(format string, as ...any) bool

Failf always fails with a formatted message.

func (*Asserts) False

func (a *Asserts) False(obtained bool, msgs ...string) bool

False tests if obtained is false.

func (*Asserts) Implementor

func (a *Asserts) Implementor(obtained, expected any, msgs ...string) bool

Implementor tests if obtained implements the expected interface variable pointer.

func (*Asserts) IncrCallstackOffset

func (a *Asserts) IncrCallstackOffset() func()

IncrCallstackOffset allows test libraries using the audit package internally to adjust the callstack offset. This way test output shows the correct location. Deferring the returned function restores the former offset.

func (*Asserts) Length

func (a *Asserts) Length(obtained any, expected int, msgs ...string) bool

Length tests if the len of the obtained string, array, slice map, or channel is equal to the expected one.

func (*Asserts) Logf

func (a *Asserts) Logf(format string, as ...any)

Logf can be used to display helpful information during testing.

func (*Asserts) Match

func (a *Asserts) Match(obtained, regex string, msgs ...string) bool

Match tests if the obtained string matches a regular expression.

func (*Asserts) Nil

func (a *Asserts) Nil(obtained any, msgs ...string) bool

Nil tests if obtained is nil.

func (*Asserts) NoError

func (a *Asserts) NoError(obtained any, msgs ...string) bool

NoError tests if the obtained error or ErrorProne.Err() is nil.

func (*Asserts) NotContains added in v0.4.0

func (a *Asserts) NotContains(part, full any, msgs ...string) bool

NotContains tests if the obtained data is not part of the expected string, array, or slice.

func (*Asserts) NotEmpty

func (a *Asserts) NotEmpty(obtained any, msgs ...string) bool

NotEmpty tests if the len of the obtained string, array, slice map, or channel is greater than 0.

func (*Asserts) NotNil

func (a *Asserts) NotNil(obtained any, msgs ...string) bool

NotNil tests if obtained is not nil.

func (*Asserts) NotOK added in v0.5.0

func (a *Asserts) NotOK(obtained any, msgs ...string) bool

NotOK is a convenient metatest depending in the obtained tyoe. In case of a bool it has to be false, a func() bool has to return false, an int has to be not 0, a string has to be not empty, and a func() error has to return an error. Any else value has to be not nil or in case of an ErrorProne its Err() has not to return nil.

func (*Asserts) NotPanics added in v0.4.0

func (a *Asserts) NotPanics(pf func(), msgs ...string) bool

NotPanics checks if the passed function does not panic.

func (*Asserts) OK added in v0.3.2

func (a *Asserts) OK(obtained any, msgs ...string) bool

OK is a convenient metatest depending in the obtained tyoe. In case of a bool it has to be true, a func() bool has to return true, an int has to be 0, a string has to be empty, and a func() error has to return no error. Any else value has to be nil or in case of an ErrorProne its Err() has to return nil.

func (*Asserts) Panics

func (a *Asserts) Panics(pf func(), msgs ...string) bool

Panics checks if the passed function panics.

func (*Asserts) PanicsWith added in v0.4.0

func (a *Asserts) PanicsWith(pf func(), reason any, msgs ...string) bool

PanicsWith checks if the passed function panics with the passed reason.

func (*Asserts) PathExists

func (a *Asserts) PathExists(obtained string, msgs ...string) bool

PathExists checks if the passed path or file exists.

func (*Asserts) Range

func (a *Asserts) Range(obtained, low, high any, msgs ...string) bool

Range tests if obtained is larger or equal low and lower or equal high. Allowed are byte, int and float64 for numbers, runes, strings, times, and duration. In case of obtained arrays, slices, and maps low and high have to be ints for testing the length.

func (*Asserts) Retry

func (a *Asserts) Retry(rf func() bool, retries int, pause time.Duration, msgs ...string) bool

Retry calls the passed function and expects it to return true. Otherwise it pauses for the given duration and retries the call the defined number.

func (*Asserts) SetFailable

func (a *Asserts) SetFailable(f Failable) func()

SetFailable allows to change the failable possibly used inside a failer. This way a testing.T of a sub-test can be injected. A restore function is returned.

t.Run(name, func(t *testing.T)) {
    defer assert.SetFailable(t)()
    ...
})

So the returned restorer function will be called when leaving the sub-test.

func (*Asserts) SetPrinter

func (a *Asserts) SetPrinter(printer Printer) Printer

SetPrinter sets a new Printer used for the output of failing tests or logging. The current one is returned, e.g. for a later restoring.

func (*Asserts) Substring

func (a *Asserts) Substring(obtained, full string, msgs ...string) bool

Substring tests if obtained is a substring of the full string.

func (*Asserts) True

func (a *Asserts) True(obtained bool, msgs ...string) bool

True tests if obtained is true.

func (*Asserts) Unassignable

func (a *Asserts) Unassignable(obtained, expected any, msgs ...string) bool

Unassignable tests if the types of expected and obtained are not assignable.

func (*Asserts) Wait

func (a *Asserts) Wait(
	sigc <-chan any,
	expected any,
	timeout time.Duration,
	msgs ...string,
) bool

Wait receives a signal from a channel and compares it to the expired value. Assert also fails on timeout.

func (*Asserts) WaitClosed

func (a *Asserts) WaitClosed(
	sigc <-chan any,
	timeout time.Duration,
	msgs ...string,
) bool

WaitClosed waits until a channel closing, the assert fails on a timeout.

func (*Asserts) WaitGroup

func (a *Asserts) WaitGroup(
	wg *sync.WaitGroup,
	timeout time.Duration,
	msgs ...string,
) bool

WaitGroup waits until a wait group instance is done, the assert fails on a timeout.

func (*Asserts) WaitTested

func (a *Asserts) WaitTested(
	sigc <-chan any,
	test func(any) error,
	timeout time.Duration,
	msgs ...string,
) bool

WaitTested receives a signal from a channel and runs the passed tester function on it. That has to return nil for a signal assert. In case of a timeout the assert fails.

type BufferedPrinter

type BufferedPrinter interface {
	Printer

	// Flush returns and resets the buffered prints.
	Flush() []string
}

BufferedPrinter collects prints to be retrieved later via Flush().

func NewBufferedPrinter

func NewBufferedPrinter() BufferedPrinter

NewBufferedPrinter returns the buffered printer for collecting assertion output.

type FailMode

type FailMode int

FailMode defines how to react on failing test asserts.

const (
	NoFailing    FailMode = 0 // NoFailing simply logs a failing.
	FailContinue FailMode = 1 // FailContinue logs a failing and calls Failable.Fail().
	FailStop     FailMode = 2 // FailStop logs a failing and calls Failable.FailNow().
)

Fail modes for test failer.

type Failable

type Failable interface {
	Fail()
	FailNow()
}

Failable allows an assertion to signal a fail to an external instance like testing.T or testing.B.

type Failer

type Failer interface {
	// SetPrinter sets a new Printer for the Failer and
	// returns the current one, e.g. for restoring.
	SetPrinter(printer Printer) Printer

	// IncrCallstackOffset increases the callstack offset for
	// the assertion output (see Asserts) and returns a function
	// for restoring.
	IncrCallstackOffset() func()

	// Logf can be used to display useful information during testing.
	Logf(format string, args ...any)

	// Fail will be called if an assert fails.
	Fail(test Test, obtained, expected any, msgs ...string) bool
}

Failer describes a type controlling how an assert reacts after a failure.

type FailureDetail

type FailureDetail interface {
	// TImestamp tells when the failure has happened.
	Timestamp() time.Time

	// Locations returns file name with line number and
	// function name of the failure.
	Location() (string, string)

	// Test tells which kind of test has failed.
	Test() Test

	// Error returns the failure as error.
	Error() error

	// Message return the optional test message.
	Message() string
}

FailureDetail contains detailed information of a failure.

type Failures

type Failures interface {
	// HasErrors returns true, if assertion failures happened.
	HasErrors() bool

	// Details returns the collected details.
	Details() []FailureDetail

	// Errors returns the so far collected errors.
	Errors() []error

	// Error returns the collected errors as one error.
	Error() error
}

Failures collects the collected failures of a validation assertion.

type Printer

type Printer interface {
	// Logf prints a formatted logging information.
	Logf(format string, args ...any)

	// Errorf prints a formatted error.
	Errorf(format string, args ...any)
}

Printer allows to switch between different outputs of the tests.

func NewStandardPrinter

func NewStandardPrinter() Printer

NewStandardPrinter creates a printer writing its output to stdout and stderr.

func NewWrappedPrinter

func NewWrappedPrinter(p Printer) Printer

NewWrappedPrinter returns a printer using the passed Printer.

type Test

type Test int

Test represents the test inside an assert.

const (
	Invalid Test = iota + 1
	True
	False
	Nil
	NotNil
	NoError
	AnyError
	Equal
	Different
	Contains
	NotContains
	About
	Range
	Substring
	Case
	Match
	ErrorMatch
	ErrorContains
	Implementor
	Assignable
	Unassignable
	Empty
	NotEmpty
	Length
	Panics
	NotPanics
	PanicsWith
	PathExists
	Wait
	WaitClosed
	WaitGroup
	WaitTested
	Retry
	Fail
	OK
	NotOK
)

Tests provided by the assertion.

func (Test) String

func (t Test) String() string

String implements fmt.Stringer.

Jump to

Keyboard shortcuts

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