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

tessl/golang-github-com-onsi--gomega

Gomega is Ginkgo's preferred matcher library for BDD-style testing in Go

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/onsi/gomega@v1.38.2

To install, run

npx @tessl/cli install tessl/golang-github-com-onsi--gomega@1.38.0

index.mddocs/

Gomega

Gomega is a BDD-style matcher and assertion library for Go testing. It provides expressive matchers for synchronous and asynchronous assertions, extensive built-in matchers for common testing scenarios, and specialized packages for buffer testing, HTTP server mocking, process execution, goroutine leak detection, performance measurement, and structural matching.

Package Information

  • Package Name: github.com/onsi/gomega
  • Package Type: golang
  • Language: Go
  • Installation: go get github.com/onsi/gomega

Core Imports

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

For specialized testing packages:

import (
    "github.com/onsi/gomega/gbytes"    // Buffer testing
    "github.com/onsi/gomega/gcustom"   // Custom matchers
    "github.com/onsi/gomega/gexec"     // Process execution
    "github.com/onsi/gomega/ghttp"     // HTTP server testing
    "github.com/onsi/gomega/gleak"     // Goroutine leak detection
    "github.com/onsi/gomega/gmeasure"  // Performance measurement
    "github.com/onsi/gomega/gstruct"   // Structural matching
    "github.com/onsi/gomega/format"    // Output formatting
)

Basic Usage

With Ginkgo

import (
    . "github.com/onsi/ginkgo/v2"
    . "github.com/onsi/gomega"
)

var _ = Describe("Calculator", func() {
    It("should add numbers correctly", func() {
        result := Add(2, 3)
        Expect(result).To(Equal(5))
    })

    It("should eventually process the queue", func() {
        Eventually(queue.Size).Should(BeZero())
    })
})

func TestCalculator(t *testing.T) {
    RegisterFailHandler(Fail)
    RunSpecs(t, "Calculator Suite")
}

With testing.T

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

func TestAdd(t *testing.T) {
    g := NewWithT(t)
    result := Add(2, 3)
    g.Expect(result).To(Equal(5))
}

func TestAsyncOperation(t *testing.T) {
    g := NewWithT(t)
    g.Eventually(func() int {
        return queue.Size()
    }).Should(Equal(0))
}

Capabilities Overview

Core Assertions

Gomega provides synchronous and asynchronous assertion functions with flexible matching capabilities.

// Synchronous assertions for immediate value checking
func Expect(actual any, extra ...any) Assertion
func Ω(actual any, extra ...any) Assertion
func ExpectWithOffset(offset int, actual any, extra ...any) Assertion

// Asynchronous assertions that poll until condition is met or timeout
func Eventually(actualOrCtx any, args ...any) AsyncAssertion
func EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion

// Asynchronous assertions that verify condition stays true for duration
func Consistently(actualOrCtx any, args ...any) AsyncAssertion
func ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion

Setup and configuration functions:

// Setup functions for test framework integration
func RegisterFailHandler(fail types.GomegaFailHandler)
func NewGomega(fail types.GomegaFailHandler) Gomega
func NewWithT(t types.GomegaTestingT) *WithT

// Timeout configuration for asynchronous assertions
func SetDefaultEventuallyTimeout(t time.Duration)
func SetDefaultEventuallyPollingInterval(t time.Duration)
func SetDefaultConsistentlyDuration(t time.Duration)
func SetDefaultConsistentlyPollingInterval(t time.Duration)

// Context behavior control
func EnforceDefaultTimeoutsWhenUsingContexts()
func DisableDefaultTimeoutsWhenUsingContext()

// Polling control
func StopTrying(message string) PollingSignalError
func TryAgainAfter(duration time.Duration) PollingSignalError

Core Assertions

Built-in Matchers

Gomega includes 70+ built-in matchers covering equality, errors, strings, collections, numerics, types, functions, channels, files, HTTP, and structured data.

Equality and identity matchers:

func Equal(expected any) types.GomegaMatcher
func BeEquivalentTo(expected any) types.GomegaMatcher
func BeComparableTo(expected any, opts ...cmp.Option) types.GomegaMatcher
func BeIdenticalTo(expected any) types.GomegaMatcher
func BeNil() types.GomegaMatcher
func BeZero() types.GomegaMatcher

Error matchers:

func HaveOccurred() types.GomegaMatcher
func Succeed() types.GomegaMatcher
func MatchError(expected any, functionErrorDescription ...any) types.GomegaMatcher

String matchers:

