hegel

package module
v0.9.32 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 26 Imported by: 0

README

[!IMPORTANT] We're excited you're checking out Hegel! Hegel is in beta, and we'd love for you to try it and report any feedback.

As part of our beta, we may make breaking changes if it makes Hegel a better property-based testing library. If that instability bothers you, please check back in a few months for a stable release!

See https://hegel.dev/compatibility for more details.

Hegel for Go

Hegel is a property-based testing library for Go.

Installation

To install: go get hegel.dev/go/hegel@latest.

Supported platforms:

  • Linux amd64/arm64
  • macOS arm64 (Apple Silicon)
  • Windows amd64/arm64.

Quickstart

Here's a quick example of how to write a Hegel test:

package example_test

import (
	"math"
	"slices"
	"testing"

	"hegel.dev/go/hegel"
)

func mySort(ls []int) []int {
	result := make([]int, len(ls))
	copy(result, ls)
	slices.Sort(result)
	result = slices.Compact(result)
	return result
}

func TestMatchesBuiltin(t *testing.T) {
	hegel.Test(t, func(ht *hegel.T) {
		slice1 := hegel.Draw(ht, hegel.Lists(hegel.Integers(math.MinInt, math.MaxInt)))
		slice2 := mySort(slice1)
		slices.Sort(slice1)
		if !slices.Equal(slice1, slice2) {
			ht.Fatalf("slices not equal: %v != %v", slice1, slice2)
		}
	})
}

This test will fail when run with go test! Hegel will produce a minimal failing test case for us:

example_test.go:46: slice1 := hegel.Draw(ht, hegel.Lists(hegel.Integers(math.MinInt, math.MaxInt))) = []int{0, 0}
example_test.go:50: slices not equal: [0 0] != [0]

Hegel reports the minimal example showing that our sort is incorrectly dropping duplicates. If we remove result = slices.Compact(result) from mySort(), this test will then pass (because it's just comparing the standard sort against itself).

Example workloads

  • The bank workload tests a PostgreSQL-compatible store by pretending to move balances around.
  • The ring workload looks for atomicity, isolation, and durability violations.

Documentation

Overview

Hegel is a property-based testing library for Go. Hegel is based on Hypothesis, using the Hegel protocol.

Getting started with Hegel for Go

This guide walks you through the basics of installing Hegel and writing your first tests.

Install Hegel

Add hegel to your module using go get:

go get hegel.dev/go/hegel@latest

Hegel calls into libhegel — the Rust engine shipped by the hegeldev/hegel project — via FFI.

Write your first test

You're now ready to write your first test. Hegel integrates directly with go test via Test:

func TestIntegerSelfEquality(t *testing.T) {
	hegel.Test(t, func(ht *hegel.T) {
		n := hegel.Draw(ht, hegel.Integers(math.MinInt, math.MaxInt))
		if n != n {
			ht.Fatal("integer was not equal to itself")
		}
	})
}

Now run the test using go test. You should see that this test passes.

Let's look at what's happening in more detail. Test runs your test many times (100, by default). The test function receives a *T, which is used with the Draw function for drawing different values. This test draws a random integer and checks that it should be equal to itself.

Next, try a test that fails:

func TestIntegersAlwaysBelow50(t *testing.T) {
	hegel.Test(t, func(ht *hegel.T) {
		n := hegel.Draw(ht, hegel.Integers(math.MinInt, math.MaxInt))
		if n >= 50 {
			ht.Fatalf("n=%d is too large", n)
		}
	})
}

This test asserts that any integer is less than 50, which is obviously incorrect. Hegel will find a test case that makes this assertion fail, and then shrink it to find the smallest counterexample — in this case, n = 50.

To fix this test, you can constrain the integers you generate with the min and max arguments to Integers:

func TestBoundedIntegersAlwaysBelow50(t *testing.T) {
	hegel.Test(t, func(ht *hegel.T) {
		n := hegel.Draw(ht, hegel.Integers(0, 49))
		if n >= 50 {
			ht.Fatalf("n=%d is too large", n)
		}
	})
}

Run the test again. It should now pass.

Use generators

Hegel provides a rich library of generators that you can use out of the box. There are primitive generators, such as Integers, Floats, and Text, and combinators that allow you to make generators out of other generators, such as Lists and Maps.

For example, you can use Lists to generate a slice of integers:

func TestAppendIncreasesLength(t *testing.T) {
	hegel.Test(t, func(ht *hegel.T) {
		slice := hegel.Draw(ht, hegel.Lists(hegel.Integers(math.MinInt, math.MaxInt)))
		initialLength := len(slice)
		slice = append(slice, hegel.Draw(ht, hegel.Integers(math.MinInt, math.MaxInt)))
		if len(slice) <= initialLength {
			ht.Fatal("length did not increase")
		}
	})
}

This test checks that appending an element to a random slice of integers should always increase its length.

You can also build composite data by drawing multiple values. For example, say you have a Person struct that we want to generate. Because generation in Hegel is imperative, you build the struct by drawing its fields directly:

func TestPerson(t *testing.T) {
	type Person struct {
		Age  int
		Name string
	}
	hegel.Test(t, func(ht *hegel.T) {
		person := Person{
			Age:  hegel.Draw(ht, hegel.Integers(0, 120)),
			Name: hegel.Draw(ht, hegel.Text().MinSize(1).MaxSize(50)),
		}
		_ = person // use person in your test
	})
}

Note that you can feed the results of a Draw to subsequent calls. For example, say that you extend the Person struct to include a DrivingLicense boolean field:

func TestPersonWithLicense(t *testing.T) {
	type Person struct {
		Age            int
		Name           string
		DrivingLicense bool
	}
	hegel.Test(t, func(ht *hegel.T) {
		age := hegel.Draw(ht, hegel.Integers(0, 120))
		name := hegel.Draw(ht, hegel.Text().MinSize(1).MaxSize(50))
		drivingLicense := false
		if age >= 18 {
			drivingLicense = hegel.Draw(ht, hegel.Booleans())
		}
		person := Person{Age: age, Name: name, DrivingLicense: drivingLicense}
		_ = person // use person in your test
	})
}

Debug your failing test cases

Use the TestCase.Note method to attach debug information:

func TestWithNotes(t *testing.T) {
	hegel.Test(t, func(ht *hegel.T) {
		x := hegel.Draw(ht, hegel.Integers(math.MinInt, math.MaxInt))
		y := hegel.Draw(ht, hegel.Integers(math.MinInt, math.MaxInt))
		ht.Note(fmt.Sprintf("x + y = %d, y + x = %d", x+y, y+x))
		if x+y != y+x {
			ht.Fatal("addition is not commutative")
		}
	})
}

Notes only appear when Hegel replays the minimal failing example.

Change the number of test cases

When go test is run with -short, Hegel reduces the number of test cases, overriding WithTestCases and profile settings.

By default Hegel runs 100 test cases. To override this, pass WithTestCases:

func TestIntegersMany(t *testing.T) {
	hegel.Test(t, func(ht *hegel.T) {
		n := hegel.Draw(ht, hegel.Integers(math.MinInt, math.MaxInt))
		if n != n {
			ht.Fatal("integer was not equal to itself")
		}
	}, hegel.WithTestCases(500))
}

Run as a standalone binary

To run a property test outside of go test — for example as a workload in a soak run or fuzzing harness — use Workload. It parses the usual CLI flags (--test-cases, --derandomize, --database, --suppress-health-check) and runs the body unbounded by default.

Learning more

  • Browse the function documentation for the full list of available generators.
  • See WithTestCases and other Option functions for more configuration settings to customize how your test runs.
  • See Workload for running a property test as a standalone CLI binary outside of go test.

Index

Examples

Constants

View Source
const (
	// FilterTooMuch indicates too many test cases are being filtered out via [TestCase.Assume].
	FilterTooMuch = libhegel.HC_FILTER_TOO_MUCH
	// TooSlow indicates test execution is too slow.
	TooSlow = libhegel.HC_TOO_SLOW
	// TestCasesTooLarge indicates generated test cases are too large.
	TestCasesTooLarge = libhegel.HC_TEST_CASES_TOO_LARGE
	// LargeInitialTestCase indicates the smallest natural input is very large.
	LargeInitialTestCase = libhegel.HC_LARGE_INITIAL_TEST_CASE
)
View Source
const (
	// BackendDefault expands a single seeded PRNG; runs are reproducible from
	// the seed and shrinking / replay work as usual.
	BackendDefault = libhegel.BACKEND_DEFAULT
	// BackendURandom reads fresh entropy from /dev/urandom on every draw.
	// Intended for running under Antithesis; you almost certainly don't want it
	// otherwise.
	BackendURandom = libhegel.BACKEND_URANDOM
)
View Source
const (
	// VerbosityQuiet suppresses engine logging.
	VerbosityQuiet = libhegel.VERBOSITY_QUIET
	// VerbosityNormal is the default logging level.
	VerbosityNormal = libhegel.VERBOSITY_NORMAL
	// VerbosityVerbose enables verbose logging.
	VerbosityVerbose = libhegel.VERBOSITY_VERBOSE
	// VerbosityDebug enables debug logging.
	VerbosityDebug = libhegel.VERBOSITY_DEBUG
)
View Source
const (
	// PhaseExplicit runs explicitly-provided examples.
	PhaseExplicit = libhegel.PHASE_EXPLICIT
	// PhaseReuse replays examples from the example database.
	PhaseReuse = libhegel.PHASE_REUSE
	// PhaseGenerate generates new examples.
	PhaseGenerate = libhegel.PHASE_GENERATE
	// PhaseTarget runs targeted-property search.
	PhaseTarget = libhegel.PHASE_TARGET
	// PhaseShrink shrinks failing examples.
	PhaseShrink = libhegel.PHASE_SHRINK
)

Variables

This section is empty.

Functions

func Draw

func Draw[T any](tc TestCase, g Generator[T]) T

Draw produces a value from a Generator using the given TestCase context.

Example
package main

import (
	"math"
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		n := hegel.Draw(ht, hegel.Integers(math.MinInt, math.MaxInt))
		s := hegel.Draw(ht, hegel.Text().MaxSize(50))
		_ = n // n is int
		_ = s // s is string
	})
}
Example (DependentGeneration)
package main

