expect

package module
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: LGPL-3.0 Imports: 19 Imported by: 1

README

expect

Go test expectations.

Intention of the library is to be able to write simple readable tests which produce easy to understand messages when the expectation fails.

func TestExample(t *testing.T) {
    expect.Value(t, "the guy", "Peter").ToBe("Steven")
    // will fail with error:
    //   expected the guy to be 'Steven' but it is 'Peter'
}

Expectations

ToBe

Asserts that the value is deeply equal to the provided value.

expect.Value(t, "the house", "big").ToBe("small")
// expected the house to be 'small' but it is 'big'
checking time.Time

When comparing times it can happen that two time instances with the exact same date/time can be different. This happens when one of them has location set to nil and the other to UTC. Although the documntation states that nil must be used instead of UTC some 3th party libs manage to return such instances.

checking nil

A check for nil will always be ok if the value is nil or a interface that points to a nil value. This allows that following works:

var a = *AType
expect.Value(t, "a nil", a).ToBe(nil)
checking error

For error comparison the Error strings are returned. This can lead to messages like expected Error to be 'foo' but it is 'foo'.

checking structs, slices, maps

It will print complex data types formated as yaml:

expect.Value(t, "array", []int{3, 1}).ToBe([]int{1, 3})
// expected array to be:
//   > - 1
//   > - 3
// but it is:
//   > - 3
//   > - 1

It will check for exact numbers:

expect.Value(t, "liters", 3.4500000000001).ToBe(3.45)
// expected liters to be 3.45 but it is 3.4500000000001
ToCount

Asserts that the list/map/chan/string has c elements.

expect.Value(t, "token", "F7gTr7y").ToCount(8)
// expected token to have 8 elements but it has 7 elements
ToHavePrefix/Suffix

Asserts that the string begins with the provided string or ends with it.

NotToBe

Asserts that the value is not deeply equal to the provided value.

ToBeAbout

Asserts that the value deeply equals the expected value like ToBe, except that numeric, time.Time and time.Duration leaves only need to be within the deltas given as options. The structural shape and every other leaf must still match exactly. Without options it behaves like an exact match.

expect.Value(t, "liters", 1.92).ToBeAbout(2.0, expect.FloatDelta(0.1))

expect.Value(t, "measurement", got).ToBeAbout(want,
    expect.FloatDelta(0.01),
    expect.IntDelta(5),
    expect.TimeDelta(time.Second),
    expect.DurationDelta(10*time.Millisecond),
)
// on mismatch it points at the offending path:
// expected measurement.Readings[1] to be 2±0.1 but it is 2.5

The available options are FloatDelta (float32/float64), IntDelta (signed and unsigned integers), TimeDelta (time.Time) and DurationDelta (time.Duration). A leaf with no matching option, or any non-numeric leaf, must match exactly.

time.Time values are compared by instant (a.Sub(b)), not field by field, so the location/monotonic-clock pitfall described under ToBe does not apply. Tolerances reach values through exported fields, slices, arrays and maps; unexported leaves are compared exactly.

ToBeType

Asserts that the type of the value is the same of the value given as parameter.

ToBeSnapshot(filename)

ToBeSnapshot checks if the value is the same as what's in the given file. The value can be a string or a []byte slice.

  • If the file isn't there, it will make a new one. You can look at it and change it if you need to.

  • If the value doesn't match what's in the file, the test will fail. It will also create a new file with the same name but with a ".current" extension. This file will contain the failed content.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	PlainOutput       = output("plain")
	ColoredDiffOutput = output("coloredDiffOutput")
)
View Source
var Default = &Expect{
	Output: PlainOutput,
}

Functions

This section is empty.

Types

type AboutOption added in v0.14.0

type AboutOption func(*aboutConfig)

AboutOption configures the per-type tolerances used by ToBeAbout.

func DurationDelta added in v0.14.0

func DurationDelta(d time.Duration) AboutOption

DurationDelta sets the maximum allowed absolute difference for time.Duration leaves.

func FloatDelta added in v0.14.0

func FloatDelta(d float64) AboutOption