func ContainSubstring(substr string, args ...any) types.GomegaMatcher
func HavePrefix(prefix string, args ...any) types.GomegaMatcher
func HaveSuffix(suffix string, args ...any) types.GomegaMatcher
func MatchRegexp(regexp string, args ...any) types.GomegaMatcher

Collection matchers:

func BeEmpty() types.GomegaMatcher
func HaveLen(count int) types.GomegaMatcher
func HaveCap(count int) types.GomegaMatcher
func ContainElement(element any, result ...any) types.GomegaMatcher
func ContainElements(elements ...any) types.GomegaMatcher
func ConsistOf(elements ...any) types.GomegaMatcher
func HaveExactElements(elements ...any) types.GomegaMatcher
func HaveEach(element any) types.GomegaMatcher

Combinator matchers:

func And(ms ...types.GomegaMatcher) types.GomegaMatcher
func Or(ms ...types.GomegaMatcher) types.GomegaMatcher
func Not(matcher types.GomegaMatcher) types.GomegaMatcher
func WithTransform(transform any, matcher types.GomegaMatcher) types.GomegaMatcher
func Satisfy(predicate any) types.GomegaMatcher

Built-in Matchers

Types & Interfaces

Core types and interfaces for creating and using matchers with Gomega.

// Main Gomega interface
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()
}

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

// Optional interface for asynchronous assertions
type OracleMatcher interface {
    MatchMayChangeInTheFuture(actual any) bool
}

// Synchronous assertion interface
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
}

// Asynchronous assertion interface
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
}

// Testing framework integration
type GomegaTestingT interface {
    Helper()
    Fatalf(format string, args ...any)
}

// Fail handler function type
type GomegaFailHandler func(message string, callerSkip ...int)

Types & Interfaces

Output Formatting

Customizable output formatting for assertion failure messages and object representation.

// Pretty-print formatting
func Object(object any, indentation uint) string
func Message(actual any, message string, expected ...any) string
func MessageWithDiff(actual, message, expected string) string
func IndentString(s string, indentation uint) string

// Custom formatter registration
func RegisterCustomFormatter(customFormatter CustomFormatter) CustomFormatterKey
func UnregisterCustomFormatter(key CustomFormatterKey)

Configuration variables:

var MaxDepth uint = 10
var MaxLength int = 4000
var UseStringerRepresentation bool = false
var PrintContextObjects bool = false
var TruncatedDiff bool = true
var TruncateThreshold uint = 50
var CharactersAroundMismatchToInclude uint = 5
var Indent string = "    "

Types:

type CustomFormatter func(value any) (string, bool)
type CustomFormatterKey int

type GomegaStringer interface {
    GomegaString() string
}

Output Formatting

Buffer Testing

Thread-safe buffer implementation with pattern detection for testing streaming I/O operations.

// Buffer creation
func NewBuffer() *Buffer
func BufferWithBytes(bytes []byte) *Buffer
func BufferReader(reader io.Reader) *Buffer

// Timeout wrappers
func TimeoutCloser(c io.Closer, timeout time.Duration) io.Closer
func TimeoutReader(r io.Reader, timeout time.Duration) io.Reader
func TimeoutWriter(w io.Writer, timeout time.Duration) io.Writer

// Matcher
func Say(expected string, args ...any) *sayMatcher

Buffer type:

type Buffer struct {
    // Thread-safe buffer for testing streaming I/O
}

// Methods:
func (b *Buffer) Write(p []byte) (n int, err error)
func (b *Buffer) Read(d []byte) (int, error)
func (b *Buffer) Clear() error
func (b *Buffer) Close() error
func (b *Buffer) Closed() bool
func (b *Buffer) Contents() []byte
func (b *Buffer) Detect(desired string, args ...any) chan bool
func (b *Buffer) CancelDetects()

Buffer Testing

Custom Matchers

Create custom matchers with flexible match functions and templated failure messages.

// Create custom matcher from function
func MakeMatcher(matchFunc any, args ...any) CustomGomegaMatcher

// Template parsing for custom messages
func ParseTemplate(templ string) (*template.Template, error)

Custom matcher builder:

type CustomGomegaMatcher struct {
    // Custom matcher builder
}

// Methods:
func (m CustomGomegaMatcher) WithMessage(message string) CustomGomegaMatcher
func (m CustomGomegaMatcher) WithTemplate(templ string, data ...any) CustomGomegaMatcher
func (m CustomGomegaMatcher) WithPrecompiledTemplate(templ *template.Template, data ...any) CustomGomegaMatcher
func (m CustomGomegaMatcher) WithTemplateData(data any) CustomGomegaMatcher
func (m CustomGomegaMatcher) Match(actual any) (bool, error)
func (m CustomGomegaMatcher) FailureMessage(actual any) string
func (m CustomGomegaMatcher) NegatedFailureMessage(actual any) string

