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 "github.com/onsi/gomega/types"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:
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))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:
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
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:
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.
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:
.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"))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:
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")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:
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())
}func MatchMayChangeInTheFuture(matcher GomegaMatcher, value any) boolHelper 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 checkvalue - The value being matched againstReturns:
true if the matcher implements OracleMatcher and its result may change in the futuretrue if the matcher does not implement OracleMatcher (conservative default)false if the matcher implements OracleMatcher and its result will not changeBehavior:
OracleMatcher interface, delegates to its MatchMayChangeInTheFuture methodOracleMatcher, 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 falseThis function is primarily used internally by Gomega's Eventually and Consistently implementations to determine when to stop polling.
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:
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)
})The types package provides the core contracts and type definitions for Gomega:
These interfaces enable:
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.