FloatDelta sets the maximum allowed absolute difference for float32/float64 leaves.

func IntDelta added in v0.14.0

func IntDelta(d int64) AboutOption

IntDelta sets the maximum allowed absolute difference for signed and unsigned integer leaves.

func TimeDelta added in v0.14.0

func TimeDelta(d time.Duration) AboutOption

TimeDelta sets the maximum allowed absolute difference for time.Time leaves. Times are compared by instant (a.Sub(b)), not field by field.

type Expect

type Expect struct {
	Output output
}

func (*Expect) Error

func (e *Expect) Error(t Test, val interface{}) Val

Error wraps an error and provides expectations for this value. This is a shortcut for Value(t, "error", val).

func (*Expect) Value

func (e *Expect) Value(t Test, name string, val interface{}) Val

Value wraps a value and provides expectations for this value.

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithExact

func WithExact() Option

func WithMatchTolerance

func WithMatchTolerance(t float64) Option

WithMatchTolerance sets the maximum fraction of pixels that may differ while still accepting the image. 0 means no mismatches allowed. 1 means all mismatches allowed.

func WithPixelTolerance

func WithPixelTolerance(t float64) Option

WithPixelTolerance sets the maximum allowed color difference for a pixel to be considered a match. 0 means exact match only. 1 means all pixels matched.

type Test

type Test interface {
	Fatalf(f string, i ...interface{})
	Errorf(f string, i ...interface{})
	Error(p ...interface{})
	Helper()
}

Test implements testing.T methods used by expect. Necessary to: - allow usage of testing.T and testing.B instances - for running tests

type Val

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

Val to call expectations on.

func Error

func Error(t Test, val interface{}) Val

Error wraps an error and provides expectations for this value. It delegates to the default instance `Default`.

func Value

func Value(t Test, name string, val interface{}) Val

Value wraps a value and provides expectations for this value. It delegates to the default instance `Default`.

func (Val) First

func (e Val) First() Val

func (Val) Last

func (e Val) Last() Val

func (Val) Message

func (e Val) Message() Val

Message creates a new value from the given errors message. If the error is nil the message wil be the empty string.

func (Val) NotToBe

func (e Val) NotToBe(unExpected interface{}) Val

NotToBe asserts that the value is not deeply equals to expected value.

func (Val) ToBe

func (e Val) ToBe(expected interface{}) Val

ToBe asserts that the value is deeply equals to expected value.

func (Val) ToBeAbout

func (e Val) ToBeAbout(expected interface{}, opts ...AboutOption) Val

ToBeAbout asserts that the value deeply equals expected, like ToBe, except that numeric, time.Time and time.Duration leaves only need to be within the deltas given by the options. Every other leaf and the structural shape must still match exactly. Without options it behaves like an exact match.

Tolerances apply to top-level values and to values reachable through exported fields, slices, arrays and maps. Unexported leaves are compared exactly.

func (Val) ToBeSnapshot

func (e Val) ToBeSnapshot(path string) Val

func (Val) ToBeSnapshotImage

func (e Val) ToBeSnapshotImage(path string, opts ...Option) Val

ToBeSnapshotImage saves the image in the first run, in later runs, compares the image to the saved one. If they are not the same it will write a .current.pn and .diff.png version of the image. The images match by default when 99% of the pixels colors are by less than 10% off. The Parameter SnapshotImageOptionExact forces the images to be exactly the same.

func (Val) ToBeType

func (e Val) ToBeType(t any) Val

func (Val) ToContain

func (e Val) ToContain(expected interface{}) Val

ToContain checks if the expected value is in the expected slice or if the string contains a substring or not. Does a deep equal for slices.

func (Val) ToCount

func (e Val) ToCount(c int) Val

ToCount asserts that the list/map/chan/string has c elements. Strings use the number of unicode chars.

func (Val) ToHavePrefix

func (e Val) ToHavePrefix(prefix string) Val

ToHavePrefix asserts that the string value starts with the provided prefix.

func (Val) ToHaveSuffix

func (e Val) ToHaveSuffix(suffix string) Val

ToHaveSuffix asserts that the string value ends with the provided sufix.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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