or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-assertions.mdgbytes.mdgcustom.mdgexec.mdghttp.mdgleak.mdgmeasure.mdgstruct.mdindex.mdmatchers.mdtypes.md
tile.json

core-assertions.mddocs/

Core Assertions and DSL

The Gomega DSL provides functions for creating assertions, integrating with test frameworks, and configuring assertion behavior. It supports both synchronous assertions (Expect, Ω) and asynchronous assertions (Eventually, Consistently).

Synchronous Assertions

Expect

Creates an assertion on an actual value.

func Expect(actual any, extra ...any) Assertion

Parameters:

  • actual: The value to assert on
  • extra: Optional additional values that must be nil/zero (useful for function returns)

Returns: Assertion interface with methods Should, ShouldNot, To, ToNot, NotTo

Usage:

// Basic assertion
Expect(value).To(Equal(42))

// With extra values (e.g., error checking)
value, err := GetValue()
Expect(value).To(Equal("expected")) // Fails if err != nil

// Negation
Expect(value).ToNot(BeNil())
Expect(value).ShouldNot(BeEmpty())

ExpectWithOffset

Like Expect but adjusts the call stack offset for error reporting.

func ExpectWithOffset(offset int, actual any, extra ...any) Assertion

Parameters:

  • offset: Call stack offset for error messages
  • actual: The value to assert on
  • extra: Optional additional values that must be nil/zero

Returns: Assertion

Usage:

// In a helper function, offset by 1 to show correct file:line
func AssertEqual(t *testing.T, actual, expected any) {
    ExpectWithOffset(1, actual).To(Equal(expected))
}

Ω (Omega)

Identical to Expect. Provides alternative syntax using the Greek omega symbol.

func Ω(actual any, extra ...any) Assertion

Parameters:

  • actual: The value to assert on
  • extra: Optional additional values that must be nil/zero

Returns: Assertion

Usage:

Ω(value).Should(Equal(42))
Ω(value, err).Should(Equal("expected")) // Fails if err != nil

Asynchronous Assertions

Eventually

Polls a value or function until an assertion passes or timeout is reached.

func Eventually(actualOrCtx any, args ...any) AsyncAssertion

Parameters:

  • actualOrCtx: Value, function returning value(s), or context.Context
  • args: Optional timeout and polling interval (time.Duration values)

Returns: AsyncAssertion interface

Timeout/Interval Resolution:

  1. If first arg is context.Context, use ctx and remaining args for timeout/interval
  2. Use provided timeout and interval from args
  3. Fall back to configured defaults (SetDefaultEventuallyTimeout, SetDefaultEventuallyPollingInterval)
  4. Ultimate defaults: 1s timeout, 10ms polling interval

Usage:

// Poll function until it returns true
Eventually(func() bool {
    return counter.Value() == 10
}).Should(BeTrue())

// With timeout and polling interval
Eventually(isReady, 5*time.Second, 100*time.Millisecond).Should(BeTrue())

// With context
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
Eventually(ctx, func() bool {
    return checkCondition()
}).Should(BeTrue())

// Poll value directly (re-evaluated each poll)
Eventually(counter.Value).Should(Equal(10))

// With channel
Eventually(ch).Should(Receive())

Advanced Usage:

// Fluent configuration
Eventually(func() int {
    return queue.Size()
}).WithTimeout(10 * time.Second).
   WithPolling(500 * time.Millisecond).
   Should(Equal(0))

// Must pass repeatedly (passes N times in a row before succeeding)
Eventually(flaky).MustPassRepeatedly(3).Should(BeTrue())

// With arguments passed to function
Eventually(func(arg1 int, arg2 string) bool {
    return process(arg1, arg2)
}).WithArguments(42, "test").Should(BeTrue())

EventuallyWithOffset

Like Eventually but with custom call stack offset for error reporting.

func EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion

Parameters:

  • offset: Call stack offset for error messages
  • actualOrCtx: Value, function, or context.Context
  • args: Optional timeout and polling interval

Returns: AsyncAssertion

Consistently

Polls a value or function and requires the assertion to pass for the entire duration.

func Consistently(actualOrCtx any, args ...any) AsyncAssertion

