or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

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

types-interfaces.mddocs/

Types Package: Core Interfaces and Types

Package: github.com/onsi/gomega/types

The types package defines the core interfaces and types that form the foundation of Gomega's assertion framework. These interfaces enable the main Gomega DSL, matcher contracts, and extensibility points.

Import

import "github.com/onsi/gomega/types"

Core Interfaces

Gomega Interface

The Gomega interface is the main entry point for all Gomega assertions. It provides methods for synchronous and asynchronous assertions, as well as configuration options.

type Gomega interface {
    Ω(actual any, extra ...any) Assertion
    Expect(actual any, extra ...any) Assertion
    ExpectWithOffset(offset int, actual any, extra ...any) Assertion

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

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

    SetDefaultEventuallyTimeout(time.Duration)
    SetDefaultEventuallyPollingInterval(time.Duration)
    SetDefaultConsistentlyDuration(time.Duration)
    SetDefaultConsistentlyPollingInterval(time.Duration)
    EnforceDefaultTimeoutsWhenUsingContexts()
    DisableDefaultTimeoutsWhenUsingContext()
}

Purpose: Represents an object that can perform synchronous and asynchronous assertions with Gomega matchers. This interface is implemented by the main Gomega DSL instance and provides all assertion and configuration methods.

Methods:

  • Ω(actual any, extra ...any) Assertion - Creates a synchronous assertion on the actual value using the omega symbol. Alias for Expect.
  • Expect(actual any, extra ...any) Assertion - Creates a synchronous assertion on the actual value. Main assertion function.
  • ExpectWithOffset(offset int, actual any, extra ...any) Assertion - Like Expect but adjusts stack trace offset for helper functions.
  • Eventually(actualOrCtx any, args ...any) AsyncAssertion - Polls until condition is met or timeout. First arg can be value, function, or context.Context.
  • EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion - Like Eventually with stack offset adjustment.
  • Consistently(actualOrCtx any, args ...any) AsyncAssertion - Polls to ensure condition stays true for duration. First arg can be value, function, or context.Context.
  • ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion - Like Consistently with stack offset adjustment.
  • SetDefaultEventuallyTimeout(time.Duration) - Sets default timeout for Eventually assertions.
  • SetDefaultEventuallyPollingInterval(time.Duration) - Sets default polling interval for Eventually assertions.
  • SetDefaultConsistentlyDuration(time.Duration) - Sets default duration for Consistently assertions.
  • SetDefaultConsistentlyPollingInterval(time.Duration) - Sets default polling interval for Consistently assertions.
  • EnforceDefaultTimeoutsWhenUsingContexts() - Makes Eventually/Consistently enforce default timeouts even with context.Context.
  • DisableDefaultTimeoutsWhenUsingContext() - Disables default timeouts when context.Context is provided.

Usage Example:

import (
    "github.com/onsi/gomega"
    "github.com/onsi/gomega/types"
)

// Using package-level default instance
gomega.Expect(value).To(gomega.Equal(42))

// Creating custom instance
failHandler := func(message string, callerSkip ...int) {
    // Custom failure handling
}
g := gomega.NewGomega(failHandler)
g.Expect(value).To(gomega.Equal(42))

GomegaMatcher Interface

The GomegaMatcher interface is the contract that all Gomega matchers must implement. It defines the three core methods required for matching values and generating failure messages.

type GomegaMatcher interface {
    Match(actual any) (success bool, err error)
    FailureMessage(actual any) (message string)
    NegatedFailureMessage(actual any) (message string)
}

Purpose: All Gomega matchers must implement this interface. It provides the contract for matching values and generating appropriate failure messages for both positive and negative assertions.

Methods:

  • Match(actual any) (success bool, err error) - Performs the actual matching logic. Returns true if the match succeeds, false otherwise. Returns an error if the matcher cannot evaluate the actual value.
  • FailureMessage(actual any) (message string) - Returns the failure message to display when Match returns false in a positive assertion (e.g., Should, To).
  • NegatedFailureMessage(actual any) (message string) - Returns the failure message to display when Match returns true in a negative assertion (e.g., ShouldNot, NotTo).

Usage Example:

import "github.com/onsi/gomega/types"

// Custom matcher implementation
type BeEvenMatcher struct{}

func (m *BeEvenMatcher) Match(actual any) (bool, error) {
    num, ok := actual.(int)
    if !ok {
        return false, fmt.Errorf("BeEven expects an int, got %T", actual)
    }
    return num%2 == 0, nil
}

func (m *BeEvenMatcher) FailureMessage(actual any) string {
    return fmt.Sprintf("Expected %d to be even", actual)
}