Custom Matchers

Process Testing

Execute and test external processes with captured output and exit code verification.

// Start process
func Start(command *exec.Cmd, outWriter io.Writer, errWriter io.Writer) (*Session, error)

// Build Go binaries
func Build(packagePath string, args ...string) (compiledPath string, err error)
func BuildWithEnvironment(packagePath string, env []string, args ...string) (compiledPath string, err error)
func BuildIn(gopath string, packagePath string, args ...string) (compiledPath string, err error)
func CleanupBuildArtifacts()

// Global session control
func KillAndWait(timeout ...any)
func TerminateAndWait(timeout ...any)
func Kill()
func Terminate()
func Signal(signal os.Signal)
func Interrupt()

// Exit code matcher
func Exit(optionalExitCode ...int) *exitMatcher

// Utility
func NewPrefixedWriter(prefix string, writer io.Writer) *PrefixedWriter

Session type:

type Session struct {
    Command *exec.Cmd
    Out *gbytes.Buffer
    Err *gbytes.Buffer
    Exited <-chan struct{}
}

// Methods:
func (s *Session) ExitCode() int
func (s *Session) Wait(timeout ...any) *Session
func (s *Session) Kill() *Session
func (s *Session) Interrupt() *Session
func (s *Session) Terminate() *Session
func (s *Session) Signal(signal os.Signal) *Session
func (s *Session) Buffer() *gbytes.Buffer

Process Testing

HTTP Testing

Mock HTTP server implementation for testing HTTP clients and handlers with request verification and response generation.

// Server creation
func NewServer() *Server
func NewUnstartedServer() *Server
func NewTLSServer() *Server

// Verification handlers
func CombineHandlers(handlers ...http.HandlerFunc) http.HandlerFunc
func VerifyRequest(method string, path any, rawQuery ...string) http.HandlerFunc
func VerifyContentType(contentType string) http.HandlerFunc
func VerifyMimeType(mimeType string) http.HandlerFunc
func VerifyBasicAuth(username string, password string) http.HandlerFunc
func VerifyHeader(header http.Header) http.HandlerFunc
func VerifyHeaderKV(key string, values ...string) http.HandlerFunc
func VerifyHost(host any) http.HandlerFunc
func VerifyBody(expectedBody []byte) http.HandlerFunc
func VerifyJSON(expectedJSON string) http.HandlerFunc
func VerifyJSONRepresenting(object any) http.HandlerFunc
func VerifyForm(values url.Values) http.HandlerFunc
func VerifyFormKV(key string, values ...string) http.HandlerFunc
func VerifyProtoRepresenting(expected protoiface.MessageV1) http.HandlerFunc

// Response handlers
func RespondWith(statusCode int, body any, optionalHeader ...http.Header) http.HandlerFunc
func RespondWithPtr(statusCode *int, body any, optionalHeader ...http.Header) http.HandlerFunc
func RespondWithJSONEncoded(statusCode int, object any, optionalHeader ...http.Header) http.HandlerFunc
func RespondWithJSONEncodedPtr(statusCode *int, object any, optionalHeader ...http.Header) http.HandlerFunc
func RespondWithProto(statusCode int, message protoadapt.MessageV1, optionalHeader ...http.Header) http.HandlerFunc

// Scoped handler factory
func NewGHTTPWithGomega(gomega Gomega) *GHTTPWithGomega

Server type:

type Server struct {
    HTTPTestServer *httptest.Server
    AllowUnhandledRequests bool
    UnhandledRequestStatusCode int
    Writer io.Writer
}

// Server management:
func (s *Server) Start()
func (s *Server) Close()
func (s *Server) URL() string
func (s *Server) Addr() string
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)
func (s *Server) CloseClientConnections()

// Handler management:
func (s *Server) AppendHandlers(handlers ...http.HandlerFunc)
func (s *Server) SetHandler(index int, handler http.HandlerFunc)
func (s *Server) GetHandler(index int) http.HandlerFunc
func (s *Server) WrapHandler(index int, handler http.HandlerFunc)
func (s *Server) RouteToHandler(method string, path any, handler http.HandlerFunc)
func (s *Server) Reset()

// Configuration:
func (s *Server) SetAllowUnhandledRequests(bool)
func (s *Server) GetAllowUnhandledRequests() bool
func (s *Server) SetUnhandledRequestStatusCode(int)
func (s *Server) GetUnhandledRequestStatusCode() int