Parameters:

  • actualOrCtx: Value, function returning value(s), or context.Context
  • args: Optional duration and polling interval (time.Duration values)

Returns: AsyncAssertion interface

Duration/Interval Resolution:

  1. If first arg is context.Context, use ctx and remaining args for duration/interval
  2. Use provided duration and interval from args
  3. Fall back to configured defaults (SetDefaultConsistentlyDuration, SetDefaultConsistentlyPollingInterval)
  4. Ultimate defaults: 100ms duration, 10ms polling interval

Usage:

// Verify condition stays true for duration
Consistently(func() bool {
    return service.IsHealthy()
}).Should(BeTrue())

// With custom duration and polling
Consistently(isStable, 2*time.Second, 50*time.Millisecond).Should(BeTrue())

// With context
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
Consistently(ctx, func() int {
    return activeConnections.Count()
}).Should(BeNumerically("<", 100))

ConsistentlyWithOffset

Like Consistently but with custom call stack offset for error reporting.

func ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion

Parameters:

  • offset: Call stack offset for error messages
  • actualOrCtx: Value, function, or context.Context
  • args: Optional duration and polling interval

Returns: AsyncAssertion

Test Framework Integration

RegisterFailHandler

Connects Gomega to a test framework by registering a fail handler function.

func RegisterFailHandler(fail types.GomegaFailHandler)

Parameters:

  • fail: Function called when assertion fails: func(message string, callerSkip ...int)

Usage:

// With Ginkgo
import . "github.com/onsi/ginkgo/v2"

func TestMyPackage(t *testing.T) {
    RegisterFailHandler(Fail) // Ginkgo's Fail function
    RunSpecs(t, "MyPackage Suite")
}

// Custom fail handler
RegisterFailHandler(func(message string, callerSkip ...int) {
    log.Fatalf("Assertion failed: %s", message)
})

NewWithT

Creates a WithT instance for use with testing.T or compatible test frameworks.

func NewWithT(t types.GomegaTestingT) *WithT

Parameters:

  • t: testing.T or any type implementing GomegaTestingT interface (has Helper() and Fatalf(format, args...))

Returns: *WithT with Expect, Eventually, Consistently methods

Usage:

func TestMyFeature(t *testing.T) {
    g := NewWithT(t)

    value := DoSomething()
    g.Expect(value).To(Equal("expected"))

    g.Eventually(func() bool {
        return checkReady()
    }).Should(BeTrue())
}

RegisterTestingT

Deprecated. Registers testing.T with the global Default Gomega instance. Use NewWithT() instead for fresh instance per test.

func RegisterTestingT(t types.GomegaTestingT)

Parameters:

  • t: testing.T or compatible interface

RegisterFailHandlerWithT

Deprecated. Use RegisterFailHandler or RegisterTestingT instead.

func RegisterFailHandlerWithT(_ types.GomegaTestingT, fail types.GomegaFailHandler)

Gomega Instances

NewGomega

Creates a new Gomega instance with a custom fail handler. Useful for non-test scenarios or collecting failures without failing the test.

func NewGomega(fail types.GomegaFailHandler) Gomega

Parameters:

  • fail: Custom fail handler function

Returns: Gomega interface with full DSL

Usage:

// Create Gomega that collects failures instead of failing
var failures []string
g := NewGomega(func(message string, callerSkip ...int) {
    failures = append(failures, message)
})

g.Expect(value1).To(Equal("expected1"))
g.Expect(value2).To(Equal("expected2"))

// Check collected failures
if len(failures) > 0 {
    log.Printf("Validation failures: %v", failures)
}

Default

The global default Gomega instance used by package-level functions.

var Default = Gomega(internal.NewGomega(internal.FetchDefaultDurationBundle()))

Usage:

Most users don't interact with Default directly - package-level functions like Expect() use it automatically.

Failure Interception

InterceptGomegaFailure

Runs a callback and returns the first failure message as an error, stopping execution on first failure.

func InterceptGomegaFailure(f func()) (err error)

Parameters:

  • f: Callback function to run

Returns: error wrapping the first failure message, or nil if no failures

Usage:

