be

package module
v1.0.0-rc.6 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). Two equivalent spellings — a fluent one and a flat, testify-style one — both backed by the same engine, both driven by the stdlib *testing.T:

import "github.com/expectto/be"

// fluent (ginkgo/gomega-flavored)
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())

// flat (testify-flavored)
be.AssertThat(t, n, be_math.GreaterThan(10))     // soft fail (assert-style)
be.RequireThat(t, s, be_string.NonEmptyString()) // hard fail (require-style)

Already on testify? Keep your assert/require calls and reach for be only where a matcher earns its keep — be.AssertThat / be.RequireThat are the drop-in slots (no extra dependency):

assert.Equal(t, want, got)          // testify, as usual
be.AssertThat(t, got, be.Eq(want))  // be — and now `got` can face any matcher,
                                    // e.g. be_url.URL(be_url.HavingHost("x"), ...)

The subject comes first and the expected value lives inside the matcher (be.Eq(want)), so — unlike testify's Equal(t, want, got) — there's no want/got order to memorize or get wrong.

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

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 MatchedBy (works for hand-written and mockery-generated mocks) — the matcher equivalent of testify's own mock.MatchedBy. This is the one place you need the separate x/mock module (it's what keeps testify out of the core deps); 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/mock@latest
import bemock "github.com/expectto/be/x/mock"

svc.On("Do", bemock.MatchedBy(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, Identical, NotIdentical, Via, 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, Values, HavingHost, HavingHostname, HavingScheme, NotHavingScheme, WithHttps, WithHttp, HavingPort, NotHavingPort, HavingPath, HavingRawQuery, HavingSearchParam, NotHavingSearchParam, 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 AssertThat

func AssertThat(t TestingT, actual, matcher any, msgAndArgs ...any) bool

AssertThat is the flat, testify-style spelling of Expect(t, actual).To(matcher): a soft assertion that reports via Errorf and lets the test continue. It is the drop-in for testify's assert when you want a be matcher:

assert.Equal(t, want, got)          // testify
be.AssertThat(t, got, be.Eq(want))  // be — and now `got` can face any matcher

The subject (actual) comes first and the expected value lives inside the matcher, so unlike testify's Equal there is no want/got order to get wrong. An optional message provides failure context (see To). Returns true on success.

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 Identical

func Identical(expected any) types.BeMatcher

Identical succeeds if actual is identical to expected using Go's == operator (pointer identity for pointers). Like gomega.BeIdenticalTo / testify's Same.

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 NotIdentical

func NotIdentical(expected any) types.BeMatcher

NotIdentical succeeds if actual is NOT identical to expected (the negation of Identical). Like testify's NotSame.

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 RequireThat

func RequireThat(t TestingT, actual, matcher any, msgAndArgs ...any) bool

RequireThat is the flat, testify-style spelling of Require(t, actual).To(matcher): a hard assertion that stops the test on the first failure via Fatalf. See AssertThat for the argument-order rationale. Returns true on success.

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.

func Via

func Via(transform any, matcher any) types.BeMatcher

Via applies the transform function to the actual value and matches the result against the given matcher. Handy for projecting through a public accessor when the underlying value can't be matched directly, e.g.:

be.Expect(t, ctx).To(be.Via(GetActor, be.Eq(wantActor)))

transform must be a function of one argument returning one value (and optionally an error).

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