be

package module
v1.0.0-rc.4 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2026 License: MIT Imports: 12 Imported by: 0

README ΒΆ

Expect(πŸ‘¨πŸΌβ€πŸ’»).To(Be(πŸš€))

License Go Reference

expectto/be is a Golang package that offers a substantial collection of Be matchers. Every Be matcher is compatible with both Ginkgo/Gomega and Gomock. Where possible, arguments of matchers can be either finite values or matchers (Be/Gomega/Gomock).
Employing expectto/be matchers enables you to create straightforward, readable, and maintainable unit or integration tests in Golang. Tasks such as testing HTTP requests, validating JSON responses, and more become remarkably comprehensive and straightforward.

Table of Contents

Installation

To use Be in your Golang project, simply import it:

import "github.com/expectto/be"

Example

Consider the following example demonstrating the usage of expectto/be's HTTP request matchers:

req, err := buildRequestForServiceFoo()
Expect(err).To(Succeed())

// Matching an HTTP request
Expect(req).To(be_http.Request(
    // Matching the URL
    be_http.HavingURL(be_url.URL(
        be_url.WithHttps(),
        be_url.HavingHost("example.com"),
        be_url.HavingPath("/path"),
        be_url.HavingSearchParam("status", "active"),
        be_url.HavingSearchParam("v", be_reflected.AsNumericString()),
        be_url.HavingSearchParam("q", "Hello World"),
    )),

    // Matching the HTTP method
    be_http.POST(),

    // Matching the request's context
    be_http.HavingCtx(
        be_ctx.CtxWithDeadline(be_time.LaterThan(time.Now().Add(30*time.Minute))),
        be_ctx.CtxWithValue("foobar", 100),
    ),

    // Matching the request body using JSON matchers
    be_http.HavingBody(
        be.JSON(
            be_json.JsonAsReader,
            be_json.HaveKeyValue("hello", "world"),
            // NOTE: JSON numbers decode to float64, so use AsFloat (not AsInteger) here
            be_json.HaveKeyValue("n", be_reflected.AsFloat(), be_math.GreaterThan(10)),
            be_json.HaveKeyValue("ids", be_reflected.AsSliceOf[string]()),
            Not(be_json.HaveKeyValue("deleted_field")), // not to have a deleted field
            
            be_json.HaveKeyValue("email", be_string.ValidEmail(), HaveSuffix("@tests.com")),

            // "details":[{"key":"foo"},{"key":"bar"}]
            be_json.HaveKeyValue("details", And(
                be_reflected.AsObjects(),
                be.HaveLength(be_math.GreaterThan(2)),
                ContainElements(
                    be_json.HaveKeyValue("key", "foo"),
                    be_json.HaveKeyValue("key", "bar"),
                ),
            )),
        ),
    ),

	// Matching HTTP headers 
    be_http.HavingHeader("X-Custom", "Hey-There"), 
    be_http.HavingHeader("Authorization", 
        be_string.MatchTemplate("Bearer {{jwt}}", 
        be_string.V("jwt", 
            be_jwt.Token(
                be_jwt.Valid(), 
                be_jwt.HavingClaim("name", "John Doe"), 
            ), 
        ), 
    ),
))      

Test framework integration

be matchers are framework-agnostic. The core github.com/expectto/be module imports no test framework β€” pick how you run assertions:

Standard library (no extra deps):

import "github.com/expectto/be"

be.Expect(t, n).To(be_math.GreaterThan(10))   // soft fail (assert-style)
be.Require(t, n).To(be_math.GreaterThan(10))  // hard fail (require-style)
be.Expect(t, s).NotTo(be_string.EmptyString())

Ginkgo / Gomega: every be matcher already satisfies gomega's matcher interface, so use it directly inside Expect(...).To(...).

Testify (assert / require): opt in via the separate driver module (keeps testify out of your deps unless you want it). Install it with @latest (the submodule shares version numbers with the core module, which confuses go get <pkg>@<version>):

go get github.com/expectto/be/x/testify@latest
import betestify "github.com/expectto/be/x/testify"

betestify.Assert(t, n, be_math.GreaterThan(10))
betestify.Require(t, s, be_string.NonEmptyString())

Note the argument order vs testify: assert.Equal(t, want, got) becomes betestify.Assert(t, got, be.Eq(want)) β€” the actual value comes first.

Mocking

be matchers also work as mock argument matchers:

Gomock: every be matcher already satisfies gomock.Matcher, so pass it directly:

mockObj.EXPECT().Do(be_math.GreaterThan(10)).Return("ok")

Testify mock / mockery: wrap with Mock (works for hand-written and mockery-generated mocks):

import betestify "github.com/expectto/be/x/testify"

svc.On("Do", betestify.Mock(be_math.GreaterThan(10))).Return("ok")

Matchers

Core Be

πŸ“¦ be provides a set of core matchers for common testing scenarios.
See detailed docs

Core matchers:

Always, Never, All, Any, Eq, Not, HaveLength, Dive, DiveAny, DiveFirst

Everyday matchers:

Nil, NotNil, True, False, Eq, Ne, Empty, NotEmpty, Succeed, HaveOccurred, MatchError, Panic, NotPanic, ContainElement, ContainElements, ContainSubstring, HaveKey, HaveKeyWithValue

be_reflected

πŸ“¦ be_reflected provides Be matchers that use reflection, enabling expressive assertions on values' reflect kinds and types.
See detailed docs

General Matchers based on reflect.Kind:

AsKind, AsFunc, AsChan, AsPointer, AsFinalPointer, AsStruct, AsPointerToStruct, AsSlice, AsPointerToSlice, AsSliceOf, AsMap, AsPointerToMap, AsObject, AsObjects, AsPointerToObject

Data Type Matchers based on reflect.Kind

AsString, AsBytes, AsNumeric, AsNumericString, AsInteger, AsIntegerString, AsFloat, AsFloatishString,

Interface Matchers based on reflect.Kind

AsReader,AsStringer

Matchers based on types compatibility:

AssignableTo, Implementing

be_math

πŸ“¦ be_math provides Be matchers for mathematical operations.
See detailed docs

Matchers on math:

GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, Approx, InRange, Odd, Even, Negative, Positive, Zero, Integral, DivisibleBy

Shortcut aliases for math matchers:

Gt, Gte, Lt, Lte

be_string

πŸ“¦ be_string provides Be matchers for string-related assertions.
See detailed docs

Matchers on strings

NonEmptyString, EmptyString, Alpha, Numeric, AlphaNumeric, AlphaNumericWithDots, Float, Titled, LowerCaseOnly, MatchWildcard, ValidEmail

Template matchers

MatchTemplate

be_time

πŸ“¦ be_time provides Be matchers on time.Time.
See detailed docs

Time Matchers

LaterThan, LaterThanEqual, EarlierThan, EarlierThanEqual, Eq, Approx,
SameExactMilli, SameExactSecond, SameExactMinute, SameExactHour,
SameExactDay, SameExactWeekday, SameExactWeek, SameExactMonth,
SameSecond, SameMinute, SameHour, SameDay, SameYearDay,
SameWeek, SameMonth, SameYear, SameTimzone, SameOffset, IsDST

be_jwt

πŸ“¦ be_jwt provides Be matchers for handling JSON Web Tokens (JWT). It includes matchers for transforming and validating JWT tokens. Matchers corresponds to specific golang jwt implementation.
See detailed docs

Transformers for JWT matching:

TransformSignedJwtFromString, TransformJwtFromString

Matchers on JWT:

Token, Valid, HavingClaims, HavingClaim, HavingMethodAlg, SignedVia

be_url

πŸ“¦ be_url provides Be matchers on url.URL.
See detailed docs

Transformers for URL Matchers:

TransformUrlFromString, TransformSchemelessUrlFromString

URL Matchers:

URL, HavingHost, HavingHostname, HavingScheme, NotHavingScheme, WithHttps, WithHttp, HavingPort, NotHavingPort, HavingPath, HavingRawQuery, HavingSearchParam, HavingMultipleSearchParam, HavingUsername, HavingUserinfo, HavingPassword

be_ctx

πŸ“¦ be_ctx provides Be matchers on context.Context.
See detailed docs

Context Matchers:

Ctx, CtxWithValue, CtxWithDeadline, CtxWithError

be_json

πŸ“¦ be_json provides Be matchers for expressive assertions on JSON.
See detailed docs

JSON Matchers:

Matcher, HaveKeyValue

be_http

πŸ“¦ be_http provides Be matchers for expressive assertions on http.Request.
See detailed docs

Matchers on HTTP:

Request, HavingMethod,
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, CONNECT, TRACE,
HavingURL, HavingBody, HavingHost, HavingProto, HavingCtx, HavingHeader, HavingHeaders

Contributing

Be welcomes contributions! Feel free to open issues, suggest improvements, or submit pull requests. Contribution guidelines for this project

License

This project is licensed under the MIT License.

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var Ctx = be_ctx.Ctx

Ctx is an alias for be_ctx.Ctx

View Source
var HttpRequest = be_http.Request

HttpRequest is an alias for be_http.Request matcher

JSON is an alias for be_json.JSON matcher

View Source
var JwtToken = be_jwt.Token

JwtToken is an alias for be_jwt.Token matcher

View Source
var StringAsTemplate = be_string.MatchTemplate

StringAsTemplate is an alias for be_string.MatchTemplate matcher

View Source
var URL = be_url.URL

URL is an alias for be_url.URL matcher

Functions ΒΆ

func All ΒΆ

func All(ms ...any) types.BeMatcher

All is like gomega.And()

func Always ΒΆ

func Always() types.BeMatcher

Always does always match

func Any ΒΆ

func Any(ms ...any) types.BeMatcher

Any is like gomega.Or()

func ContainElement ΒΆ

func ContainElement(element any) types.BeMatcher

ContainElement succeeds if actual (a slice, array or map) contains an element that matches the given value or matcher.

func ContainElements ΒΆ

func ContainElements(elements ...any) types.BeMatcher

ContainElements succeeds if actual contains all of the given elements (each may be a value or a matcher), in any order.

func ContainSubstring ΒΆ

func ContainSubstring(substr string) types.BeMatcher

ContainSubstring succeeds if actual is a string containing the given substring. (For slices/arrays/maps use ContainElement.)

func Dive ΒΆ added in v0.2.0

func Dive(matcher any) types.BeMatcher

Dive applies the given matcher to each (every) element of a slice or array, or to each value of a map. Note: Dive is very close to gomega.HaveEach

func DiveAny ΒΆ added in v0.2.0

func DiveAny(matcher any) types.BeMatcher

DiveAny applies the given matcher to each element and succeeds in case if it succeeds at least at one item

func DiveFirst ΒΆ added in v0.2.0

func DiveFirst(matcher any) types.BeMatcher

DiveFirst applies the given matcher to the first element of the given slice

func DiveNth ΒΆ added in v0.2.2

func DiveNth(n int, matcher any) types.BeMatcher

DiveNth applies the given matcher to the nth element of the given slice

func Empty ΒΆ

func Empty() types.BeMatcher

Empty succeeds if actual is empty: a zero-length string, slice, array, map or channel (like gomega.BeEmpty).

func Eq ΒΆ

func Eq(expected any) types.BeMatcher

Eq is like gomega.Equal()

func False ΒΆ

func False() types.BeMatcher

False succeeds if actual is the boolean false.

func HaveKey ΒΆ

func HaveKey(key any) types.BeMatcher

HaveKey succeeds if actual (a map) has a key matching the given value or matcher.

func HaveKeyWithValue ΒΆ

func HaveKeyWithValue(key, value any) types.BeMatcher

HaveKeyWithValue succeeds if actual (a map) has the given key with a matching value.

func HaveLength ΒΆ

func HaveLength(args ...any) types.BeMatcher

HaveLength is like gomega.HaveLen() HaveLength succeeds if the actual value has a length that matches the provided conditions. It accepts either a count value or one or more Gomega matchers to specify the desired length conditions.

func HaveOccurred ΒΆ

func HaveOccurred() types.BeMatcher

HaveOccurred succeeds if actual is a non-nil error.

func MatchError ΒΆ

func MatchError(expected any) types.BeMatcher

MatchError succeeds if actual is an error matching expected, which may be:

  • a target error (compared with errors.Is),
  • a string (compared against err.Error()),
  • a matcher applied to the error.

func Ne ΒΆ

func Ne(expected any) types.BeMatcher

Ne succeeds if actual is NOT equal to expected (the negation of Eq).

func Never ΒΆ

func Never(err error) types.BeMatcher

Never does never succeed (does always fail)

func Nil ΒΆ

func Nil() types.BeMatcher

Nil succeeds if actual is nil. It is typed-nil aware (a nil *T inside an interface matches), unlike a bare `== nil` comparison.

func Not ΒΆ

func Not(expected any) types.BeMatcher

Not is like gomega.Not()

func NotEmpty ΒΆ

func NotEmpty() types.BeMatcher

NotEmpty succeeds if actual is not empty.

func NotNil ΒΆ

func NotNil() types.BeMatcher

NotNil succeeds if actual is not nil.

func NotPanic ΒΆ

func NotPanic() types.BeMatcher

NotPanic succeeds if actual is a func() that does not panic when invoked.

func Panic ΒΆ

func Panic() types.BeMatcher

Panic succeeds if actual is a func() that panics when invoked.

func Succeed ΒΆ

func Succeed() types.BeMatcher

Succeed succeeds if actual is a nil error. Intended for error values:

be.Expect(t, err).To(be.Succeed())

func True ΒΆ

func True() types.BeMatcher

True succeeds if actual is the boolean true.

Types ΒΆ

type Expectation ΒΆ

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

Expectation is a TestingT-bound assertion produced by Expect or Require.

func Expect ΒΆ

func Expect(t TestingT, actual any) *Expectation

Expect begins a soft assertion: a failure is reported via Errorf and the test continues (assert-style).

func Require ΒΆ

func Require(t TestingT, actual any) *Expectation

Require begins a hard assertion: the first failure stops the test via Fatalf (require-style).

func (*Expectation) NotTo ΒΆ

func (e *Expectation) NotTo(matcher any, msgAndArgs ...any) bool

NotTo asserts that actual does NOT satisfy the matcher. An optional message provides failure context (see To).

func (*Expectation) To ΒΆ

func (e *Expectation) To(matcher any, msgAndArgs ...any) bool

To asserts that actual satisfies the matcher. The matcher may be a be/gomega/ gomock matcher or a raw value (wrapped via Psi, like the rest of be). An optional message β€” a format string plus args, or plain values β€” is prepended to the failure output for context. Returns true on success.

func (*Expectation) ToNot ΒΆ

func (e *Expectation) ToNot(matcher any, msgAndArgs ...any) bool

ToNot is an alias for NotTo.

type TestingT ΒΆ

type TestingT interface {
	Helper()
	Errorf(format string, args ...any)
	Fatalf(format string, args ...any)
}

TestingT is the minimal subset of *testing.T the native driver needs. *testing.T satisfies it; tests can supply a fake. Mirrors testify's approach so the runner never imports the heavyweight `testing` package contract.

Directories ΒΆ

Path Synopsis
Package be_ctx provides Be matchers on context.Context
Package be_ctx provides Be matchers on context.Context
Package be_http provides matchers for url.Request TODO: more detailed documentation here is required
Package be_http provides matchers for url.Request TODO: more detailed documentation here is required
Package be_json provides Be matchers for expressive assertions on JSON TODO: more detailed explanation what is considered to be JSON here
Package be_json provides Be matchers for expressive assertions on JSON TODO: more detailed explanation what is considered to be JSON here
Package be_jwt provides Be matchers for handling JSON Web Tokens (JWT).
Package be_jwt provides Be matchers for handling JSON Web Tokens (JWT).
Package be_math provides Be matchers for mathematical operations
Package be_math provides Be matchers for mathematical operations
Package be_reflected provides Be matchers that use reflection, enabling expressive assertions on values' reflect kinds and types.
Package be_reflected provides Be matchers that use reflection, enabling expressive assertions on values' reflect kinds and types.
Package be_string provides Be matchers for string-related assertions.
Package be_string provides Be matchers for string-related assertions.
Package be_time provides Be matchers on time.Time
Package be_time provides Be matchers on time.Time
Package be_url provides Be matchers on url.URL
Package be_url provides Be matchers on url.URL
internal
beformat
Package beformat renders matcher failure messages in a compact, framework-native form.
Package beformat renders matcher failure messages in a compact, framework-native form.
psi
Package psi contains helpers that extends gomega library Name psi stands for previous letter from Omega (as we want to have a name that is close to gomega, but not to be a gomega)
Package psi contains helpers that extends gomega library Name psi stands for previous letter from Omega (as we want to have a name that is close to gomega, but not to be a gomega)
psi_matchers
Package psi_matchers is a package that contains core matchers required Psi() to work properly
Package psi_matchers is a package that contains core matchers required Psi() to work properly
testing/mocks
Code generated by MockGen.
Code generated by MockGen.
Package options declares options to be used in customizeable matchers Note: Options of ALL `be_*` matchers are stored here, in a separate package `options`.
Package options declares options to be used in customizeable matchers Note: Options of ALL `be_*` matchers are stored here, in a separate package `options`.
x
belint module
mock module
testify module

Jump to

Keyboard shortcuts

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