import (
	"math"
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		n := hegel.Draw(ht, hegel.Integers(1, 10))
		lst := hegel.Draw(ht, hegel.Lists(
			hegel.Integers(math.MinInt, math.MaxInt),
		).MinSize(int(n)).MaxSize(int(n)))
		index := hegel.Draw(ht, hegel.Integers(0, n-1))
		if index < 0 || index >= len(lst) {
			ht.Fatal("index out of range")
		}
	})
}

func MustRun

func MustRun(fn func(TestCase), opts ...Option)

MustRun runs a property test and panics if it fails.

func Run

func Run(fn func(TestCase), opts ...Option) error

Run runs a property test and returns any error.

Note output goes to stdout. For use in standalone binaries and conformance tests.

func RunStateful added in v0.3.4

func RunStateful[M any, T interface{ *M }](tc TestCase, machine T, opts ...StateMachineOption)

RunStateful enables model-based testing.

machine is a pointer to a struct which implements a state-machine in terms of rules and invariants.

Methods whose name starts with "Rule" and whose signature is func(TestCase) are registered as rules. Methods whose name starts with "Invariant" with the same signature are registered as invariants.

Rules run sequentially by default. Pass WithConcurrency or WithBoundedConcurrency to allow rules to run concurrently, and WithRuleGroup to restrict which rules may overlap. Pass WithStatefulStepCount to change the default limit of 50 rounds, and WithAlwaysCheckInvariants for invariants that must observe every join point. Other invariants are sampled between unconditional initial and final checks.

It panics if a method takes TestCase but is not prefixed with Rule or Invariant, if a Rule- or Invariant-prefixed method has the wrong signature, or if the machine has no rules.

Example
package main

import (
	"hegel.dev/go/hegel"
)

// stateCounter is a tiny state machine:
// every test case starts with a fresh counter and Hegel drives a sequence
// of rule invocations against it. The invariant fires if the counter
// ever leaves the sensible range.
type stateCounter struct{ n int }

func (c *stateCounter) reset() { c.n = 0 }

// RuleIncrement bumps the counter up by one.
func (c *stateCounter) RuleIncrement(_ hegel.TestCase) { c.n++ }

// RuleDecrement bumps the counter down by one.
func (c *stateCounter) RuleDecrement(_ hegel.TestCase) { c.n-- }

// InvariantSensible panics if the counter has drifted out of range.
func (c *stateCounter) InvariantSensible(_ hegel.TestCase) {
	if c.n < -10000 || c.n > 10000 {
		panic("counter out of sensible range")
	}
}

func main() {
	var c stateCounter
	hegel.MustRun(func(tc hegel.TestCase) {
		// Reset model state before each case — in a real scenario this
		// might flush a database or other shared store.
		c.reset()

		hegel.RunStateful(tc, &c)
	})
}
Example (Concurrent)
package main

