Documentation
¶
Overview ¶
Package check provides equality toolkit used by assert package.
Index ¶
- Constants
- Variables
- func After(date, mark any, opts ...Option) error
- func AfterOrEqual(date, mark any, opts ...Option) error
- func Before(date, mark any, opts ...Option) error
- func BeforeOrEqual(date, mark any, opts ...Option) error
- func ChannelWillClose[C any](within any, c <-chan C, opts ...Option) error
- func Contain(want, have string, opts ...Option) error
- func Count(count int, what, where any, opts ...Option) error
- func DirExist(pth string, opts ...Option) error
- func Duration(want, have any, opts ...Option) error
- func Empty(have any, opts ...Option) error
- func Epsilon[T constraints.Number](want, epsilon, have T, opts ...Option) error
- func Equal(want, have any, opts ...Option) error
- func Error(err error, opts ...Option) error
- func ErrorAs(want any, err error, opts ...Option) error
- func ErrorContain(want string, err error, opts ...Option) error
- func ErrorEqual(want string, err error, opts ...Option) error
- func ErrorIs(want, err error, opts ...Option) error
- func ErrorRegexp(want any, err error, opts ...Option) error
- func Exact(want, have any, opts ...Option) error
- func ExitCode(want int, err error, opts ...Option) error
- func False(have bool, opts ...Option) error
- func FieldName(ops Options, typeName string) func(fldName string) Option
- func Fields(want int, s any, opts ...Option) error
- func FileContain[T Content](want T, pth string, opts ...Option) error
- func FileExist(pth string, opts ...Option) error
- func Has[T comparable](want T, bag []T, opts ...Option) error
- func HasKey[K comparable, V any](key K, set map[K]V, opts ...Option) (V, error)
- func HasKeyValue[K, V comparable](key K, want V, set map[K]V, opts ...Option) error
- func HasNo[T comparable](want T, set []T, opts ...Option) error
- func HasNoKey[K comparable, V any](key K, set map[K]V, opts ...Option) error
- func JSON(want, have string, opts ...Option) error
- func Len(want int, have any, opts ...Option) (err error)
- func MapSubset[K comparable, V any](want, have map[K]V, opts ...Option) error
- func MapsSubset[K comparable, V any](want, have []map[K]V, opts ...Option) error
- func Nil(have any, opts ...Option) error
- func NoDirExist(pth string, opts ...Option) error
- func NoError(err error, opts ...Option) error
- func NoFileExist(pth string, opts ...Option) error
- func NoPanic(fn TestFunc, opts ...Option) error
- func NotContain(want, have string, opts ...Option) error
- func NotEmpty(have any, opts ...Option) error
- func NotEqual(want, have any, opts ...Option) error
- func NotNil(have any, opts ...Option) error
- func NotSame(want, have any, opts ...Option) error
- func NotZero(have any, opts ...Option) error
- func Panic(fn TestFunc, opts ...Option) error
- func PanicContain(want string, fn TestFunc, opts ...Option) error
- func PanicMsg(fn TestFunc, opts ...Option) (*string, error)
- func Recent(have any, opts ...Option) error
- func Regexp(want, have any, opts ...Option) error
- func RegisterTypeChecker(typ any, chk Checker)
- func Same(want, have any, opts ...Option) error
- func SliceSubset[V comparable](want, have []V, opts ...Option) error
- func Time(want, have any, opts ...Option) error
- func True(have bool, opts ...Option) error
- func Type(want, have any, opts ...Option) error
- func Within(want, within, have any, opts ...Option) error
- func Zero(have any, opts ...Option) error
- func Zone(want, have any, opts ...Option) error
- type Checker
- type Content
- type 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 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 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 ChannelWillClose ¶
ChannelWillClose checks channel will be closed "within" 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 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 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 constraints.Number](want, epsilon, have T, opts ...Option) error
Epsilon checks the difference between two numbers is within a given delta. Returns nil if it does, otherwise it returns an error with a message indicating the expected and actual values.
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 ...check.Option) 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 ...check.Option) 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 ...check.Option) 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 Has ¶
func Has[T comparable](want T, bag []T, opts ...Option) 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 ...Option) (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 ...Option) 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 ...Option) 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 ...Option) 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 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" elements. 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 ...Option) 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 ...Option) 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 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 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 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 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 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 SliceSubset ¶
func SliceSubset[V comparable](want, have []V, opts ...Option) 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 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 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.
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.
func WithinChecker ¶ added in v0.18.0
WithinChecker is a partial application function for Within.
type Option ¶
Option represents a Checker option.
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 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
// 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 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