func (m *BeEvenMatcher) NegatedFailureMessage(actual any) string {
    return fmt.Sprintf("Expected %d not to be even", actual)
}

// Using the custom matcher
func BeEven() types.GomegaMatcher {
    return &BeEvenMatcher{}
}

// In tests
gomega.Expect(4).To(BeEven())
gomega.Expect(3).NotTo(BeEven())

For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding-your-own-matchers

OracleMatcher Interface

The OracleMatcher interface is an optional extension that matchers can implement to provide information about whether their result might change in the future.

type OracleMatcher interface {
    MatchMayChangeInTheFuture(actual any) bool
}

Purpose: GomegaMatchers that also implement the OracleMatcher interface can convey information about whether or not their result will change upon future attempts. This allows Eventually and Consistently to short circuit if success becomes impossible.

Methods:

  • MatchMayChangeInTheFuture(actual any) bool - Returns true if the match result might change on future attempts, false if the result is final and will never change.

Usage Example:

import "github.com/onsi/gomega/types"

// Custom matcher that implements OracleMatcher
type ProcessExitMatcher struct {
    exitCode int
}

func (m *ProcessExitMatcher) Match(actual any) (bool, error) {
    process := actual.(*Process)
    if !process.HasExited() {
        return false, nil
    }
    return process.ExitCode() == m.exitCode, nil
}

func (m *ProcessExitMatcher) FailureMessage(actual any) string {
    return fmt.Sprintf("Expected process to exit with code %d", m.exitCode)
}

func (m *ProcessExitMatcher) NegatedFailureMessage(actual any) string {
    return fmt.Sprintf("Expected process not to exit with code %d", m.exitCode)
}

func (m *ProcessExitMatcher) MatchMayChangeInTheFuture(actual any) bool {
    process := actual.(*Process)
    // Once the process exits, the exit code will never change
    return !process.HasExited()
}

// Using with Eventually
// Eventually will stop polling once the process exits, even if the exit code doesn't match
gomega.Eventually(process).Should(HaveExitCode(0))

Real-World Example:

For example, a process' exit code can never change. So, gexec's Exit matcher returns true for MatchMayChangeInTheFuture until the process exits, at which point it returns false forevermore. This allows Eventually to short-circuit and fail immediately once the process exits with the wrong code, rather than continuing to poll until timeout.

Assertion Interface

The Assertion interface is returned by synchronous assertion functions (Expect, Ω) and provides methods for applying matchers to values.

type Assertion interface {
    Should(matcher GomegaMatcher, optionalDescription ...any) bool
    ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool

    To(matcher GomegaMatcher, optionalDescription ...any) bool
    ToNot(matcher GomegaMatcher, optionalDescription ...any) bool
    NotTo(matcher GomegaMatcher, optionalDescription ...any) bool

    WithOffset(offset int) Assertion

    Error() Assertion
}

Purpose: Assertions are returned by Ω and Expect and enable assertions against Gomega matchers. This interface provides methods for immediate value matching with optional descriptions.

Methods:

  • Should(matcher GomegaMatcher, optionalDescription ...any) bool - Applies the matcher to the actual value. Fails the test if the matcher does not match. Returns true if match succeeds.
  • ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool - Applies the negated matcher to the actual value. Fails the test if the matcher matches. Returns true if negated match succeeds.
  • To(matcher GomegaMatcher, optionalDescription ...any) bool - Equivalent to Should. Preferred for readability.
  • ToNot(matcher GomegaMatcher, optionalDescription ...any) bool - Equivalent to ShouldNot.
  • NotTo(matcher GomegaMatcher, optionalDescription ...any) bool - Equivalent to ShouldNot. Preferred for readability.
  • WithOffset(offset int) Assertion - Adjusts the stack trace offset for reporting failures. Useful when creating helper functions that wrap assertions.
  • Error() Assertion - Convenience method for assertions on error values. Equivalent to .Error() on the assertion.

Usage Example:

import "github.com/onsi/gomega"

// Basic assertions
gomega.Expect(value).To(gomega.Equal(42))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(slice).To(gomega.BeEmpty())

// With optional description
gomega.Expect(user.Age).To(gomega.BeNumerically(">", 18), "user must be an adult")

// Using Should/ShouldNot (alternative syntax)
gomega.Ω(result).Should(gomega.BeTrue())
gomega.Ω(list).ShouldNot(gomega.ContainElement("secret"))

// Using WithOffset in helper functions
func ExpectValidUser(user User) {
    gomega.ExpectWithOffset(1, user.Name).NotTo(gomega.BeEmpty())
    gomega.ExpectWithOffset(1, user.Age).To(gomega.BeNumerically(">", 0))
}