// Request tracking:
func (s *Server) ReceivedRequests() []*http.Request

// RoundTripper:
func (s *Server) RoundTripper(rt http.RoundTripper) http.RoundTripper

HTTP Testing

Goroutine Leak Detection

Detect and filter goroutine leaks in tests with customizable ignore patterns.

// Get all goroutines
func Goroutines() []Goroutine

// Leak detection matcher
func HaveLeaked(ignoring ...any) types.GomegaMatcher

// Filter matchers
func IgnoringTopFunction(name string) types.GomegaMatcher
func IgnoringGoroutines(goroutines []Goroutine) types.GomegaMatcher
func IgnoringInBacktrace(substring string) types.GomegaMatcher
func IgnoringCreator(name string) types.GomegaMatcher

Configuration:

var ReportFilenameWithPath bool = false

Goroutine Leak Detection

Performance Measurement

Measure and analyze performance metrics including duration, values, and statistical analysis.

// Create experiment
func NewExperiment(name string) *Experiment

Experiment type:

type Experiment struct {
    Name string
    Measurements Measurements
}

// Recording methods:
func (e *Experiment) RecordNote(note string, args ...any)
func (e *Experiment) RecordDuration(name string, duration time.Duration, args ...any)
func (e *Experiment) RecordValue(name string, value float64, args ...any)

// Measurement methods:
func (e *Experiment) MeasureDuration(name string, callback func(), args ...any) time.Duration
func (e *Experiment) MeasureValue(name string, callback func() float64, args ...any) float64

// Sampling methods:
func (e *Experiment) SampleDuration(name string, callback func(idx int), samplingConfig SamplingConfig, args ...any)
func (e *Experiment) SampleAnnotatedDuration(name string, callback func(idx int) Annotation, samplingConfig SamplingConfig, args ...any)
func (e *Experiment) SampleValue(name string, callback func(idx int) float64, samplingConfig SamplingConfig, args ...any)
func (e *Experiment) SampleAnnotatedValue(name string, callback func(idx int) (float64, Annotation), samplingConfig SamplingConfig, args ...any)
func (e *Experiment) Sample(callback func(idx int), samplingConfig SamplingConfig)

// Query methods:
func (e *Experiment) Get(name string) Measurement
func (e *Experiment) GetStats(name string) Stats

// Utility methods:
func (e *Experiment) NewStopwatch() *Stopwatch
func (e *Experiment) String() string
func (e *Experiment) ColorableString() string

Decorator functions:

func Units(string) Annotation
func Annotation(string) Annotation
func Style(string) Annotation
func Precision(any) PrecisionBundle

Performance Measurement

Structural Matching

Match complex struct, array, and map structures with field-level and element-level matchers.

// Struct matchers
func MatchAllFields(fields Fields) types.GomegaMatcher
func MatchFields(options Options, fields Fields) types.GomegaMatcher

// Array/Slice matchers
func MatchAllElements(identifier Identifier, elements Elements) types.GomegaMatcher
func MatchAllElementsWithIndex(identifier IdentifierWithIndex, elements Elements) types.GomegaMatcher
func MatchElements(identifier Identifier, options Options, elements Elements) types.GomegaMatcher
func MatchElementsWithIndex(identifier IdentifierWithIndex, options Options, elements Elements) types.GomegaMatcher

// Map matchers
func MatchAllKeys(keys Keys) types.GomegaMatcher
func MatchKeys(options Options, keys Keys) types.GomegaMatcher

// Pointer matcher
func PointTo(matcher types.GomegaMatcher) types.GomegaMatcher

// Utility matchers
func Ignore() types.GomegaMatcher
func Reject() types.GomegaMatcher

// Helper identifier
func IndexIdentity(index int, _ any) string

Types:

type Fields map[string]types.GomegaMatcher
type Elements map[string]types.GomegaMatcher
type Keys map[any]types.GomegaMatcher

type Identifier func(element any) string
type IdentifierWithIndex func(index int, element any) string

type Options int

Options constants:

const (
    IgnoreExtras Options = 1 << iota
    IgnoreMissing
    AllowDuplicates
    IgnoreUnexportedExtras
)

Structural Matching

Types

Common types used across multiple capabilities:

// Main Gomega interface
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()
}

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

// Synchronous assertion interface
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
}

// Asynchronous assertion interface
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
}

// Testing framework integration interface
type GomegaTestingT interface {
    Helper()
    Fatalf(format string, args ...any)
}

// Fail handler function type
type GomegaFailHandler func(message string, callerSkip ...int)

// Polling control error type
type PollingSignalError interface {
    error
}