Ginkgo provides extensive configuration options for controlling test execution, parallelization, filtering, timeouts, and reporting.
Configuration controlling how an individual test suite is run.
type SuiteConfig struct {
// Randomization
RandomSeed int64
RandomizeAllSpecs bool
// Filtering
FocusStrings []string
SkipStrings []string
FocusFiles []string
SkipFiles []string
LabelFilter string
SemVerFilter string
// Failure handling
FailOnPending bool
FailOnEmpty bool
FailFast bool
FlakeAttempts int
MustPassRepeatedly int
// Execution control
DryRun bool
Timeout time.Duration
GracePeriod time.Duration
// Parallelization
ParallelProcess int
ParallelTotal int
ParallelHost string
// Progress reporting
PollProgressAfter time.Duration
PollProgressInterval time.Duration
EmitSpecProgress bool
SourceRoots []string
// Output
OutputInterceptorMode string
}Constructor:
func NewDefaultSuiteConfig() SuiteConfigExample:
config := types.NewDefaultSuiteConfig()
config.RandomSeed = 1234
config.FailFast = true
config.Timeout = 30 * time.MinuteRandomSeed (int64): Seed for randomization. Use same seed to reproduce test order.RandomizeAllSpecs (bool): If true, randomize all specs together. If false, only randomize top-level containers.FocusStrings ([]string): Regular expressions to focus specs. Only matching specs run.SkipStrings ([]string): Regular expressions to skip specs. Matching specs don't run.FocusFiles ([]string): File filters to focus specs (e.g., "file.go:10-20").SkipFiles ([]string): File filters to skip specs.LabelFilter (string): Label filter expression (e.g., "integration && !slow").SemVerFilter (string): Semantic version filter (e.g., ">=1.0.0").FailOnPending (bool): Fail suite if any specs are pending.FailOnEmpty (bool): Fail suite if no specs run.FailFast (bool): Stop running after first failure.FlakeAttempts (int): Default retry attempts for flaky specs.MustPassRepeatedly (int): Default number of times specs must pass.DryRun (bool): Walk test tree without running tests.Timeout (time.Duration): Maximum duration for entire suite.GracePeriod (time.Duration): Grace period for cleanup after interrupt.ParallelProcess (int): Current process number (1-indexed).ParallelTotal (int): Total number of parallel processes.ParallelHost (string): Address of parallel coordination server.PollProgressAfter (time.Duration): Emit progress if node hasn't completed after this duration.PollProgressInterval (time.Duration): Rate of progress reports after PollProgressAfter.EmitSpecProgress (bool): Deprecated - kept for backward compatibility.SourceRoots ([]string): Directories to search for source code in progress reports.OutputInterceptorMode (string): Output interception strategy ("dup", "swap", or "none").Configuration for Ginkgo's reporter and output formatting.
type ReporterConfig struct {
// Output formatting
NoColor bool
Succinct bool
Verbose bool
VeryVerbose bool
FullTrace bool
ShowNodeEvents bool
GithubOutput bool
SilenceSkips bool
ForceNewlines bool
// Report files
JSONReport string
GoJSONReport string
JUnitReport string
TeamcityReport string
}Constructor:
func NewDefaultReporterConfig() ReporterConfigMethods:
func (rc ReporterConfig) WillGenerateReport() boolExample:
config := types.NewDefaultReporterConfig()
config.Verbose = true
config.JSONReport = "results.json"
config.JUnitReport = "results.xml"
if config.WillGenerateReport() {
fmt.Println("Will generate report files")
}NoColor (bool): Disable colored output.Succinct (bool): Minimal output, just summary.Verbose (bool): Include GinkgoWriter output for all specs.VeryVerbose (bool): Maximum verbosity, includes skipped/pending specs.FullTrace (bool): Print full stack traces on failure.ShowNodeEvents (bool): Show node enter/exit events in failures.GithubOutput (bool): Format output for GitHub Actions.SilenceSkips (bool): Don't print skipped specs.ForceNewlines (bool): Ensure newline after each spec.JSONReport (string): Path for JSON report file.GoJSONReport (string): Path for Go JSON test format report.JUnitReport (string): Path for JUnit XML report file.TeamcityReport (string): Path for TeamCity report file.Configuration for Go build and test flags.
type GoFlagsConfig struct {
// Code analysis (build-time)
Race bool
Cover bool
CoverMode string
CoverPkg string
Vet string
// Performance profiling (run-time)
BlockProfile string
BlockProfileRate int
CoverProfile string
CPUProfile string
MemProfile string
MemProfileRate int
MutexProfile string
MutexProfileFraction int
Trace string
// Build flags
A bool
ASMFlags string
BuildMode string
BuildVCS bool
Compiler string
GCCGoFlags string
GCFlags string
InstallSuffix string
LDFlags string
LinkShared bool
Mod string
ModFile string
ModCacheRW bool
MSan bool
N bool
PkgDir string
Tags string
TrimPath bool
ToolExec string
Work bool
X bool
O string
}Constructor:
func NewDefaultGoFlagsConfig() GoFlagsConfigExample:
goConfig := types.NewDefaultGoFlagsConfig()
goConfig.Race = true
goConfig.Cover = true
goConfig.CoverProfile = "coverage.out"
goConfig.Tags = "integration"Race (bool): Enable race detector.Cover (bool): Enable coverage analysis.CoverMode (string): Coverage mode: "set", "count", or "atomic".CoverPkg (string): Packages to include in coverage.Vet (string): Vet checks to run.BlockProfile (string): Write blocking profile to file.BlockProfileRate (int): Blocking profile sample rate.CoverProfile (string): Write coverage profile to file.CPUProfile (string): Write CPU profile to file.MemProfile (string): Write memory profile to file.MemProfileRate (int): Memory profile sample rate.MutexProfile (string): Write mutex profile to file.MutexProfileFraction (int): Mutex profile sample rate.Trace (string): Write execution trace to file.A (bool): Force rebuild of packages.ASMFlags (string): Arguments for assembler.BuildMode (string): Build mode (see go help buildmode).BuildVCS (bool): Add version control info.Compiler (string): Compiler to use ("gc" or "gccgo").GCCGoFlags (string): Flags for gccgo compiler.GCFlags (string): Flags for Go compiler.InstallSuffix (string): Suffix for package installation directory.LDFlags (string): Flags for linker.LinkShared (bool): Link against shared libraries.Mod (string): Module download mode ("readonly", "vendor", or "mod").ModFile (string): Alternate go.mod file.ModCacheRW (bool): Leave module cache read-write.MSan (bool): Enable memory sanitizer.N (bool): Print commands without running.PkgDir (string): Install/load packages from directory.Tags (string): Build tags (comma-separated).TrimPath (bool): Remove file system paths from executable.ToolExec (string): Program to invoke toolchain programs.Work (bool): Keep temporary work directory.X (bool): Print commands.O (string): Output binary path.Configuration for the Ginkgo CLI (not typically used in test code).
type CLIConfig struct {
// Suite discovery
Recurse bool
SkipPackage string
RequireSuite bool
NumCompilers int
// Execution
Procs int
Parallel bool
AfterRunHook string
OutputDir string
KeepSeparateCoverprofiles bool
KeepSeparateReports bool
// Run control
KeepGoing bool
UntilItFails bool
Repeat int
RandomizeSuites bool
// Watch mode
Depth int
WatchRegExp string
}Constructor:
func NewDefaultCLIConfig() CLIConfigReturns current suite and reporter configuration.
func GinkgoConfiguration() (SuiteConfig, ReporterConfig)Example:
suiteConfig, reporterConfig := GinkgoConfiguration()
fmt.Printf("Random seed: %d\n", suiteConfig.RandomSeed)
fmt.Printf("Parallel process: %d of %d\n",
suiteConfig.ParallelProcess, suiteConfig.ParallelTotal)
fmt.Printf("Verbose: %v\n", reporterConfig.Verbose)
if suiteConfig.FailFast {
fmt.Println("Running with --fail-fast")
}func GinkgoRandomSeed() int64
func GinkgoParallelProcess() int
func GinkgoLabelFilter() string
func GinkgoSemVerFilter() stringExample:
BeforeEach(func() {
seed := GinkgoRandomSeed()
processNum := GinkgoParallelProcess()
// Use different test data per process
testData := LoadTestData(seed, processNum)
})// In test file
func TestMyPackage(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "My Package Suite")
}
// Run with: ginkgo -p
// Or: ginkgo --procs=4Describe("Feature", Label("integration"), func() {
It("test 1", Label("smoke"), func() {
// Has labels: integration, smoke
})
It("test 2", Label("slow"), func() {
// Has labels: integration, slow
})
})
// Run with: ginkgo --label-filter="integration && !slow"Describe("API tests", func() {
BeforeEach(func() {
// Suite-level timeout from CLI or default (1 hour)
config, _ := GinkgoConfiguration()
fmt.Printf("Suite timeout: %v\n", config.Timeout)
})
It("fast test", func() {
// Uses node timeout
}, NodeTimeout(5*time.Second))
It("slow test", func() {
// Uses spec timeout (includes setup/teardown)
}, SpecTimeout(30*time.Second))
})
// Run with: ginkgo --timeout=10m// Run with: ginkgo --dry-run -v
// Prints test structure without running
Describe("Suite", func() {
It("test 1", func() {
// Won't actually run
})
It("test 2", Label("smoke"), func() {
// Won't actually run
})
})// Run with:
// ginkgo --json-report=results.json --junit-report=results.xml
ReportAfterSuite(func(report Report) {
// Custom report processing
if report.SuiteSucceeded {
generateSuccessReport(report)
} else {
generateFailureReport(report)
}
})// Run with:
// ginkgo --race --cover --coverprofile=coverage.out
It("is thread-safe", func() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer GinkgoRecover()
defer wg.Done()
// Code that will be checked for races
performThreadSafeOperation()
}()
}
wg.Wait()
})It("has progressive timeouts", func(ctx SpecContext) {
By("quick operation")
quickOp(ctx) // Uses spec timeout
By("checking progress", func() {
// This emits progress every 5 seconds
time.Sleep(10 * time.Second)
})
},
SpecTimeout(30*time.Second),
PollProgressAfter(5*time.Second),
PollProgressInterval(2*time.Second),
)var _ = BeforeSuite(func() {
config, _ := GinkgoConfiguration()
if config.ParallelTotal > 1 {
fmt.Printf("Running in parallel with %d processes\n",
config.ParallelTotal)
setupParallelResources()
}
if os.Getenv("CI") == "true" {
// Adjust behavior for CI environment
increasedTimeouts()
}
})The reporter config supports multiple verbosity levels:
type VerbosityLevel uint
const (
VerbosityLevelSuccinct VerbosityLevel = iota
VerbosityLevelNormal
VerbosityLevelVerbose
VerbosityLevelVeryVerbose
)Methods:
func (vl VerbosityLevel) GT(comp VerbosityLevel) bool
func (vl VerbosityLevel) GTE(comp VerbosityLevel) bool
func (vl VerbosityLevel) Is(comp VerbosityLevel) bool
func (vl VerbosityLevel) LTE(comp VerbosityLevel) bool
func (vl VerbosityLevel) LT(comp VerbosityLevel) bool
func (rc ReporterConfig) Verbosity() VerbosityLevelExample:
_, reporterConfig := GinkgoConfiguration()
verbosity := reporterConfig.Verbosity()
if verbosity.GTE(types.VerbosityLevelVerbose) {
// Print extra debug information
fmt.Println("Detailed debugging enabled")
}