// Error assertions
gomega.Expect(err).Error().To(gomega.HaveOccurred())
gomega.Expect(operation()).Error().To(gomega.MatchError("connection failed"))

AsyncAssertion Interface

The AsyncAssertion interface is returned by Eventually and Consistently and enables matchers to be polled repeatedly to ensure they are eventually satisfied.

type AsyncAssertion interface {
    Should(matcher GomegaMatcher, optionalDescription ...any) bool
    ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool

    To(matcher GomegaMatcher, optionalDescription ...any) bool
    ToNot(matcher GomegaMatcher, optionalDescription ...any) bool
    NotTo(matcher GomegaMatcher, optionalDescription ...any) bool

    WithOffset(offset int) AsyncAssertion
    WithTimeout(interval time.Duration) AsyncAssertion
    WithPolling(interval time.Duration) AsyncAssertion
    Within(timeout time.Duration) AsyncAssertion
    ProbeEvery(interval time.Duration) AsyncAssertion
    WithContext(ctx context.Context) AsyncAssertion
    WithArguments(argsToForward ...any) AsyncAssertion
    MustPassRepeatedly(count int) AsyncAssertion
}

Purpose: AsyncAssertions are returned by Eventually and Consistently and enable matchers to be polled repeatedly to ensure they are eventually satisfied. This interface provides methods for configuring polling behavior and timeout settings.

Methods:

  • Should(matcher GomegaMatcher, optionalDescription ...any) bool - Polls the actual value repeatedly until the matcher matches or timeout. Fails the test if timeout is reached.
  • ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool - Polls the actual value repeatedly until the matcher does not match or timeout. Fails the test if the matcher matches during the duration.
  • To(matcher GomegaMatcher, optionalDescription ...any) bool - Equivalent to Should.
  • ToNot(matcher GomegaMatcher, optionalDescription ...any) bool - Equivalent to ShouldNot.
  • NotTo(matcher GomegaMatcher, optionalDescription ...any) bool - Equivalent to ShouldNot.
  • WithOffset(offset int) AsyncAssertion - Adjusts the stack trace offset for reporting failures.
  • WithTimeout(interval time.Duration) AsyncAssertion - Sets the timeout duration for this assertion.
  • WithPolling(interval time.Duration) AsyncAssertion - Sets the polling interval for this assertion.
  • Within(timeout time.Duration) AsyncAssertion - Alias for WithTimeout.
  • ProbeEvery(interval time.Duration) AsyncAssertion - Alias for WithPolling.
  • WithContext(ctx context.Context) AsyncAssertion - Attaches a context for cancellation and deadline control.
  • WithArguments(argsToForward ...any) AsyncAssertion - Forwards arguments to the actual function on each poll (if actual is a function).
  • MustPassRepeatedly(count int) AsyncAssertion - Requires the matcher to succeed consecutively count times before considering the assertion successful.

Usage Example:

import (
    "context"
    "time"
    "github.com/onsi/gomega"
)

// Basic Eventually assertion
gomega.Eventually(func() int {
    return counter.Value()
}).Should(gomega.Equal(10))

// With timeout and polling configuration
gomega.Eventually(isReady).
    WithTimeout(30 * time.Second).
    WithPolling(500 * time.Millisecond).
    Should(gomega.BeTrue())

// Using Within and ProbeEvery (aliases)
gomega.Eventually(getStatus).
    Within(5 * time.Second).
    ProbeEvery(100 * time.Millisecond).
    Should(gomega.Equal("ready"))

// With context for cancellation
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
gomega.Eventually(fetchData).
    WithContext(ctx).
    Should(gomega.Not(gomega.BeNil()))

// With arguments forwarded to function
gomega.Eventually(database.GetUser).
    WithArguments("user123").
    Should(gomega.Not(gomega.BeNil()))

// MustPassRepeatedly ensures stability
gomega.Eventually(healthCheck).
    MustPassRepeatedly(5).
    Should(gomega.Equal("healthy"))

// Consistently ensures condition stays true
gomega.Consistently(func() bool {
    return cache.IsHealthy()
}, 5*time.Second, 100*time.Millisecond).Should(gomega.BeTrue())

// Consistently with descriptive message
gomega.Consistently(memoryUsage).
    Within(30 * time.Second).
    ProbeEvery(1 * time.Second).
    Should(gomega.BeNumerically("<", 100), "memory usage should stay under 100MB")

GomegaTestingT Interface

The GomegaTestingT interface defines the minimal contract required for integration with Go's testing package or compatible test frameworks.

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

Purpose: Interface for *testing.T and compatible types. This simple interface allows Gomega to integrate with Go's standard testing package and other test frameworks that provide similar APIs.

