should

package
v0.0.0-...-8ff35f7 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package should contains comparisons such as should.Equal to be used with the "go.chromium.org/luci/common/testing/truth" library.

Example:

import (
  "testing"
  "go.chromium.org/luci/common/testing/truth/assert"
  "go.chromium.org/luci/common/testing/truth/should"
)

func TestSomething(t *testing.T) {
    assert.That(t, something(), should.Equal("hello"))
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AlmostEqual

func AlmostEqual[T ~float32 | ~float64](target T, epsilon ...T) comparison.Func[T]

AlmostEqual returns a comparison Func which checks if a floating point value is within `|epsilon|` of `target`.

By default, this computes `epsilon` to be `math.Nextafter(1, 2) - 1` (or the 32 bit equivalent). This yields the next representable floating point value after `1` (effectively Float64frombits(Float64bits(x)+1)).

You may optionally pass a (single, positive) explicit epsilon value.

func BeBetween

func BeBetween[T constraints.Ordered](lower, upper T) comparison.Func[T]

BeBetween returns a comparison.Func which checks if an ordered value sorts between a lower and upper bound.

func BeBetweenOrEqual

func BeBetweenOrEqual[T constraints.Ordered](lower, upper T) comparison.Func[T]

BeBetweenOrEqual returns a comparison.Func which checks if an ordered value sorts between (or equal to) a lower and upper bound.

func BeBlank

func BeBlank(actual string) *failure.Summary

BeBlank implements comparison.Func[string] and asserts that `actual` contains only whitespace chars.

func BeEmpty

func BeEmpty(actual any) *failure.Summary

BeEmpty is a Comparison which expects `actual` to have length 0.

Supports all values which work with the `len()` builtin function.

func BeFalse

func BeFalse(actual bool) *failure.Summary

BeFalse is a comparison.Func[bool] which asserts that the actual value is `false`.

func BeGreaterThan

func BeGreaterThan[T constraints.Ordered](lower T) comparison.Func[T]

BeGreaterThan returns a comparison.Func which checks if an ordered value is greater than a lower bound.

func BeGreaterThanOrEqual

func BeGreaterThanOrEqual[T constraints.Ordered](lower T) comparison.Func[T]

BeGreaterThanOrEqual returns a comparison.Func which checks if an ordered value is greater than (or equal to) a lower bound.

func BeIn

func BeIn[T comparable](collection ...T) comparison.Func[T]

BeIn returns a Comparison which checks to see if `actual` is equal to any of the entries in `collection`.

Comparison is done via simple equality check.

func BeLessThan

func BeLessThan[T constraints.Ordered](upper T) comparison.Func[T]

BeLessThan returns a comparison.Func which checks if an ordered value sorts between (or equal to) a lower and upper bound.

func BeLessThanOrEqual

func BeLessThanOrEqual[T constraints.Ordered](upper T) comparison.Func[T]

BeLessThanOrEqual returns a comparison.Func which checks if an ordered value sorts between (or equal to) a lower and upper bound.

func BeNaN

func BeNaN[T ~float32 | ~float64](actual T) *failure.Summary

BeNaN checks that `actual` is a floating point NaN.

func BeNil

func BeNil(actual any) *failure.Summary

BeNil implements comparison.Func[any] and asserts that `actual` is a nillable type (like a pointer, slice, channel, etc) and is nil. This will also accept untyped nils (e.g. `any(nil)`).

Note that this is a stricter form than should.BeZero.

func BeSorted

func BeSorted[T constraints.Ordered](actual []T) (fail *failure.Summary)

BeSorted is a comparison.Func which ensures that a given slice is in sorted order.

func BeTrue

func BeTrue(actual bool) *failure.Summary

BeTrue is a comparison.Func[bool] which asserts that the actual value is `true`.

func BeZero

func BeZero(actual any) *failure.Summary

BeZero implements comparison.Func[any] and asserts that `actual` is a zero value (by Go's definition of zero values, e.g. empty strings, structs, nil pointers, etc).

func Contain

func Contain[T comparable](target T) comparison.Func[[]T]

Contain returns a Comparison which checks to see if `actual` contains `item`.

Comparison is done via simple equality check.

func ContainKey

func ContainKey[K comparable](key K) comparison.Func[any]

ContainKey returns a comparison.Func which checks to see if some `map[~K]?` contains a given key.

Example: `Assert(t, someMap, should.ContainKey("someKey"))`

NOTE: Go doesn't have something like a `rest` type where we could express that this is an `comparison.Func[map[K]?]` so we have to accept `any` here.

func ContainMatch

func ContainMatch[T comparable](target T, opts ...cmp.Option) comparison.Func[[]T]

ContainMatch returns a Comparison which checks to see if `actual` contains `item`.

Comparison is done via the same algorithm as Match.

func ContainSubstring

func ContainSubstring(substr string) comparison.Func[string]

ContainSubstring returns a comparison.Func which checks to see if a string contains `substr`.

func Equal

func Equal[T comparable](expected T) comparison.Func[T]

Equal checks whether two objects are equal, as determined by Go's `==` operator.

Notably, NaN (the float value) cannot compare to itself. This Comparison implementation will return a specific error in the event that `expected` and `actual` are NaN.

func ErrLike

func ErrLike(stringOrError any) comparison.Func[error]

ErrLike returns a Comparison[error] which will check that `actual` is:

  • `nil`, if `stringOrError` is nil.
  • errors.Is(actual, stringOrError) if `stringOrError` is `error`.
  • strings.Contains(actual.Error(), stringOrError) if `stringOrError` is `string.

Examples

err := funcReturnsErr()
Assert(t, err, should.ErrLike("bad value"))  // strings.Contains
Assert(t, err, should.ErrLike(ErrBadValue))  // errors.Is
Assert(t, err, should.ErrLike(nil))          // err == nil

func ErrLikeError

func ErrLikeError(target error) comparison.Func[error]

ErrLikeError checks whether your error errors.Is another error.

nil is an acceptable target here indicating the absence of an error.

func ErrLikeString

func ErrLikeString(substring string) comparison.Func[error]

ErrLikeString returns failure when the stringified error is not a substring of the target. Additionally, when the substring argument is empty, ErrLikeString always returns failure because the empty string is a subset of every string and you probably made a mistake.

func HappenAfter

func HappenAfter(target time.Time) comparison.Func[time.Time]

HappenAfter returns a comparison.Func which checks that some actual time happened after 'target'.

func HappenBefore

func HappenBefore(target time.Time) comparison.Func[time.Time]

HappenBefore returns a comparison.Func which checks that some actual time happened before 'target'.

func HappenOnOrAfter

func HappenOnOrAfter(target time.Time) comparison.Func[time.Time]

HappenOnOrAfter returns a comparison.Func which checks that some actual time happened on or after 'target'.

func HappenOnOrBefore

func HappenOnOrBefore(target time.Time) comparison.Func[time.Time]

HappenOnOrBefore returns a comparison.Func which checks that some actual time happened on or before 'target'.

func HappenOnOrBetween

func HappenOnOrBetween(lower, upper time.Time) comparison.Func[time.Time]

HappenOnOrBetween returns a comparison.Func which checks that some actual time happened on or after 'lower' and on or after 'upper'.

lower must be <= upper or this will panic.

func HappenWithin

func HappenWithin(delta time.Duration, target time.Time) comparison.Func[time.Time]

HappenWithin returns a comparison.Func which checks that some actual time happened within 'delta' of 'target'.

func HaveLength

func HaveLength(expected int) comparison.Func[any]

HaveLength returns a Comparison which expects `actual` to have the given length.

Supports all values which work with the `len()` builtin function.

func HavePrefix

func HavePrefix(prefix string) comparison.Func[string]

HavePrefix returns a comparison.Func which checks to see if a string ends with `prefix`.

func HaveSuffix

func HaveSuffix(suffix string) comparison.Func[string]

HaveSuffix returns a comparison.Func which checks to see if a string ends with `suffix`.

func HaveType

func HaveType[T any](actual T) *failure.Summary

HaveType checks that the underlying type of `actual` is T.

Use with {assert,check}.Loosely to see if some interface value has the specified type:

assert.Loosely(t, actual, should.HaveType[expectedType])

This works because assert.Loosely will ensure that `actual` can cast losslessly to `expectedType`, and display an error if this fails.

func Match

func Match[T any](expected T, opts ...cmp.Option) comparison.Func[T]

Match returns a comparison.Func which checks if the actual value matches `expected`.

Semblance is computed with "github.com/google/go-cmp/cmp", and this function accepts additional cmp.Options to allow for handling of different types/fields/filtering proto Message semantics, etc.

For convenience, `opts` implicitly includes:

  • "google.golang.org/protobuf/testing/protocmp".Transform()
  • A direct comparison of protoreflect.Descriptor types. These are documented as being comparable with `==`, but by default `cmp` will recurse into their guts.
  • A direct comparison of reflect.Type interfaces.

This is done via the go.chromium.org/luci/common/testing/registry package, which also allows process-wide registration of additional default cmp.Options. It is recommended to register cmp.Options in TestMain for any types that your package tests which contain unexported fields, or other internal details. Note that cmp.Diff implicitly will use `X.Equal(X)` methods for any types which implement them as methods, so this may be a good first thing to implement.

It is recommended that you use should.Equal when comparing primitive types.

func MatchIn

func MatchIn[T comparable](collection []T, opts ...cmp.Option) comparison.Func[T]

MatchIn returns a Comparison which checks to see if `actual` Matches any of the entries in `collection`.

Comparison is done via the same mechanism as should.Match.

func MatchRegexp

func MatchRegexp(re string) comparison.Func[string]

MatchRegexp returns a comparison.Func[string] that asserts that `actual` matches the given regexp `re`.

func NotBeBlank

func NotBeBlank(actual string) *failure.Summary

NotBeBlank implements comparison.Func[string] and asserts that `actual` contains at least one non-whitespace char.

func NotBeEmpty

func NotBeEmpty(actual any) *failure.Summary

NotBeEmpty is a Comparison which expects `actual` to have a non-0 length.

Supports all values which work with the `len()` builtin function.

func NotBeIn

func NotBeIn[T comparable](collection ...T) comparison.Func[T]

NotBeIn returns a Comparison which checks to see if `actual` is not equal to any of the entries in `collection`.

Comparison is done via simple equality check.

func NotBeNaN

func NotBeNaN[T ~float32 | ~float64](actual T) *failure.Summary

NotBeNaN checks that `actual` is a floating point NaN.

func NotBeNil

func NotBeNil(actual any) *failure.Summary

NotBeNil implements comparison.Func[any] and asserts that `actual` is a nillable type (like a pointer, slice, channel, etc) and is not nil.

Note that this will NOT accept any("hello"), because `string` is not a nillable type. If you just care that `actual` has SOME value at all, use NotBeNilInterface.

Note that this is a slightly stricter form than should.NotBeZero.

func NotBeNilInterface

func NotBeNilInterface(actual any) *failure.Summary

NotBeNilInterface implements comparison.Func[any] and asserts that `actual` contains ANY value.

Note that this will accept a typed-nil e.g. `any((*Type)(nil)`, because this interface is not, itself, nil. If you want to check the value contained in the interface for non-nil-ness, use NotBeNil.

func NotBeZero

func NotBeZero(actual any) *failure.Summary

NotBeZero implements comparison.Func[any] and asserts that `actual` is a non-zero value (by Go's definition of zero values, e.g. empty strings, structs, nil pointers, etc).

func NotContain

func NotContain[T comparable](target T) comparison.Func[[]T]

NotContain returns a Comparison which checks to see if `actual` does not contain `item`.

Comparison is done via simple equality check.

func NotContainKey

func NotContainKey[K comparable](key K) comparison.Func[any]

NotContainKey returns a comparison.Func which checks to see if some `map[~K]?` does not contain a given key.

Example: `Assert(t, someMap, should.NotContainKey("someKey"))`

NOTE: Go doesn't have something like a `rest` type where we could express that this is an `comparison.Func[map[K]?]` so we have to accept `any` here.

func NotContainSubstring

func NotContainSubstring(substr string) comparison.Func[string]

NotContainSubstring returns a comparison.Func which checks to see if a string does not contain `substr`.

func NotEqual

func NotEqual[T comparable](expected T) comparison.Func[T]

NotEqual checks whether two objects are equal, as determined by Go's `!=` operator.

Notably, NaN (the float value) cannot compare to itself. This Comparison implementation will return a specific error in the event that `expected` and `actual` are NaN.

func NotHavePrefix

func NotHavePrefix(prefix string) comparison.Func[string]

NotHavePrefix returns a comparison.Func which checks to see if a string does not end with `prefix`.

func NotHaveSuffix

func NotHaveSuffix(suffix string) comparison.Func[string]

NotHaveSuffix returns a comparison.Func which checks to see if a string does not end with `suffix`.

func NotMatch

func NotMatch[T any](expected T, opts ...cmp.Option) comparison.Func[T]

NotMatch returns a comparison.Func which checks if the actual value doesn't match `expected`.

Semblance is computed with "github.com/google/go-cmp/cmp", and this function accepts additional cmp.Options to allow for handling of different types/fields/filtering proto Message semantics, etc.

For convenience, `opts` implicitly includes:

  • "google.golang.org/protobuf/testing/protocmp".Transform()
  • A direct comparison of protoreflect.Descriptor types. These are documented as being comparable with `==`, but by default `cmp` will recurse into their guts.
  • A direct comparison of reflect.Type interfaces.

This is done via the go.chromium.org/luci/common/testing/registry package, which also allows process-wide registration of additional default cmp.Options. It is recommended to register cmp.Options in TestMain for any types that your package tests which contain unexported fields, or other internal details. Note that cmp.Diff implicitly will use `X.Equal(X)` methods for any types which implement them as methods, so this may be a good first thing to implement.

It is recommended that you use should.NotEqual when comparing primitive types.

func NotPanic

func NotPanic(fn func()) *failure.Summary

NotPanic checks whether a function doesn't panic.

func NotResemble deprecated

func NotResemble[T any](expected T) comparison.Func[T]

NotResemble returns a comparison.Func which checks if the actual value doesn't 'resemble' `expected`, but implicitly compares unexported fields for compatibility with goconvey's ShouldNotResemble check.

Deprecated: Use should.NotMatch instead, which does not automatically add AllowUnexported(expected). should.NotMatch also allows specifying your own/ auxilliary cmp.Options globally and locally, for more advanced interaction with cmp.Diff.

Semblance is computed with "github.com/google/go-cmp/cmp", and this function automatically adds the following cmp.Options to match behavior of coconvey:

  • "google.golang.org/protobuf/testing/protocmp".Transform()
  • A direct comparison of protoreflect.Descriptor types. These are documented as being comparable with `==`, but by default `cmp` will recurse into their guts.
  • A direct comparison of reflect.Type interfaces.
  • "github.com/google/go-cmp/cmp".AllowUnexported(expected) (if `expected` has an underlying struct type after peeling off slices, pointers, etc.)

It is recommended that you use should.NotEqual when comparing primitive types.

func Panic

func Panic(fn func()) *failure.Summary

Panic checks whether a function panics.

func PanicLike deprecated

func PanicLike(target any) comparison.Func[func()]

PanicLike checks whether a function panics like a string or an error, which is cool.

Deprecated: use PanicLikeString or PanicLikeError depending on the type.

func PanicLikeError

func PanicLikeError(target error) comparison.Func[func()]

PanicLikeError checks if something panics like a given error.

func PanicLikeString

func PanicLikeString(substring string) comparison.Func[func()]

PanicLikeString checks if something panics like with a string or error that matches target.

It fails when you panic with anything that is NOT a string or an error.

func Resemble deprecated

func Resemble[T any](expected T) comparison.Func[T]

Resemble returns a comparison.Func which checks if the actual value 'resembles' `expected`, but implicitly compares unexported fields for compatibility with goconvey's ShouldResemble check.

Deprecated: Use should.Match instead, which does not automatically add AllowUnexported(expected). should.Match also allows specifying your own auxilliary cmp.Options globally and locally, for more advanced interaction with cmp.Diff.

Semblance is computed with "github.com/google/go-cmp/cmp", and this function automatically adds the following cmp.Options to match behavior of coconvey:

  • "google.golang.org/protobuf/testing/protocmp".Transform()
  • A direct comparison of protoreflect.Descriptor types. These are documented as being comparable with `==`, but by default `cmp` will recurse into their guts.
  • A direct comparison of reflect.Type interfaces.
  • "github.com/google/go-cmp/cmp".AllowUnexported(expected) (if `expected` has an underlying struct type after peeling off slices, pointers, etc.)

It is recommended that you use should.Equal when comparing primitive types.

func StaticallyHaveSameTypeAs

func StaticallyHaveSameTypeAs[T any](expected T) comparison.Func[T]

StaticallyHaveSameTypeAs checks if two values statically have the same type.

Like HaveType, it will fail to compile if the types are incompatible.

func UnwrapToErrStringLike

func UnwrapToErrStringLike(substring string) comparison.Func[error]

UnwrapToErrStringLike returns failure when unwrapping the error repeatedly doesn't yield an error whose text contains `substring`.

This is useful when dealing with MultiError types which implement `Unwrap() []error`, but whose Error function summarize the error.

Strongly consider using a real target error instead so that this works with `errors.Is` in typical code, e.g.:

var ErrMyTargetErr = errors.New("some description")

...
return ..., MultiError{
  ...,
  errors.Annotate(ErrMyTargetErr, "some extra info").Error(),
}

...
if errors.Is(err, ErrMyTargetErr) {
  // do something
}

Types

This section is empty.

Jump to

Keyboard shortcuts

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