import (
	"fmt"
	"maps"
	"runtime"
	"sync"
	"sync/atomic"
	"testing"

	"hegel.dev/go/hegel"
)

// concurrentKVStore is a tiny in-memory key-value store whose increment has a
// lost-update race: it reads the current value, releases the lock, and writes
// back the incremented value, so two workers incrementing the same key can
// each overwrite the other's update.
type concurrentKVStore struct {
	mu sync.Mutex
	m  map[int]int64
}

func newConcurrentKVStore() concurrentKVStore {
	return concurrentKVStore{m: make(map[int]int64)}
}

func (s *concurrentKVStore) get(key int) (int64, bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	value, ok := s.m[key]
	return value, ok
}

func (s *concurrentKVStore) put(key int, value int64) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.m[key] = value
}

func (s *concurrentKVStore) putIfAbsent(key int, value int64) bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	if _, ok := s.m[key]; ok {
		return false
	}
	s.m[key] = value
	return true
}

func (s *concurrentKVStore) increment(key int) {
	value, _ := s.get(key)
	runtime.Gosched() // Make the lost-update race easier to find.
	s.put(key, value+1)
}

func (s *concurrentKVStore) snapshot() map[int]int64 {
	s.mu.Lock()
	defer s.mu.Unlock()
	snapshot := make(map[int]int64, len(s.m))
	maps.Copy(snapshot, s.m)
	return snapshot
}

type concurrentKVTest struct {
	store      concurrentKVStore
	keys       *hegel.Pool[int]
	increments atomic.Int64
}

func (m *concurrentKVTest) RuleRegister(tc hegel.TestCase) {
	key := hegel.Draw(tc, hegel.Integers(0, 3))
	if m.store.putIfAbsent(key, 0) {
		m.keys.Add(tc, key)
	}
}

func (m *concurrentKVTest) RuleIncrement(tc hegel.TestCase) {
	key := hegel.Draw(tc, m.keys.ValuesReusable())
	m.store.increment(key)
	m.increments.Add(1)
}

func (m *concurrentKVTest) RuleRead(tc hegel.TestCase) {
	key := hegel.Draw(tc, m.keys.ValuesReusable())
	value, ok := m.store.get(key)
	tc.Note(fmt.Sprintf("read %d -> %d (present: %t)", key, value, ok))
}

func (m *concurrentKVTest) RuleSnapshot(tc hegel.TestCase) {
	tc.Note(fmt.Sprintf("snapshot holds %d keys", len(m.store.snapshot())))
}

func (m *concurrentKVTest) InvariantNoLostUpdates(tc hegel.TestCase) {
	var stored int64
	for _, value := range m.store.snapshot() {
		stored += value
	}
	performed := m.increments.Load()
	if stored != performed {
		tc.Errorf(
			"increments were lost: the store sums to %d after %d increments",
			stored,
			performed,
		)
	}
}

func main() {
	hegel.Test(new(testing.T), func(tc *hegel.T) {
		machine := &concurrentKVTest{
			store: newConcurrentKVStore(),
			keys:  hegel.NewPool[int](tc),
		}
		hegel.RunStateful(
			tc,
			machine,
			hegel.WithBoundedConcurrency(4),
			hegel.WithRuleGroup("operations", "RuleRegister", "RuleIncrement", "RuleRead"),
			hegel.WithRuleGroup("snapshot", "RuleRead", "RuleSnapshot"),
		)
	})
}

func Test added in v0.3.0

func Test(t *testing.T, fn func(*T), opts ...Option)

Test runs a property test against t.

When testing.Short is true, Test reduces the number of test cases, overriding WithTestCases and profile settings.

Example
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{} // in real code, use the *testing.T from your test function
	hegel.Test(t, func(ht *hegel.T) {
		n := hegel.Draw(ht, hegel.Integers(0, 200))
		if n >= 50 {
			ht.Fatalf("n=%d is too large", n)
		}
	})
}
Example (Assume)
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		n1 := hegel.Draw(ht, hegel.Integers(-1000, 1000))
		n2 := hegel.Draw(ht, hegel.Integers(-1000, 1000))
		ht.Assume(n2 != 0)
		q, r := n1/n2, n1%n2
		if n1 != q*n2+r {
			ht.Fatalf("%d != %d*%d + %d", n1, q, n2, r)
		}
	})
}
Example (DisableDatabase)
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		_ = hegel.Draw(ht, hegel.Booleans())
	}, hegel.WithDatabase("")) // empty path disables persistence
}
Example (Note)
package main

import (
	"fmt"
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		x := hegel.Draw(ht, hegel.Integers(-1000, 1000))
		y := hegel.Draw(ht, hegel.Integers(-1000, 1000))
		ht.Note(fmt.Sprintf("trying x=%d, y=%d", x, y))
		if x+y != y+x {
			ht.Fatal("addition is not commutative")
		}
	})
}
Example (Target)
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		x := hegel.Draw(ht, hegel.Integers(0, 10000))
		ht.Target(float64(x), "maximize_x")
		if x > 9999 {
			ht.Fatalf("x=%d exceeds limit", x)
		}
	}, hegel.WithTestCases(1000))
}
Example (WithDatabase)
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		n := hegel.Draw(ht, hegel.Integers(0, 100))
		if n < 0 {
			ht.Fatal("negative integer should not be generated")
		}
	}, hegel.WithDatabase("my_hegel_database"))
}
Example (WithDerandomize)
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		_ = hegel.Draw(ht, hegel.Integers(0, 100))
	}, hegel.WithDerandomize(true))
}
Example (WithSeed)
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		_ = hegel.Draw(ht, hegel.Integers(0, 100))
	}, hegel.WithSeed(42))
}
Example (WithTestCases)
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		a := hegel.Draw(ht, hegel.Integers(-1000, 1000))
		b := hegel.Draw(ht, hegel.Integers(-1000, 1000))
		if a+b != b+a {
			ht.Fatal("addition is not commutative")
		}
	}, hegel.WithTestCases(500))
}

func Workload added in v0.4.0

func Workload(fn func(TestCase), opts ...Option)

Workload runs a property test as a standalone CLI binary, parsing flags from os.Args.

Runs for an unbounded amount of time unless overridden via an option or flag.

opts are overridden by flags.

Example
package main

import (
	"hegel.dev/go/hegel"
)

func main() {
	hegel.Workload(func(tc hegel.TestCase) {
		_ = hegel.Draw(tc, hegel.Integers(0, 100))
	})
}

Types

type Backend added in v0.6.9

type Backend = libhegel.Backend

Backend selects the engine's source of randomness. Pass one to WithBackend.

type CharactersGenerator added in v0.2.0