Methods:

  • Helper() - Marks the calling function as a test helper, improving stack traces by skipping this function in error reports.
  • Fatalf(format string, args ...any) - Formats and logs a failure message, then marks the test as failed and stops execution.

Usage Example:

import (
    "testing"
    "github.com/onsi/gomega"
)

func TestMyFunction(t *testing.T) {
    // NewWithT creates a Gomega instance bound to testing.T
    g := gomega.NewWithT(t)

    result := MyFunction()
    g.Expect(result).To(gomega.Equal("expected"))
}

// Custom test framework adapter
type CustomTestFramework struct {
    t *testing.T
}

func (c *CustomTestFramework) Helper() {
    c.t.Helper()
}

func (c *CustomTestFramework) Fatalf(format string, args ...any) {
    c.t.Fatalf(format, args...)
}

func TestWithCustomFramework(t *testing.T) {
    custom := &CustomTestFramework{t: t}
    g := gomega.NewWithT(custom)

    g.Expect(true).To(gomega.BeTrue())
}

Helper Functions

MatchMayChangeInTheFuture

func MatchMayChangeInTheFuture(matcher GomegaMatcher, value any) bool

Helper function that checks if a matcher's result may change in the future for the given value. This is used internally by Eventually and Consistently to optimize polling behavior.

Parameters:

  • matcher - The matcher to check
  • value - The value being matched against

Returns:

  • true if the matcher implements OracleMatcher and its result may change in the future
  • true if the matcher does not implement OracleMatcher (conservative default)
  • false if the matcher implements OracleMatcher and its result will not change

Behavior:

  • If the matcher implements the OracleMatcher interface, delegates to its MatchMayChangeInTheFuture method
  • If the matcher does not implement OracleMatcher, conservatively returns true (assumes result may change)

Usage Example:

import (
    "github.com/onsi/gomega/types"
    "github.com/onsi/gomega/gexec"
)

// Check if Exit matcher result may change
session := startProcess()
exitMatcher := gexec.Exit(0)

// While process is running, this returns true
mayChange := types.MatchMayChangeInTheFuture(exitMatcher, session)
// After process exits, this returns false

This function is primarily used internally by Gomega's Eventually and Consistently implementations to determine when to stop polling.

Function Types

GomegaFailHandler

The GomegaFailHandler type defines the signature for functions that handle assertion failures.

type GomegaFailHandler func(message string, callerSkip ...int)

Purpose: Fail handler function type. This function is called when an assertion fails, allowing custom failure handling and integration with different test frameworks.

Parameters:

  • message string - The formatted failure message describing what went wrong.
  • callerSkip ...int - Optional offset to adjust the call stack for better error reporting. Higher values skip more stack frames.

Usage Example:

import (
    "fmt"
    "github.com/onsi/gomega"
    "github.com/onsi/gomega/types"
)

// Custom fail handler for logging
func loggingFailHandler(message string, callerSkip ...int) {
    fmt.Printf("ASSERTION FAILED: %s\n", message)
    // Could also send to logging service, metrics, etc.
    panic(message)
}

// Register custom fail handler
gomega.RegisterFailHandler(loggingFailHandler)

// Create Gomega instance with custom fail handler
customFailHandler := func(message string, callerSkip ...int) {
    // Custom failure logic
    logger.Error("Test failure:", message)
    os.Exit(1)
}
g := gomega.NewGomega(customFailHandler)

// Integration with Ginkgo (typical usage)
import "github.com/onsi/ginkgo/v2"

var _ = BeforeSuite(func() {
    gomega.RegisterFailHandler(ginkgo.Fail)
})

Summary

The types package provides the core contracts and type definitions for Gomega:

  • Gomega - Main interface for creating assertions and configuring behavior
  • GomegaMatcher - Contract that all matchers must implement
  • OracleMatcher - Optional interface for matchers to indicate if results may change
  • Assertion - Interface for synchronous assertions returned by Expect/Ω
  • AsyncAssertion - Interface for asynchronous assertions returned by Eventually/Consistently
  • GomegaTestingT - Interface for test framework integration (testing.T compatibility)
  • GomegaFailHandler - Function type for custom failure handling

These interfaces enable:

  1. Extensibility - Custom matchers can implement GomegaMatcher (and optionally OracleMatcher)
  2. Framework Integration - GomegaTestingT and GomegaFailHandler allow integration with any test framework
  3. Type Safety - Clear contracts for assertion behavior and matcher implementation
  4. Flexibility - Support for both synchronous and asynchronous testing patterns

All public-facing Gomega APIs are built on these foundational interfaces, making the types package essential for understanding how Gomega works and how to extend it.