// Test a custom matcher without failing the test
err := InterceptGomegaFailure(func() {
    Expect(value).To(MyCustomMatcher())
})
if err != nil {
    t.Logf("Matcher failed as expected: %v", err)
}

// Validate multiple items, stop on first failure
err = InterceptGomegaFailure(func() {
    Expect(result.Name).To(Equal("expected"))
    Expect(result.Value).To(BeNumerically(">", 0))
})

InterceptGomegaFailures

Runs a callback and returns all failure messages, continuing execution after failures.

func InterceptGomegaFailures(f func()) []string

Parameters:

  • f: Callback function to run

Returns: Slice of all failure messages

Usage:

// Collect all failures
failures := InterceptGomegaFailures(func() {
    Expect(result.Name).To(Equal("expected"))
    Expect(result.Value).To(BeNumerically(">", 0))
    Expect(result.Status).To(Equal("active"))
})

if len(failures) > 0 {
    t.Logf("Found %d validation failures:", len(failures))
    for _, f := range failures {
        t.Log(f)
    }
}

Configuration

SetDefaultEventuallyTimeout

Sets the default timeout for Eventually assertions.

func SetDefaultEventuallyTimeout(t time.Duration)

Parameters:

  • t: Timeout duration (default: 1 second)

SetDefaultEventuallyPollingInterval

Sets the default polling interval for Eventually assertions.

func SetDefaultEventuallyPollingInterval(t time.Duration)

Parameters:

  • t: Polling interval (default: 10 milliseconds)

SetDefaultConsistentlyDuration

Sets the default duration for Consistently assertions.

func SetDefaultConsistentlyDuration(t time.Duration)

Parameters:

  • t: Duration (default: 100 milliseconds)

SetDefaultConsistentlyPollingInterval

Sets the default polling interval for Consistently assertions.

func SetDefaultConsistentlyPollingInterval(t time.Duration)

Parameters:

  • t: Polling interval (default: 10 milliseconds)

DisableDefaultTimeoutsWhenUsingContext

Disables default timeouts when using context.Context with Eventually/Consistently. The context's deadline becomes the only timeout.

func DisableDefaultTimeoutsWhenUsingContext()

EnforceDefaultTimeoutsWhenUsingContexts

Enforces default timeouts even when using context.Context (default behavior). The shorter of the context deadline and default timeout is used.

func EnforceDefaultTimeoutsWhenUsingContexts()

Polling Signal Errors

Special errors that control polling behavior in Eventually/Consistently.

StopTrying

Signal error that stops Eventually/Consistently polling and fails the assertion.

var StopTrying = internal.StopTrying

Usage:

Eventually(func() error {
    result, err := TryOperation()
    if err != nil {
        if isFatal(err) {
            return StopTrying // Stop polling, fail now
        }
        return err // Continue polling
    }
    return nil
}).Should(Succeed())

TryAgainAfter

Signal function that delays the next poll by a custom duration.

var TryAgainAfter = internal.TryAgainAfter

Usage:

Eventually(func() error {
    result, err := TryOperation()
    if err != nil {
        if isRateLimited(err) {
            return TryAgainAfter(5 * time.Second) // Wait 5s before next attempt
        }
        return err
    }
    return nil
}).Should(Succeed())

Type Aliases

Gomega

Type alias for the Gomega interface.

type Gomega = types.Gomega

WithT

Type alias for WithT (testing.T integration).

type WithT = internal.Gomega

GomegaWithT

Deprecated alias for WithT.

type GomegaWithT = WithT

Assertion

Type alias for the Assertion interface.

type Assertion = types.Assertion

AsyncAssertion

Type alias for the AsyncAssertion interface.

type AsyncAssertion = types.AsyncAssertion

GomegaAssertion

Type alias for Assertion.

type GomegaAssertion = types.Assertion

GomegaAsyncAssertion

Type alias for AsyncAssertion.

type GomegaAsyncAssertion = types.AsyncAssertion

OmegaMatcher

Type alias for GomegaMatcher.

type OmegaMatcher = types.GomegaMatcher

PollingSignalError

Type alias for polling signal errors.

type PollingSignalError = internal.PollingSignalError

Version Constant

const GOMEGA_VERSION = "1.38.2"