type CharactersGenerator struct {
	// contains filtered or unexported fields
}

CharactersGenerator configures and generates single-character strings. Use Characters to create one, then chain builder methods to configure character filtering.

func Characters added in v0.2.0

func Characters() CharactersGenerator

Characters returns a CharactersGenerator that produces single-codepoint strings.

func (CharactersGenerator) Categories added in v0.2.0

func (g CharactersGenerator) Categories(cats []string) CharactersGenerator

Categories restricts generated characters to the given Unicode general categories.

func (CharactersGenerator) Codec added in v0.2.0

Codec restricts generated characters to those encodable in the given codec.

func (CharactersGenerator) ExcludeCategories added in v0.2.0

func (g CharactersGenerator) ExcludeCategories(cats []string) CharactersGenerator

ExcludeCategories excludes characters in the given Unicode general categories.

func (CharactersGenerator) ExcludeCharacters added in v0.2.0

func (g CharactersGenerator) ExcludeCharacters(chars string) CharactersGenerator

ExcludeCharacters always excludes these specific characters.

func (CharactersGenerator) IncludeCharacters added in v0.2.0

func (g CharactersGenerator) IncludeCharacters(chars string) CharactersGenerator

IncludeCharacters always includes these specific characters.

func (CharactersGenerator) MaxCodepoint added in v0.2.0

func (g CharactersGenerator) MaxCodepoint(cp rune) CharactersGenerator

MaxCodepoint sets the maximum Unicode codepoint.

func (CharactersGenerator) MinCodepoint added in v0.2.0

func (g CharactersGenerator) MinCodepoint(cp rune) CharactersGenerator

MinCodepoint sets the minimum Unicode codepoint.

type DateGenerator added in v0.9.0

type DateGenerator struct {
	// contains filtered or unexported fields
}

DateGenerator generates dates at midnight UTC within inclusive bounds.

func Dates

func Dates() DateGenerator

Dates returns a DateGenerator with default bounds of 0001-01-01 and 9999-12-31. Custom bounds may use years from -999999 through 999999.

func (DateGenerator) Max added in v0.9.0

Max sets the inclusive maximum from v's date fields. It ignores the time and location.

func (DateGenerator) Min added in v0.9.0

Min sets the inclusive minimum from v's date fields. It ignores the time and location.

type DatetimeGenerator added in v0.9.0

type DatetimeGenerator struct {
	// contains filtered or unexported fields
}

DatetimeGenerator generates UTC datetimes within inclusive bounds.

func Datetimes

func Datetimes() DatetimeGenerator

Datetimes returns a DatetimeGenerator with default bounds from 0001-01-01 through the last nanosecond of 9999-12-31. Custom bounds may use years from -999999 through 999999.

func (DatetimeGenerator) Max added in v0.9.0

Max sets the inclusive maximum from v's wall-clock fields. It ignores the location.

func (DatetimeGenerator) Min added in v0.9.0

Min sets the inclusive minimum from v's wall-clock fields. It ignores the location.

type DefaultOption added in v0.9.21

type DefaultOption struct {
	// contains filtered or unexported fields
}

DefaultOption configures a generator constructed by Default.

Use WithGenerator or WithFieldGenerator to construct an option; the zero value is invalid.

func WithFieldGenerator added in v0.9.22

func WithFieldGenerator[S, T any](field string, g Generator[T]) DefaultOption

WithFieldGenerator overrides the default generator for a field of S.

S must be a struct, and field must name a direct exported field whose type is exactly T. The override applies wherever S occurs. Type overrides for T take precedence over field overrides. An override for S replaces the whole struct.

WithFieldGenerator returns an option for Default. It panics if these requirements are not met.

func WithGenerator added in v0.9.21

func WithGenerator[T any](g Generator[T]) DefaultOption

WithGenerator overrides the default generator for T.

The generator applies to every occurrence of the exact type T, including nested fields and collection elements. It takes precedence over built-in generators and allows types that Default otherwise cannot construct.

WithGenerator returns an option for Default.

type DomainGenerator

type DomainGenerator struct {
	// contains filtered or unexported fields
}

DomainGenerator configures and generates domain name strings. Use Domains to create one, then chain builder methods to configure it. Invalid configurations panic on the first Draw call.

func Domains

func Domains() DomainGenerator

Domains returns a Generator that produces domain name strings.

func (DomainGenerator) MaxLength

func (g DomainGenerator) MaxLength(n int) DomainGenerator

MaxLength sets the maximum domain length.

type FloatGenerator

type FloatGenerator[T float] struct {
	// contains filtered or unexported fields
}

FloatGenerator configures and generates floating-point values of type T. Use Floats to create one, then chain builder methods to configure bounds and behavior. Invalid configurations panic on the first Draw call.

func Floats

func Floats[T float]() FloatGenerator[T]

Floats returns a FloatGenerator that produces floating-point values of type T. Configure bounds and behavior by chaining builder methods.

hegel.Floats[float64]()                         // any float64 including NaN and Inf
hegel.Floats[float64]().Min(0).Max(1)           // bounded [0, 1]
hegel.Floats[float32]().Min(0).ExcludeMin()     // (0, +Inf)

func (FloatGenerator[T]) AllowInfinity

func (g FloatGenerator[T]) AllowInfinity(v bool) FloatGenerator[T]

AllowInfinity sets whether the generator may produce infinite values. Default: true unless both bounds are set.

func (FloatGenerator[T]) AllowNaN

func (g FloatGenerator[T]) AllowNaN(v bool) FloatGenerator[T]

AllowNaN sets whether the generator may produce NaN values. Default: true when no bounds are set, false otherwise.

func (FloatGenerator[T]) ExcludeMax

func (g FloatGenerator[T]) ExcludeMax() FloatGenerator[T]

ExcludeMax excludes the upper bound from the generated range.

func (FloatGenerator[T]) ExcludeMin

func (g FloatGenerator[T]) ExcludeMin() FloatGenerator[T]

ExcludeMin excludes the lower bound from the generated range.

func (FloatGenerator[T]) Max

func (g FloatGenerator[T]) Max(v T) FloatGenerator[T]

Max sets the maximum value for the float generator.

func (FloatGenerator[T]) Min

func (g FloatGenerator[T]) Min(v T) FloatGenerator[T]

Min sets the minimum value for the float generator.

type Generator

type Generator[T any] interface {
	// contains filtered or unexported methods
}

Generator is the core abstraction for value generation in Hegel.

It is a sealed interface — only types within this package can implement it.

func Binary

func Binary(minSize int, maxSize int) Generator[[]byte]

