Documentation
¶
Overview ¶
Package check provides equality toolkit used by assert package.
Index ¶
- Constants
- Variables
- func AddRows(ops Options, msg *notice.Notice) *notice.Notice
- func After(mark, date any, opts ...any) error
- func AfterOrEqual(mark, date any, opts ...any) error
- func Before(mark, date any, opts ...any) error
- func BeforeOrEqual(mark, date any, opts ...any) error
- func Cap(want int, have any, opts ...any) (err error)
- func ChannelWillClose[C any](within any, c <-chan C, opts ...any) error
- func Contain(want, have string, opts ...any) error
- func Count(count int, what, where any, opts ...any) error
- func Decreasing[T constraints.Ordered](seq []T, opts ...any) error
- func Delta[T, E constraints.Number](want T, delta E, have T, opts ...any) error
- func DeltaSlice[T, E constraints.Number](want []T, delta E, have []T, opts ...any) error
- func DirExist(pth string, opts ...any) error
- func Duration(want, have any, opts ...any) error
- func Empty(have any, opts ...any) error
- func Epsilon[T, E constraints.Number](want T, epsilon E, have T, opts ...any) error
- func EpsilonSlice[T, E constraints.Number](want []T, epsilon E, have []T, opts ...any) error
- func Equal(want, have any, opts ...any) error
- func Error(err error, opts ...any) error
- func ErrorAs(want any, err error, opts ...any) error
- func ErrorContain(want string, err error, opts ...any) error
- func ErrorEqual(want string, err error, opts ...any) error
- func ErrorIs(want, err error, opts ...any) error
- func ErrorRegexp(want any, err error, opts ...any) error
- func Exact(want, have any, opts ...any) error
- func ExitCode(want int, err error, opts ...any) error
- func False(have bool, opts ...any) error
- func FieldName(ops Options, typeName string) func(fldName string) Option
- func Fields(want int, s any, opts ...any) error
- func FileContain[T Content](want T, pth string, opts ...any) error
- func FileExist(pth string, opts ...any) error
- func Greater[T constraints.Ordered](want, have T, opts ...any) error
- func GreaterOrEqual[T constraints.Ordered](want, have T, opts ...any) error
- func Has[T comparable](want T, bag []T, opts ...any) error
- func HasKey[K comparable, V any](key K, set map[K]V, opts ...any) (V, error)
- func HasKeyValue[K, V comparable](key K, want V, set map[K]V, opts ...any) error
- func HasNo[T comparable](want T, set []T, opts ...any) error
- func HasNoKey[K comparable, V any](key K, set map[K]V, opts ...any) error
- func Increasing[T constraints.Ordered](seq []T, opts ...any) error
- func JSON(want, have string, opts ...any) error
- func Len(want int, have any, opts ...any) (err error)
- func MapSubset[K comparable, V any](want, have map[K]V, opts ...any) error
- func MapsSubset[K comparable, V any](want, have []map[K]V, opts ...any) error
- func Nil(have any, opts ...any) error
- func NoDirExist(pth string, opts ...any) error
- func NoError(err error, opts ...any) error
- func NoFileExist(pth string, opts ...any) error
- func NoPanic(fn TestFunc, opts ...any) error
- func NotContain(want, have string, opts ...any) error
- func NotDecreasing[T constraints.Ordered](seq []T, opts ...any) error
- func NotEmpty(have any, opts ...any) error
- func NotEqual(want, have any, opts ...any) error
- func NotIncreasing[T constraints.Ordered](seq []T, opts ...any) error
- func NotNil(have any, opts ...any) error
- func NotSame(want, have any, opts ...any) error
- func NotSameType(want, have any, opts ...any) error
- func NotZero(have any, opts ...any) error
- func Panic(fn TestFunc, opts ...any) error
- func PanicContain(want string, fn TestFunc, opts ...any) error
- func PanicMsg(fn TestFunc, opts ...any) (*string, error)
- func Recent(have any, opts ...any) error
- func Regexp(want, have any, opts ...any) error
- func RegisterTypeChecker(typ any, chk Checker)
- func Same(want, have any, opts ...any) error
- func SameType(want, have any, opts ...any) error
- func SliceSubset[V comparable](want, have []V, opts ...any) error
- func Smaller[T constraints.Ordered](want, have T, opts ...any) error
- func SmallerOrEqual[T constraints.Ordered](want, have T, opts ...any) error
- func Time(want, have any, opts ...any) error
- func True(have bool, opts ...any) error
- func Type(target, src any, opts ...any) error
- func Wait(within any, fn func() bool, opts ...any) error
- func Within(want, within, have any, opts ...any) error
- func Zero(have any, opts ...any) error
- func Zone(want, have any, opts ...any) error
- type Checker
- type Content
- type Option
- func WithComment(format string, args ...any) Option
- func WithDumper(optsD ...dump.Option) Option
- func WithOptions(src Options) Option
- func WithRecent(recent time.Duration) Option
- func WithSkipTrail(skip ...string) Option
- func WithTimeFormat(format string) Option
- func WithTrail(pth string) Option
- func WithTrailChecker(trail string, chk Checker) Option
- func WithTrailLog(list *[]string) Option
- func WithTypeChecker(typ any, chk Checker) Option
- func WithWaitThrottle(throttle time.Duration) Option
- func WithZone(zone *time.Location) Option
- type Options
- type TestFunc
Examples ¶
- Equal (Arrays)
- Equal (CustomTrailChecker)
- Equal (CustomTypeChecker)
- Equal (ListVisitedTrails)
- Equal (Maps)
- Equal (RecursiveStructs)
- Equal (SkipAllUnexportedFields)
- Equal (SkipTrails)
- Equal (Slices)
- Equal (Structs)
- Equal (WrongTypes)
- Error
- JSON
- NoError
- NoError (ChangeMessage)
- NoError (WithTrail)
- Time
Constants ¶
const ( // DefaultParseTimeFormat is default format for dumping [time.Time] values. DefaultParseTimeFormat = time.RFC3339Nano // DefaultRecentDuration is default duration when comparing recent dates. DefaultRecentDuration = 10 * time.Second // DefaultDumpTimeFormat is default format for parsing time strings. DefaultDumpTimeFormat = time.RFC3339Nano // DefaultDumpDepth is default depth when dumping values recursively in log // messages. DefaultDumpDepth = 6 )
Package wide default configuration.
Variables ¶
var ( // ParseTimeFormat is a configurable format for parsing time strings. ParseTimeFormat = DefaultParseTimeFormat // RecentDuration is a configurable duration when comparing recent dates. RecentDuration = DefaultRecentDuration // DumpTimeFormat is configurable format for dumping [time.Time] values. DumpTimeFormat = DefaultDumpTimeFormat // DumpDepth is a configurable depth when dumping values in log messages. DumpDepth = DefaultDumpDepth )
Package-wide configuration.
var ( // ErrTimeType is returned when time representation is not supported. ErrTimeType = fmt.Errorf("not supported time type") // ErrTimeParse is used when date parsing fails for whatever reason. ErrTimeParse = fmt.Errorf("time parsing") // ErrZoneType is returned when timezone representation is not supported. ErrZoneType = fmt.Errorf("not supported timezone type") // ErrZoneParse is used when timezone parsing fails for whatever reason. ErrZoneParse = fmt.Errorf("timezone parsing") // ErrDurType is returned when duration representation is not supported. ErrDurType = fmt.Errorf("not supported duration type") // ErrDurParse is used when duration parsing fails for whatever reason. ErrDurParse = fmt.Errorf("duration parsing") )
Sentinel errors.
Functions ¶
func AddRows ¶ added in v0.35.0
AddRows adds rows based on the Options instance to the notice.Notice.
func After ¶
After checks "date" is after "mark". Returns nil if it is, otherwise it returns an error with a message indicating the expected and actual values.
The "date" and "mark" may represent dates in the form of a string, int, int64 or time.Time. For string representations the [Options.TimeFormat] is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.
func AfterOrEqual ¶
AfterOrEqual checks "date" is equal or after "mark". Returns nil if it is, otherwise it returns an error with a message indicating the expected and actual values.
The "date" and "mark" may represent dates in the form of a string, int, int64 or time.Time. For string representations the [Options.TimeFormat] is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.
func Before ¶
Before checks "date" is before "mark". Returns nil if it is, otherwise it returns an error with a message indicating the expected and actual values.
The "want" and "have" may represent dates in the form of a string, int, int64 or time.Time. For string representations the [Options.TimeFormat] is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.
func BeforeOrEqual ¶
BeforeOrEqual checks "date" is equal or before "mark". Returns nil if it is, otherwise it returns an error with a message indicating the expected and actual values.
The "date" and "mark" may represent dates in the form of a string, int, int64 or time.Time. For string representations the [Options.TimeFormat] is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.
func Cap ¶ added in v0.28.0
Cap checks "have" has "want" capacity. Returns nil if it has, otherwise it returns an error with a message indicating the expected and actual values.
func ChannelWillClose ¶
ChannelWillClose checks the channel will be closed "within" a given time duration. Returns nil if it was, otherwise returns an error with a message indicating the expected and actual values.
The "within" may represent duration in the form of a string, int, int64 or time.Duration.
func Contain ¶
Contain checks "want" is a substring of "have". Returns nil if it's, otherwise returns an error with a message indicating the expected and actual values.
func Count ¶
Count checks there is "count" occurrences of "what" in "where". Returns nil if it's, otherwise it returns an error with a message indicating the expected and actual values.
Currently, only strings are supported.
func Decreasing ¶ added in v0.22.0
func Decreasing[T constraints.Ordered](seq []T, opts ...any) error
Decreasing checks if the given sequence has values in the decreasing order. You may use the WithDecreasingSoft option to allow consecutive values to be equal. It returns an error if the sequence is not decreasing.
func Delta ¶ added in v0.23.0
func Delta[T, E constraints.Number]( want T, delta E, have T, opts ...any, ) error
Delta checks the both values are within the given delta. Returns nil if they are, otherwise it returns an error with a message indicating the expected and actual values.
|w-h| <= delta
func DeltaSlice ¶ added in v0.23.0
func DeltaSlice[T, E constraints.Number]( want []T, delta E, have []T, opts ...any, ) error
DeltaSlice checks values are within the given delta for all respective slice indexes. It returns nil if all differences are within the delta; otherwise, it returns an error indicating the first index where the "have" slice violates the epsilon condition.
|w[i]-h[i]| <= delta
func DirExist ¶
DirExist checks "pth" points to an existing directory. It fails if the path points to a filesystem entry which is not a directory or there is an error when trying to check the path. When it fails it returns an error with a detailed message indicating the expected and actual values.
func Duration ¶
Duration checks "want" and "have" durations are equal. Returns nil if they are, otherwise returns an error with a message indicating the expected and actual values.
The "want" and "have" may represent duration in the form of a string, int, int64 or time.Duration.
func Empty ¶
Empty checks if "have" is empty. Returns nil if it's, otherwise it returns an error with a message indicating the expected and actual values.
Empty values are:
- nil
- int(0)
- float64(0)
- float32(0)
- false
- len(array) == 0
- len(slice) == 0
- len(map) == 0
- len(chan) == 0
- time.Time{}
func Epsilon ¶
func Epsilon[T, E constraints.Number]( want T, epsilon E, have T, opts ...any, ) error
Epsilon checks the relative error is less than epsilon. Returns nil if it does, otherwise it returns an error with a message indicating the expected and actual values.
|w-h|/|w| <= epsilon
func EpsilonSlice ¶ added in v0.21.0
func EpsilonSlice[T, E constraints.Number]( want []T, epsilon E, have []T, opts ...any, ) error
EpsilonSlice checks the relative error is less than epsilon for all respective values in the provided slices. It returns nil if all differences are within the epsilon; otherwise, it returns an error indicating the first index where the "have" slice violates the epsilon condition.
|w[i]-h[i]|/|w[i]| <= epsilon
func Equal ¶
Equal recursively checks both values are equal. Returns nil if they are, otherwise it returns an error with a message indicating the expected and actual values.
Example (Arrays) ¶
package main
import (
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
want := [...]int{1, 2, 3}
have := [...]int{1, 2, 3, 4}
err := check.Equal(want, have)
fmt.Println(err)
}
Output: expected values to be equal: want type: [3]int have type: [4]int
Example (CustomTrailChecker) ¶
package main
import (
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
type T struct {
Str string
Any []any
}
chk := func(want, have any, opts ...any) error {
wVal := want.(float64)
hVal := want.(float64)
return check.Epsilon(wVal, 0.01, hVal, opts...)
}
opt := check.WithTrailChecker("T.Any[1]", chk)
want := T{Str: "abc", Any: []any{1, 2.123, "abc"}}
have := T{Str: "abc", Any: []any{1, 2.124, "abc"}}
err := check.Equal(want, have, opt)
fmt.Println(err)
}
Output: <nil>
Example (CustomTypeChecker) ¶
package main
import (
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
type T struct{ value float64 }
chk := func(want, have any, opts ...any) error {
w := want.(T)
h := have.(T)
return check.Epsilon(w.value, h.value, 0.001, opts...)
}
opt := check.WithTypeChecker(T{}, chk)
want := T{value: 1.2345}
have := T{value: 1.2346}
err := check.Equal(want, have, opt)
fmt.Println(err)
}
Output: <nil>
Example (ListVisitedTrails) ¶
package main
import (
"fmt"
"strings"
"github.com/ctx42/testing/pkg/check"
)
func main() {
type T struct {
Int int
Next *T
}
have := T{1, &T{2, &T{3, &T{42, nil}}}}
want := T{1, &T{2, &T{3, &T{42, nil}}}}
trails := make([]string, 0)
err := check.Equal(want, have, check.WithTrailLog(&trails))
fmt.Println(err)
fmt.Println(strings.Join(trails, "\n"))
}
Output: <nil> T.Int T.Next.Int T.Next.Next.Int T.Next.Next.Next.Int T.Next.Next.Next.Next
Example (Maps) ¶
package main
import (
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
type T struct{ Str string }
want := map[int]T{1: {Str: "abc"}, 2: {Str: "xyz"}}
have := map[int]T{1: {Str: "abc"}, 3: {Str: "xyz"}}
err := check.Equal(want, have)
fmt.Println(err)
}
Output: expected values to be equal: trail: map[2] want type: map[int]check_test.T have type: <nil> want: map[int]check_test.T{ 1: { Str: "abc", }, 3: { Str: "xyz", }, } have: nil
Example (RecursiveStructs) ¶
package main
import (
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
type T struct {
Int int
Next *T
}
have := T{1, &T{2, &T{3, &T{42, nil}}}}
want := T{1, &T{2, &T{3, &T{4, nil}}}}
err := check.Equal(want, have)
fmt.Println(err)
}
Output: expected values to be equal: trail: T.Next.Next.Next.Int want: 4 have: 42
Example (SkipAllUnexportedFields) ¶
package main
import (
"fmt"
"strings"
"github.com/ctx42/testing/pkg/check"
)
func main() {
type T struct {
Int int
prv int
Next *T
}
have := T{1, -1, &T{2, -2, &T{3, -3, &T{42, -4, nil}}}}
want := T{1, -7, &T{2, -7, &T{3, -7, &T{42, -7, nil}}}}
trails := make([]string, 0)
err := check.Equal(
want,
have,
check.WithTrailLog(&trails),
check.WithSkipUnexported,
)
fmt.Println(err)
fmt.Println(strings.Join(trails, "\n"))
}
Output: <nil> T.Int T.prv <skipped> T.Next.Int T.Next.prv <skipped> T.Next.Next.Int T.Next.Next.prv <skipped> T.Next.Next.Next.Int T.Next.Next.Next.prv <skipped> T.Next.Next.Next.Next
Example (SkipTrails) ¶
package main
import (
"fmt"
"strings"
"github.com/ctx42/testing/pkg/check"
)
func main() {
type T struct {
Int int
Next *T
}
have := T{1, &T{2, &T{3, &T{42, nil}}}}
want := T{1, &T{2, &T{8, &T{42, nil}}}}
trails := make([]string, 0)
err := check.Equal(
want,
have,
check.WithTrailLog(&trails),
check.WithSkipTrail("T.Next.Next.Int"),
)
fmt.Println(err)
fmt.Println(strings.Join(trails, "\n"))
}
Output: <nil> T.Int T.Next.Int T.Next.Next.Int <skipped> T.Next.Next.Next.Int T.Next.Next.Next.Next
Example (Slices) ¶
package main
import (
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
want := []int{1, 2, 3}
have := []int{1, 2, 3, 4}
err := check.Equal(want, have)
fmt.Println(err)
}
Output: expected values to be equal: want len: 3 have len: 4 want: []int{ 1, 2, 3, } have: []int{ 1, 2, 3, 4, } diff: @@ -2,5 +2,4 @@ 1, 2, - 3, - 4, + 3, }
Example (Structs) ¶
package main
import (
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
type T struct {
Int int
Str string
}
have := T{Int: 1, Str: "abc"}
want := T{Int: 2, Str: "xyz"}
err := check.Equal(want, have)
fmt.Println(err)
}
Output: multiple expectations violated: error: expected values to be equal trail: T.Int want: 2 have: 1 --- error: expected values to be equal trail: T.Str want: "xyz" have: "abc"
Example (WrongTypes) ¶
package main
import (
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
err := check.Equal(42, byte(42), check.WithTrail("type.field"))
fmt.Println(err)
}
Output: expected values to be equal: trail: type.field want type: int have type: uint8
func Error ¶
Error checks "err" is not nil. Returns an error if it's nil.
Example ¶
package main
import (
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
err := check.Error(nil)
fmt.Println(err)
}
Output: expected non-nil error
func ErrorAs ¶
ErrorAs checks there is an error in the "err" tree that matches the "want" target, and if one is found, sets the target to that error. Returns nil if the target is found, otherwise returns an error with a message indicating the expected and actual values.
func ErrorContain ¶
ErrorContain checks "err" is not nil and its message contains "want". Returns nil if it's, otherwise it returns an error with a message indicating the expected and actual values.
func ErrorEqual ¶
ErrorEqual checks "err" is not nil and its message equals to "want". Returns nil if it's, otherwise it returns an error with a message indicating the expected and actual values.
func ErrorIs ¶
ErrorIs checks whether any error in the "err" tree matches the "want" target. Returns nil if it's, otherwise returns an error with a message indicating the expected and actual values.
func ErrorRegexp ¶
ErrorRegexp checks "err" is not nil and its message matches the "want" regex. Returns nil if it is, otherwise it returns an error with a message indicating the expected and actual values.
The "want" can be either a regular expression string or instance of regexp.Regexp. The fmt.Sprint is used to get string representation of have argument.
func Exact ¶
Exact checks "want" and "have" dates are equal and are in the same timezone. Returns nil they are, otherwise returns an error with a message indicating the expected and actual values.
The "want" and "have" may represent dates in the form of a string, int, int64 or time.Time. For string representations the [Options.TimeFormat] is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.
func ExitCode ¶
ExitCode checks "err" is pointer to exec.ExitError with exit code equal to "want". Returns nil if it's, otherwise it returns an error with a message indicating the expected and actual values.
func False ¶
False checks "have" is false. Returns nil if it's, otherwise it returns an error with a message indicating the expected and actual values.
func FieldName ¶ added in v0.7.0
FieldName returns a helper function which updates [Options.Trail].
It is useful when construction trails in custom struct checkers.
Example:
func fileCheck(want, have any, opts ...any) error {
ops := check.DefaultOptions(opts...)
if err := check.Type(file{}, have, check.WithOptions(ops)); err != nil {
return err
}
w, h := want.(file), have.(file)
fName := check.FieldName(ops, "file")
ers := []error{
check.Equal(w.path, h.path, fName("path")),
check.Equal(w.pks, h.pks, fName("pks")),
// Not all fields are compared.
check.Fields(4, w, fName("{field count}")),
}
return notice.Join(ers...)
}
func Fields ¶
Fields checks a struct or pointer to a struct "s" has "want" number of fields. Returns nil if it does, otherwise it returns an error with a message indicating the expected and actual values.
func FileContain ¶
FileContain checks file at "pth" can be read and its string content contains "want". It fails if the path points to a filesystem entry which is not a file or there is an error reading the file. The file is read in full then strings.Contains is used to check it contains "want" string. When it fails it returns an error with a message indicating the expected and actual values.
func FileExist ¶
FileExist checks "pth" points to an existing file. Returns an error if the path points to a filesystem entry which is not a file or there is an error when trying to check the path. On success, it returns nil.
func Greater ¶ added in v0.22.0
func Greater[T constraints.Ordered](want, have T, opts ...any) error
Greater checks the "have" value is greater than the "want" value. Returns nil if the condition is met, otherwise it returns an error with a message indicating the expected and actual values.
func GreaterOrEqual ¶ added in v0.22.0
func GreaterOrEqual[T constraints.Ordered](want, have T, opts ...any) error
GreaterOrEqual checks the "have" value is greater or equal than the "want" value. Returns nil if the condition is met, otherwise it returns an error with a message indicating the expected and actual values.
func Has ¶
func Has[T comparable](want T, bag []T, opts ...any) error
Has checks slice has "want" value. Returns nil if it does, otherwise it returns an error with a message indicating the expected and actual values.
func HasKey ¶
func HasKey[K comparable, V any](key K, set map[K]V, opts ...any) (V, error)
HasKey checks the map has a key. If the key exists, it returns its value and nil, otherwise it returns zero-value and an error with a message indicating the expected and actual values.
func HasKeyValue ¶
func HasKeyValue[K, V comparable](key K, want V, set map[K]V, opts ...any) error
HasKeyValue checks the map has a key with a given value. Returns nil if it doesn't, otherwise it returns an error with a message indicating the expected and actual values.
func HasNo ¶
func HasNo[T comparable](want T, set []T, opts ...any) error
HasNo checks slice does not have the "want" value. Returns nil if it doesn't, otherwise it returns an error with a message indicating the expected and actual values.
func HasNoKey ¶
func HasNoKey[K comparable, V any](key K, set map[K]V, opts ...any) error
HasNoKey checks map has no key. Returns nil if it doesn't, otherwise it returns an error with a message indicating the expected and actual values.
func Increasing ¶ added in v0.22.0
func Increasing[T constraints.Ordered](seq []T, opts ...any) error
Increasing checks if the given sequence has values in the increasing order. You may use the WithIncreasingSoft option to allow consecutive values to be equal. It returns an error if the sequence is not increasing.
func JSON ¶
JSON checks that two JSON strings are equivalent. Returns nil if they are, otherwise it returns an error with a message indicating the expected and actual values.
Example:
check.JSON(`{"hello": "world"}`, `{"foo": "bar"}`)
Example ¶
package main
import (
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
want := `{"A": 1, "B": 2}`
have := `{"A": 1, "B": 3}`
err := check.JSON(want, have)
fmt.Println(err)
}
Output: expected JSON strings to be equal: want: {"A":1,"B":2} have: {"A":1,"B":3}
func Len ¶
Len checks "have" has "want" length. Returns nil if it has, otherwise it returns an error with a message indicating the expected and actual values.
func MapSubset ¶
func MapSubset[K comparable, V any](want, have map[K]V, opts ...any) error
MapSubset checks the "want" is a subset "have". In other words, all keys and their corresponding values in the "want" map must be in the "have" map. It is not an error when the "have" map has some other keys. Returns nil if "want" is a subset of "have", otherwise it returns an error with a message indicating the expected and actual values.
func MapsSubset ¶
func MapsSubset[K comparable, V any](want, have []map[K]V, opts ...any) error
MapsSubset checks all the "want" maps are subsets of corresponding "have" maps using MapSubset. Returns nil if all "want" maps are subset of corresponding "have" maps, otherwise it returns an error with a message indicating the expected and actual values.
func Nil ¶
Nil checks "have" is nil. Returns nil if it's, otherwise returns an error with a message indicating the expected and actual values.
func NoDirExist ¶
NoDirExist checks "pth" points to not existing directory. It fails if the path points to an existing filesystem entry. When it fails it returns an error with a detailed message indicating the expected and actual values.
func NoError ¶
NoError checks "err" is nil. Returns error it's not nil.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
have := errors.New("test error")
err := check.NoError(have)
fmt.Println(err)
}
Output: expected the error to be nil: want: nil have: "test error"
Example (ChangeMessage) ¶
package main
import (
"errors"
"fmt"
"github.com/ctx42/testing/pkg/check"
"github.com/ctx42/testing/pkg/notice"
)
func main() {
have := errors.New("test error")
err := check.NoError(have, check.WithTrail("type.field"))
err = notice.From(err, "prefix").Append("context", "wow")
fmt.Println(err)
}
Output: [prefix] expected the error to be nil: trail: type.field want: nil have: "test error" context: wow
Example (WithTrail) ¶
package main
import (
"errors"
"fmt"
"github.com/ctx42/testing/pkg/check"
)
func main() {
have := errors.New("test error")
err := check.NoError(have, check.WithTrail("type.field"))
fmt.Println(err)
}
Output: expected the error to be nil: trail: type.field want: nil have: "test error"
func NoFileExist ¶
NoFileExist checks "pth" points to not existing file. Returns an error if the path points to an existing filesystem entry. On success, it returns nil.
func NoPanic ¶
NoPanic checks "fn" does not panic. Returns nil if it doesn't, otherwise it returns an error with a message with value passed to panic and stack trace.
func NotContain ¶
NotContain checks "want" is not a substring of "have". Returns nil if it's, otherwise returns an error with a message indicating the expected and actual values.
func NotDecreasing ¶ added in v0.22.0
func NotDecreasing[T constraints.Ordered](seq []T, opts ...any) error
NotDecreasing is inverse of Decreasing.
func NotEmpty ¶
NotEmpty checks "have" is not empty. Returns nil if it's otherwise, it returns an error with a message indicating the expected and actual values.
See check.Empty for the list of values which are considered empty.
func NotEqual ¶
NotEqual checks both values are not equal using. Returns nil if they are not, otherwise it returns an error with a message indicating the expected and actual values.
func NotIncreasing ¶ added in v0.22.0
func NotIncreasing[T constraints.Ordered](seq []T, opts ...any) error
NotIncreasing is inverse of Increasing.
func NotNil ¶
NotNil checks if "have" is not nil. Returns nil if it is not nil, otherwise returns an error with a message indicating the expected and actual values.
The returned error might be one or more errors joined with errors.Join.
func NotSame ¶
NotSame checks "want" and "have" are generic pointers and that both of them reference the same object. Returns nil if it is, otherwise it returns an error with a message indicating the expected and actual values.
Both arguments must be pointer variables. Pointer variable sameness is determined based on the equality of both type and value.
func NotSameType ¶ added in v0.38.0
NotSameType checks that the arguments are not of the same type. Returns nil if they are not, otherwise it returns an error with a message indicating the expected and actual values.
Check uses reflect.TypeOf equality to determine the type.
func NotZero ¶
NotZero checks "have" is not the zero value for its type. Returns nil if it is, otherwise it returns an error with a message indicating the expected and actual values.
func Panic ¶
Panic checks "fn" panics. Returns nil if it does, otherwise it returns an error with a message with value passed to panic and stack trace.
func PanicContain ¶
PanicContain checks "fn" panics, and the recovered panic value represented as a string contains "want". Returns nil if it does, otherwise it returns an error with a message with value passed to panic and stack trace.
func PanicMsg ¶
PanicMsg checks "fn" panics and returns the recovered panic value as a string. If the function doesn't panic, it returns nil and an error with a detailed message indicating the expected behavior.
func Recent ¶
Recent checks "have" is within [Options.Recent] from time.Now. Returns nil if it is, otherwise returns an error with a message indicating the expected and actual values.
The "have" may represent date in the form of a string, int, int64 or time.Time. For string representations the [Options.TimeFormat] is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.
func Regexp ¶
Regexp checks that "want" regexp matches "have". Returns nil if it does, otherwise, it returns an error with a message indicating the expected and actual values.
The "want" can be either a regular expression string or instance of regexp.Regexp. The fmt.Sprint is used to get string representation of have argument.
func RegisterTypeChecker ¶ added in v0.7.0
RegisterTypeChecker globally registers a custom checker for a given type. It panics if a checker for the same type is already registered.
func Same ¶
Same checks "want" and "have" are generic pointers and that both of them reference the same object. Returns nil if they are, otherwise it returns an error with a message indicating the expected and actual values.
Pointer variable sameness is determined based on the equality of both type and value. It works with pointers to objects, slices, maps and functions. For arrays, it always returns error.
func SameType ¶ added in v0.37.0
SameType checks that both arguments are of the same type. Returns nil if they are, otherwise it returns an error with a message indicating the expected and actual values.
Check uses reflect.TypeOf equality to determine the type.
func SliceSubset ¶
func SliceSubset[V comparable](want, have []V, opts ...any) error
SliceSubset checks the "have" is a subset "want". In other words, all values in the "want" slice must be in the "have" slice. Returns nil if it does, otherwise returns an error with a message indicating the expected and actual values.
func Smaller ¶ added in v0.22.0
func Smaller[T constraints.Ordered](want, have T, opts ...any) error
Smaller checks the "have" value is smaller than the "want" value. Returns nil if the condition is met, otherwise it returns an error with a message indicating the expected and actual values.
func SmallerOrEqual ¶ added in v0.22.0
func SmallerOrEqual[T constraints.Ordered](want, have T, opts ...any) error
SmallerOrEqual checks the "have" value is smaller or equal than the "want" value. Returns nil if the condition is met, otherwise it returns an error with a message indicating the expected and actual values.
func Time ¶
Time checks "want" and "have" dates are equal. Returns nil if they are, otherwise returns an error with a message indicating the expected and actual values.
The "want" and "have" may represent dates in the form of a string, int, int64 or time.Time. For string representations the [Options.TimeFormat] is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.
Example ¶
package main
import (
"fmt"
"time"
"github.com/ctx42/testing/pkg/check"
)
func main() {
want := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
have := time.Date(2025, 1, 1, 0, 1, 1, 0, time.UTC)
err := check.Time(want, have)
fmt.Println(err)
}
Output: expected equal dates: want: 2025-01-01T00:00:00Z have: 2025-01-01T00:01:01Z diff: -1m1s
func True ¶
True checks "have" is true. Returns nil if it's, otherwise it returns an error with a message indicating the expected and actual values.
func Type ¶
Type checks that the "src" can be type assigned to the pointer to the "target" (same as target, ok := src.(target)). Returns nil if it can be done, otherwise it returns an error. The "target" must be a pointer to a type.
func Wait ¶ added in v0.32.0
Wait waits for "fn" to return true but no longer then given timeout. By default, calls to "fn" are throttled with a default throttle set in [Options.WaitThrottle] - use WithWaitThrottle option to change it.
The "timeout" may represent duration in the form of a string, int, int64 or time.Duration.
func Within ¶
Within checks "want" and "have" dates are equal "within" given duration. Returns nil if they are, otherwise returns an error with a message indicating the expected and actual values.
The "want" and "have" may represent dates in the form of a string, int, int64 or time.Time. For string representations the [Options.TimeFormat] is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.
The "within" may represent duration in the form of a string, int, int64 or time.Duration.
func Zero ¶
Zero checks "have" is the zero value for its type. Returns nil if it is, otherwise, it returns an error with a message indicating the expected and actual values.
func Zone ¶
Zone checks "want" and "have" timezones are equal. Returns nil if they are, otherwise returns an error with a message indicating the expected and actual values.
Note nil time.Location is the same as time.UTC.
The "want" and "have" may represent timezones in the form of a string, nil (UTC), or time.Location.
Types ¶
type Checker ¶ added in v0.18.0
Checker is signature for generic check function comparing two arguments returning an error if they are not. The returned error might be one or more errors joined with errors.Join.
The options may be one of the Option instances or formatted string.
Example:
Checker("want", "have", "A%d", 42, WithTrail("type.field"))
func WithinChecker ¶ added in v0.18.0
WithinChecker is a partial application function for Within.
type Option ¶
Option represents a Checker option.
func WithComment ¶ added in v0.35.0
WithComment is a Checker option setting a comment to be added to all error messages.
func WithDumper ¶
WithDumper is Checker option setting dump.Config options.
func WithOptions ¶
WithOptions is a Checker option which passes all options.
func WithRecent ¶
WithRecent is a Checker option setting duration used to compare recent dates.
func WithSkipTrail ¶
WithSkipTrail is a Checker option setting trails to skip.
func WithTimeFormat ¶
WithTimeFormat is a Checker option setting time format when parsing dates.
func WithTrailChecker ¶
WithTrailChecker is a Checker option setting a custom checker for a given trail.
func WithTrailLog ¶
WithTrailLog is a Checker option turning on a collection of checked fields/elements/keys. The trails are added to the provided slice.
func WithTypeChecker ¶
WithTypeChecker is a Checker option setting custom checker for a type.
func WithWaitThrottle ¶ added in v0.32.0
WithWaitThrottle is a Checker option setting how calls to the test function should be throttled.
func WithZone ¶ added in v0.17.0
WithZone is a Checker option which specifies the timezone to apply to the "want" date before comparing times. It ensures consistent timezone handling for string-based date inputs. For time.Time values, it calls time.Time.In to adjust the timezone.
Example:
assert.Exact(t, "2000-01-02T02:04:05Z", have, check.WithZone(WAW))
In the above example the string date will be parsed then time.Time.In method will set its timezone.
type Options ¶
type Options struct {
// Dump configuration.
Dumper dump.Dump
// Time format when parsing time strings (default: [time.RFC3339]).
TimeFormat string
// See [WithZone].
Zone *time.Location
// Duration when comparing recent dates.
Recent time.Duration
// Field/element/key breadcrumb trail being checked.
Trail string
// List of visited trails.
// The skipped trails have "<skipped>" suffix.
TrailLog *[]string
// Custom checks to run for a given type.
TypeCheckers map[reflect.Type]Checker
// Custom checker for given trail.
TrailCheckers map[string]Checker
// List of trails to skip.
SkipTrails []string
// Skips all unexported fields during equality checks.
SkipUnexported bool
// See [WithCmpBaseTypes].
CmpSimpleType bool
// Option for [Increasing] allowing consecutive values to be equal.
IncreaseSoft bool
// Option for [Decreasing] allowing consecutive values to be equal.
DecreaseSoft bool
// Option for [Wait] throttling the calls to a test function.
WaitThrottle time.Duration
// Comment row for all error messages.
Comment string
// contains filtered or unexported fields
}
Options represent options used by Checker functions.
func DefaultOptions ¶
DefaultOptions returns default Options.
func WithCmpBaseTypes ¶ added in v0.16.0
WithCmpBaseTypes is a Checker option turning on simple base type comparisons.
During a normal operation, when comparing values with different types, the error is returned. Then this option is used, and both values have the same underlying simple type the values of that base type will be compared.
Simple types are defined as:
- reflect.Bool
- reflect.Int
- reflect.Int8
- reflect.Int16
- reflect.Int32
- reflect.Int64
- reflect.Uint
- reflect.Uint8
- reflect.Uint16
- reflect.Uint32
- reflect.Uint64
- reflect.Float32
- reflect.Float64
- reflect.Complex64
- reflect.Complex128
- reflect.String
Example:
// --- Given ---
type MyInt int
const MyIntValue MyInt = 42
m0 := map[string]any{"A": MyIntValue}
m1 := map[string]any{"A": 42}
// --- When ---
err := Equal(m0, m1, WithCmpBaseTypes)
// --- Then ---
assert.NoError(t, err)
func WithDecreasingSoft ¶ added in v0.22.0
WithDecreasingSoft is an option used by Decreasing check allowing consecutive values to be equal to each other.
func WithIncreasingSoft ¶ added in v0.22.0
WithIncreasingSoft is an option used by Increasing check allowing consecutive values to be equal to each other.
func WithSkipUnexported ¶ added in v0.6.0
WithSkipUnexported is a Checker option instructing equality checks to skip exported fields.
func (Options) ArrTrail ¶ added in v0.7.0
ArrTrail updates [Options.Trail] with slice or array index considering already existing trail.
Example trails:
arr[1] [1]
func (Options) LogTrail ¶ added in v0.7.0
LogTrail logs non-empty [Options.Trail] to [Options.TrailLog].
func (Options) MapTrail ¶ added in v0.7.0
MapTrail updates [Options.Trail] with trail of the map value considering already existing trails.
Example trails:
map[1] ["A"]map[1] [1]map["A"] field["A"]
func (Options) StructTrail ¶ added in v0.7.0
StructTrail updates [Options.Trail] with a struct type and/or field name considering an already existing trail.
Example trails:
Type.Field Type.Field.Field Type.Field[1].Field Type.Field["A"].Field