Binary returns a Generator that produces byte slices with length in [minSize, maxSize].

Pass maxSize < 0 for unbounded. Invalid bounds produce an error when the generator is drawn.

func Booleans

func Booleans() Generator[bool]

Booleans returns a Generator that produces boolean values.

func Composite added in v0.3.3

func Composite[T any](fn func(TestCase) T) Generator[T]

Composite returns a Generator backed by an imperative function.

Inside fn, call Draw on other generators to assemble the value. The function may call Draw any number of times.

Example: a generator for a Person whose driving license field only appears when age >= 18.

type Person struct {
    Name           string
    Age            int
    DrivingLicense bool
}

personGen := hegel.Composite(func(tc hegel.TestCase) Person {
    age := hegel.Draw(tc, hegel.Integers(0, 120))
    name := hegel.Draw(tc, hegel.Text())
    p := Person{Age: age, Name: name}
    if age >= 18 {
        p.DrivingLicense = hegel.Draw(tc, hegel.Booleans())
    }
    return p
})

hegel.Test(t, func(ht *hegel.T) {
    p := hegel.Draw(ht, personGen)
    // assert properties of p
})
Example
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	type person struct {
		Name string
		Age  int
	}

	personGen := hegel.Composite(func(tc hegel.TestCase) person {
		return person{
			Name: hegel.Draw(tc, hegel.Text()),
			Age:  hegel.Draw(tc, hegel.Integers(0, 120)),
		}
	})

	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		p := hegel.Draw(ht, personGen)
		if p.Age < 0 || p.Age > 120 {
			ht.Fatalf("age out of range: %d", p.Age)
		}
	})
}
Example (DataDependentDrawCount)
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	variableList := hegel.Composite(func(tc hegel.TestCase) []int {
		n := hegel.Draw(tc, hegel.Integers(0, 10))
		out := make([]int, n)
		for i := range n {
			out[i] = hegel.Draw(tc, hegel.Integers(0, 1000))
		}
		return out
	})

	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		v := hegel.Draw(ht, variableList)
		if len(v) > 10 {
			ht.Fatalf("length %d exceeds bound", len(v))
		}
	})
}

func Default added in v0.9.16

func Default[T any](options ...DefaultOption) Generator[T]

Default constructs a generator for T.

Supported types are booleans, integers, floats, strings, arrays, slices, maps, pointers, and structs with exported fields, including named types. The element type of a zero-length array is not inspected. Integers use the full range of their type. Slices and maps may be empty, and pointers may be nil. Well-known types use their specialized generators: time.Time uses Datetimes, netip.Addr uses IPAddresses, and uuid.UUID uses UUIDs (Go 1.27 and later).

Options override generators for exact types or struct fields; the last option for a type or field wins.

Default returns the same cached generator for each type when no options are supplied. Calls with options construct a fresh generator. It panics at construction for invalid options or recursive or unsupported types that are not handled by an override.

func Emails

func Emails() Generator[string]

Emails returns a Generator that produces email address strings.

func Filter

func Filter[T any](g Generator[T], pred func(T) bool) Generator[T]

Filter returns a Generator that only produces values from g that satisfy pred.

It tries up to 3 times per test case; if all fail, the test case is rejected.

Example
package main

import (
	"math"
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		evenIntegers := hegel.Filter(hegel.Integers(math.MinInt, math.MaxInt), func(v int) bool {
			return v%2 == 0
		})
		n := hegel.Draw(ht, evenIntegers)
		if n%2 != 0 {
			ht.Fatalf("%d is not even", n)
		}
	})
}

func FlatMap

func FlatMap[T, U any](g Generator[T], f func(T) Generator[U]) Generator[U]

FlatMap returns a Generator that generates a value from g, passes it to f, and generates from the returned Generator.

Example
package main

import (
	"math"
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		result := hegel.Draw(ht, hegel.FlatMap(
			hegel.Integers(1, 5),
			func(n int) hegel.Generator[[]int] {
				return hegel.Lists(
					hegel.Integers(math.MinInt, math.MaxInt),
				).MinSize(n).MaxSize(n)
			},
		))
		if len(result) < 1 || len(result) > 5 {
			ht.Fatalf("unexpected list length: %d", len(result))
		}
	})
}

func FromRegex

func FromRegex(pattern string, fullmatch bool) Generator[string]

FromRegex returns a Generator that produces strings matching the given regular expression.

func Integers

func Integers[T integer](minVal, maxVal T) Generator[T]

Integers returns a Generator that produces integer values in [minVal, maxVal]. For unbounded generation, use the full range of the type:

hegel.Integers[int](math.MinInt, math.MaxInt)
hegel.Integers[uint](0, math.MaxUint)

func Just

func Just[T any](value T) Generator[T]

Just returns a Generator that always produces the given constant value.

func Map

func Map[T, U any](g Generator[T], fn func(T) U) Generator[U]

Map returns a new Generator that applies fn to each value from g.

Example
package main

import (
	"fmt"
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		s := hegel.Draw(ht, hegel.Map(hegel.Integers(0, 100), func(n int) string {
			return fmt.Sprintf("%d", n)
		}))
		for _, c := range s {
			if c < '0' || c > '9' {
				ht.Fatalf("%q contains non-digit %c", s, c)
			}
		}
	})
}

func OneOf

func OneOf[T any](generators ...Generator[T]) Generator[T]

OneOf returns a Generator that produces values from one of the given generators.

Requires at least 1 generator.

func Optional

func Optional[T any](element Generator[T]) Generator[*T]

Optional returns a Generator that produces either nil (as *T) or a value from element.

func SampledFrom

func SampledFrom[T any](values []T) Generator[T]

SampledFrom returns a Generator that picks at random from values.

Panics if values is empty.

func URLs

func URLs() Generator[string]

URLs returns a Generator that produces URL strings according to RFC3986.

The scheme is either "http" or "https".

func WeightedBooleans added in v0.9.0

func WeightedBooleans(p float64) Generator[bool]

WeightedBooleans returns a Generator that produces true with probability p. The probability must be within [0, 1]. Values 0 and 1 produce constants without consuming entropy.

type HealthCheck

type HealthCheck = libhegel.HealthCheck

HealthCheck identifies a health check that can be suppressed during a run.

Health checks detect common issues with test configuration that would otherwise cause tests to run inefficiently or not at all.

func AllHealthChecks

func AllHealthChecks() []HealthCheck

AllHealthChecks returns all health check variants.

type IPAddressGenerator

type IPAddressGenerator struct {
	// contains filtered or unexported fields
}

IPAddressGenerator configures and generates IP addresses. Use IPAddresses to create one, then chain builder methods to configure it.

func IPAddresses

func IPAddresses() IPAddressGenerator

IPAddresses returns a Generator that produces IP addresses.

func (IPAddressGenerator) IPv4

IPv4 restricts the generator to IPv4 addresses only.

func (IPAddressGenerator) IPv6

IPv6 restricts the generator to IPv6 addresses only.

type ListGenerator

type ListGenerator[T any] struct {
	// contains filtered or unexported fields
}

ListGenerator configures and generates slices of values from an element generator. Use Lists to create one, then chain builder methods to configure bounds. Invalid configurations panic on the first Draw call.

func Lists

func Lists[T any](elements Generator[T]) ListGenerator[T]

Lists returns a Generator that produces slices of values from the elements generator.

func (ListGenerator[T]) MaxSize

func (g ListGenerator[T]) MaxSize(n int) ListGenerator[T]

MaxSize sets the maximum number of elements (inclusive).

func (ListGenerator[T]) MinSize

func (g ListGenerator[T]) MinSize(n int) ListGenerator[T]

MinSize sets the minimum number of elements (inclusive). Default: 0.

type MapGenerator added in v0.2.0

type MapGenerator[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapGenerator configures and generates map[K]V values. Use Maps to create one, then chain builder methods to configure bounds. Invalid configurations panic on the first Draw call.

func Maps added in v0.2.0

func Maps[K comparable, V any](keys Generator[K], values Generator[V]) MapGenerator[K, V]

Maps returns a Generator that produces map[K]V values.

func (MapGenerator[K, V]) MaxSize added in v0.2.0

func (g MapGenerator[K, V]) MaxSize(n int) MapGenerator[K, V]

MaxSize sets the maximum number of key-value pairs.

func (MapGenerator[K, V]) MinSize added in v0.2.0

func (g MapGenerator[K, V]) MinSize(n int) MapGenerator[K, V]

MinSize sets the minimum number of key-value pairs. Default: 0.

type Option

type Option func(*runOptions)

Option is a functional option for Test and Run.

func SuppressHealthCheck

func SuppressHealthCheck(checks ...HealthCheck) Option

SuppressHealthCheck suppresses the given health checks so they do not cause test failure.

Each call sets the complete suppression mask; calls do not accumulate, so when SuppressHealthCheck is passed more than once the last call wins. Pass every check to suppress in a single call.

func WithBackend added in v0.6.9

func WithBackend(b Backend) Option

WithBackend selects the engine's randomness backend. See Backend. The default comes from the active libhegel settings profile.

func WithDatabase added in v0.3.2

func WithDatabase(path string) Option

WithDatabase configures example-database persistence for this test. A non-empty path persists failing examples to that directory; an empty path disables persistence entirely, so no failing examples are saved or replayed.

The default (when WithDatabase is not specified) is to use libhegel's default database location, except in CI environments where the database is automatically disabled.

func WithDerandomize added in v0.3.2

func WithDerandomize(derandomize bool) Option

WithDerandomize sets whether to use a fixed seed for reproducible runs.

func WithPhases added in v0.6.9

func WithPhases(phases ...Phase) Option

WithPhases restricts the run to the given test phases. See Phase and AllPhases. The active profile supplies the default; the base profile runs all phases.

func WithProfile added in v0.8.3

func WithProfile(name string) Option

WithProfile uses the named profile as the base settings. Other options override the profile. An empty name uses the process-wide default profile.

func WithReportMultipleFailures added in v0.6.9

func WithReportMultipleFailures(report bool) Option

WithReportMultipleFailures sets whether the engine reports every distinct counterexample it finds rather than stopping at the first.

func WithReproductionBlob added in v0.9.4

func WithReproductionBlob(show bool) Option

WithReproductionBlob controls whether failure output includes the base64 reproduction blob for the counterexample. The blob remains available to the runner for replay regardless of this setting.

func WithSeed added in v0.5.1

func WithSeed(seed int64) Option

WithSeed sets a fixed random seed for the test, making it deterministic.

func WithStatistics added in v0.9.3

func WithStatistics(show bool) Option

WithStatistics controls end-of-run statistics for events recorded with TestCase.Event and TestCase.EventValue. Statistics are disabled by default. A nonempty HEGEL_STATISTICS value other than "0" enables statistics unless WithStatistics is set.

func WithTestCases

func WithTestCases(n int) Option

WithTestCases sets the number of test cases to run.

func WithVerbosity added in v0.6.9

func WithVerbosity(v Verbosity) Option

WithVerbosity sets how much the engine logs during a run. See Verbosity. The active profile supplies the default; the base profile uses VerbosityNormal.

type Phase added in v0.6.9

type Phase = libhegel.Phase

Phase identifies one phase of a property-test run. Phases can be combined and passed to WithPhases to restrict which phases the engine runs.

func AllPhases added in v0.6.9

func AllPhases() []Phase

AllPhases returns all phase variants.

type Pool added in v0.6.32

type Pool[T any] struct {
	// contains filtered or unexported fields
}

Pool is an engine-managed collection of values generated during a stateful test. It is safe to share between concurrent state-machine workers.

A Pool belongs to the test case in which NewPool created it. Create a new pool with each new state-machine value; do not retain it between test cases.

func NewPool added in v0.6.32

func NewPool[T any](tc TestCase) *Pool[T]

NewPool creates an empty value pool for a stateful test.

Concurrent rules may share the returned pool. Operations that add or draw a value must receive the calling rule's TestCase, so each worker uses its own clone of the native test-case handle.

func (*Pool[T]) Add added in v0.6.32

func (p *Pool[T]) Add(tc TestCase, value T)

Add registers value with the pool.

func (*Pool[T]) IsEmpty added in v0.6.32

func (p *Pool[T]) IsEmpty() bool

IsEmpty reports whether the pool contains no values.

func (*Pool[T]) Len added in v0.6.32

func (p *Pool[T]) Len() int

Len returns the number of values currently in the pool.

func (*Pool[T]) ValuesConsumed added in v0.6.32

func (p *Pool[T]) ValuesConsumed() Generator[T]

ValuesConsumed returns a generator that draws and removes values from the pool.

Drawing from an empty pool rejects the current rule as though it called TestCase.Assume with false.

func (*Pool[T]) ValuesReusable added in v0.6.32

func (p *Pool[T]) ValuesReusable() Generator[T]

ValuesReusable returns a generator that draws values without removing them from the pool.

Drawing from an empty pool rejects the current rule as though it called TestCase.Assume with false.

type RecursiveGenerator added in v0.9.2

type RecursiveGenerator[T any] struct {
	// contains filtered or unexported fields
}

RecursiveGenerator generates recursively defined values within configurable depth and leaf limits. Invalid limits panic when the generator is drawn.

func Recursive added in v0.9.2

func Recursive[T any](leaf Generator[T], branch func(Generator[T]) Generator[T]) RecursiveGenerator[T]

Recursive returns a generator for recursively defined values.

The leaf generator produces terminal values. The branch function receives a generator for child values and returns a generator that combines its children. The default maximum depth is 32 and the default leaf budget is 100.

Example
package main

import (
	"testing"

	"hegel.dev/go/hegel"
)

func main() {
	type Node struct {
		Value int
		Left  *Node
		Right *Node
	}

	leaf := hegel.Map(hegel.Integers(0, 100), func(value int) *Node {
		return &Node{Value: value}
	})
	nodeGen := hegel.Recursive(leaf, func(subtree hegel.Generator[*Node]) hegel.Generator[*Node] {
		return hegel.Composite(func(tc hegel.TestCase) *Node {
			return &Node{
				Left:  hegel.Draw(tc, subtree),
				Right: hegel.Draw(tc, subtree),
			}
		})
	}).MaxDepth(5).MaxLeaves(20)

	t := &testing.T{}
	hegel.Test(t, func(ht *hegel.T) {
		_ = hegel.Draw(ht, nodeGen)
	})
}

func (RecursiveGenerator[T]) MaxDepth added in v0.9.2

func (g RecursiveGenerator[T]) MaxDepth(n int) RecursiveGenerator[T]

MaxDepth sets the maximum number of nested branches. Zero generates only leaves. The default is 32.

func (RecursiveGenerator[T]) MaxLeaves added in v0.9.2

func (g RecursiveGenerator[T]) MaxLeaves(n int) RecursiveGenerator[T]

MaxLeaves sets the maximum number of leaves in one generated value. The default is 100.

type StateMachineOption added in v0.6.32

type StateMachineOption func(*stateMachine)

StateMachineOption configures a state machine run.

func WithAlwaysCheckInvariants added in v0.8.1

func WithAlwaysCheckInvariants(invariants ...string) StateMachineOption

WithAlwaysCheckInvariants marks invariants that must run at every join point (after every rule in a sequential machine). Other invariants are sampled at intermediate states and run with probability 1 / the configured step count. All invariants run unconditionally on the initial and final states.

Pass the full method names, including the Invariant prefix. Calls are additive. RunStateful panics if a name is not a discovered invariant.

func WithBoundedConcurrency added in v0.6.32

func WithBoundedConcurrency(n int) StateMachineOption

WithBoundedConcurrency is like WithConcurrency, but uses n instead of runtime.GOMAXPROCS as the maximum worker count.

n is an upper bound, not a guarantee that every test case runs n rules at once.

func WithConcurrency added in v0.6.32

func WithConcurrency() StateMachineOption

WithConcurrency allows state machine rules to run concurrently. The engine chooses a worker count between 1 and runtime.GOMAXPROCS for each test case and may change it between rounds, so concurrent execution is not guaranteed for every round.

Workers invoke rule methods concurrently on the same machine value. Any state read or mutated by rules must therefore be safe for concurrent access, for example through mutexes or atomics. Rules must not depend on their relative ordering. Each worker receives its own TestCase, so the TestCase passed to one rule must not be retained or shared with another worker.

Execution proceeds in rounds. After every worker has finished its rules for a round, selected invariants run before the next round begins: ordinary invariants are sampled, while those configured with WithAlwaysCheckInvariants always run. Invariants are never executed concurrently.

func WithRuleGroup added in v0.6.32

func WithRuleGroup(name string, rules ...string) StateMachineOption

WithRuleGroup assigns rules to a named concurrency group. Rules in the same group may run concurrently with each other; rules that share no group never overlap. Pass the full method names, including the Rule prefix. Calls using the same group name add rules to that group.

Each round, the engine picks one group and hands out only that group's rules. Rules not mentioned by any call share one implicit default group, so they may overlap with each other but not with rules in an explicit group. A rule named by several calls belongs to every group named, and runs in the rounds of each of them, so it may overlap the rules of every group it belongs to while those groups' other rules never overlap each other.

RunStateful panics if a group is empty or names an unknown rule or invariant.

func WithStatefulStepCount added in v0.6.24

func WithStatefulStepCount(n int) StateMachineOption

WithStatefulStepCount sets the maximum number of rounds for this RunStateful invocation. With sequential rules, each round is one completed rule. The default is 50. RunStateful panics if n is less than 1.

type T

type T struct {
	*testing.T
	// contains filtered or unexported fields
}

T is the test context for property tests run via Test.

It embeds *testing.T and overrides methods like Fatal and Skip so they work correctly inside a Hegel test body.

func (T) Assume added in v0.5.0

func (s T) Assume(condition bool)

Assume rejects the current test case if condition is false.

func (*T) Error

func (t *T) Error(args ...any)

Error logs the message via the embedded *testing.T and aborts the current invocation.

func (*T) Errorf

func (t *T) Errorf(format string, args ...any)

Errorf logs the formatted message via the embedded *testing.T and aborts the current invocation.

func (T) Event added in v0.9.3

func (s T) Event(label string)

func (T) EventValue added in v0.9.3

func (s T) EventValue(label string, value float64)

func (T) Fail

func (s T) Fail()

func (T) FailNow

func (s T) FailNow()

func (*T) Failed

func (t *T) Failed() bool

Failed is false while the invocation is running. Failure methods abort the invocation immediately, so user code cannot observe a failed live context.

func (*T) Fatal

func (t *T) Fatal(args ...any)

Fatal logs the message via the embedded *testing.T and marks the test case as failed.

func (*T) Fatalf

func (t *T) Fatalf(format string, args ...any)

Fatalf logs the formatted message via the embedded *testing.T and marks the test case as failed.

func (*T) Log

func (t *T) Log(args ...any)

Log routes the message through the embedded *testing.T.

func (*T) Logf

func (t *T) Logf(format string, args ...any)

Logf routes the formatted message through the embedded *testing.T.

func (T) Note added in v0.5.0

func (s T) Note(message string)

func (*T) Run

func (t *T) Run(_ string, _ func(*testing.T)) bool

Run aborts the test — nested sub-tests inside a Hegel property test are not supported.

func (*T) Skip

func (t *T) Skip(_ ...any)

Skip discards the current test case.

func (*T) SkipNow

func (t *T) SkipNow()

SkipNow discards the current test case.

func (*T) Skipf

func (t *T) Skipf(_ string, _ ...any)

Skipf discards the current test case.

func (T) Target added in v0.5.0

func (s T) Target(value float64, label string)

type TestCase

type TestCase interface {
	// Assume rejects the current test case if condition is false.
	Assume(condition bool)

	// Note prints message during the final (replay) test case. Output is routed
	// to t.Log for [Test], or stdout for [Run].
	Note(message string)

	// Event records an occurrence under label for optional end-of-run statistics.
	Event(label string)

	// EventValue records a finite numeric observation under label for optional end-of-run statistics.
	EventValue(label string, value float64)

	// Target sends a target value to guide test generation.
	Target(value float64, label string)

	// Errorf logs the formatted message via Note and  aborts the test case.
	//
	// This is different than [testing.T.Errorf] which continues running the test.
	Errorf(format string, args ...any)

	// Fail behaves like [FailNow].
	//
	// This is different than [testing.T.Fail] which continues running the test.
	Fail()

	// FailNow marks the test case as failed and stops the test body.
	FailNow()

	// Log routes the message through Note (only emitted on final replay).
	Log(args ...any)
	// contains filtered or unexported methods
}

TestCase is the test context for a Hegel property test.

It is passed to Run bodies and Composite callbacks directly, and is embedded in the *T passed to Test bodies, so generator code written against TestCase works under either entry point.

type TextGenerator added in v0.2.0

type TextGenerator struct {
	// contains filtered or unexported fields
}

TextGenerator configures and generates Unicode text strings. Use Text to create one, then chain builder methods to configure the size bounds and character filtering. Invalid configurations panic on the first Draw call.

func Text

func Text() TextGenerator

Text returns a TextGenerator that produces string values. By default strings have no size bounds; use TextGenerator.MinSize and TextGenerator.MaxSize to constrain the codepoint count.

func (TextGenerator) Alphabet added in v0.2.0

func (g TextGenerator) Alphabet(chars string) TextGenerator

Alphabet restricts generated strings to only contain characters from the given set. Mutually exclusive with the character filtering methods like Codec, Categories, MinCodepoint, etc.

func (TextGenerator) Categories added in v0.2.0

func (g TextGenerator) Categories(cats []string) TextGenerator

Categories restricts generated characters to those in the given Unicode general categories (e.g. []string{"L", "Nd"}).

func (TextGenerator) Codec added in v0.2.0

func (g TextGenerator) Codec(codec string) TextGenerator

Codec restricts generated text to characters encodable in the given codec (e.g. "ascii", "utf-8", "latin-1").

func (TextGenerator) ExcludeCategories added in v0.2.0

func (g TextGenerator) ExcludeCategories(cats []string) TextGenerator

ExcludeCategories excludes characters in the given Unicode general categories.

func (TextGenerator) ExcludeCharacters added in v0.2.0

func (g TextGenerator) ExcludeCharacters(chars string) TextGenerator

ExcludeCharacters always excludes these specific characters.

func (TextGenerator) IncludeCharacters added in v0.2.0

func (g TextGenerator) IncludeCharacters(chars string) TextGenerator

IncludeCharacters always includes these specific characters, even if excluded by other filters.

func (TextGenerator) MaxCodepoint added in v0.2.0

func (g TextGenerator) MaxCodepoint(cp rune) TextGenerator

MaxCodepoint sets the maximum Unicode codepoint.

func (TextGenerator) MaxSize added in v0.2.0

func (g TextGenerator) MaxSize(n int) TextGenerator

MaxSize sets the maximum codepoint count for generated strings.

func (TextGenerator) MinCodepoint added in v0.2.0

func (g TextGenerator) MinCodepoint(cp rune) TextGenerator

MinCodepoint sets the minimum Unicode codepoint.

func (TextGenerator) MinSize added in v0.2.0

func (g TextGenerator) MinSize(n int) TextGenerator

MinSize sets the minimum codepoint count for generated strings.

type UUIDGenerator added in v0.6.31

type UUIDGenerator struct {
	// contains filtered or unexported fields
}

UUIDGenerator configures and generates UUID values. Use UUIDs to create one, then chain builder methods to configure it.

func UUIDs added in v0.6.31

func UUIDs() UUIDGenerator

UUIDs returns a Generator that produces UUID values.

func (UUIDGenerator) Version added in v0.6.31

func (g UUIDGenerator) Version(version int) UUIDGenerator

Version restricts the generator to a specific RFC 4122 version (1–5).

type UniqueListGenerator added in v0.9.15

type UniqueListGenerator[T any, K comparable] struct {
	// contains filtered or unexported fields
}

UniqueListGenerator generates slices with distinct keys.

Invalid configurations panic on the first Draw call.

func UniqueLists added in v0.9.15

func UniqueLists[T comparable](elements Generator[T]) UniqueListGenerator[T, T]

UniqueLists returns a generator of slices with distinct elements.

Elements retain draw order. The minimum size defaults to zero; the maximum is unbounded.

func UniqueListsBy added in v0.9.15

func UniqueListsBy[T any, K comparable](elements Generator[T], key func(T) K) UniqueListGenerator[T, K]

UniqueListsBy returns a generator of slices with distinct keys.

The key function must be deterministic. Interface values in its keys must hold comparable values.

Elements retain draw order. The minimum size defaults to zero; the maximum is unbounded.

func (UniqueListGenerator[T, K]) MaxSize added in v0.9.15

func (g UniqueListGenerator[T, K]) MaxSize(n int) UniqueListGenerator[T, K]

MaxSize sets the maximum number of distinct elements, inclusive.

func (UniqueListGenerator[T, K]) MinSize added in v0.9.15

func (g UniqueListGenerator[T, K]) MinSize(n int) UniqueListGenerator[T, K]

MinSize sets the minimum number of distinct elements, inclusive.

The minimum defaults to zero.

type Verbosity added in v0.6.9

type Verbosity = libhegel.Verbosity

Verbosity controls how much the engine logs during a run. Pass one to WithVerbosity.

Source Files

  • collections.go
  • combinators.go
  • composite.go
  • default.go
  • draw_report.go
  • generators.go
  • hegel.go
  • labels.go
  • pool.go
  • primitives.go
  • recursive.go
  • runner.go
  • state.go
  • stateful.go
  • uuid.go
  • workload.go

Directories

Path Synopsis
examples
bank command
Bank tests PostgreSQL-compatible stores using concurrent transactions.
Bank tests PostgreSQL-compatible stores using concurrent transactions.
ring command
Ring looks for atomicity, isolation, and durability violations in PostgreSQL-compatible stores.
Ring looks for atomicity, isolation, and durability violations in PostgreSQL-compatible stores.
internal
cgo

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL