assert

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2025 License: MIT Imports: 11 Imported by: 0

README

Assert Go

A lightweight assertion library for Go, designed for systems and real-time programming with structured logging and flush controls. Features safe-by-default behavior with optional instance creation using the Function Options pattern.

Go Reference Go Report Card

Installation

go get github.com/ZanzyTHEbar/assert-lib

Documentation

Quick Start - No Instance Required!

package main

import (
    "context"
    "github.com/ZanzyTHEbar/assert-lib"
)

func main() {
    ctx := context.TODO()

    // Safe by default - won't crash your program
    assert.Assert(ctx, 1 == 2, "This will log an error but continue")
    assert.NotEmpty(ctx, "hello", "String should not be empty")
    assert.Equal(ctx, 42, 42, "Numbers should match")

    println("Program continues safely!")
}

Advanced Usage with Options

// Custom behavior using Function Options pattern
assert.Assert(ctx, false, "JSON formatted error",
    assert.WithFormatter(&assert.JSONFormatter{}))

// Exit on failure (opt-in behavior)
assert.Assert(ctx, false, "This will exit",
    assert.WithCrashOnFailure())

// Silent mode for performance-critical sections
assert.Assert(ctx, condition, "Silent check",
    assert.WithSilentMode())

// Debug mode with stack traces (great for development)
assert.Assert(ctx, false, "Debug assertion with stack trace",
    assert.WithDebugMode())

// Verbose mode with stack traces and argument details
assert.Assert(ctx, false, "Verbose assertion with full details",
    assert.WithVerboseMode())

// Testing defaults (safe + text format + debug info)
assert.Assert(ctx, false, "Test assertion",
    assert.WithTestingDefaults())

// Production defaults (safe + JSON format + clean output)
assert.Assert(ctx, false, "Production assertion",
    assert.WithProductionDefaults())

// Production defaults (safe + JSON format)
assert.Assert(ctx, false, "Production assertion",
    assert.WithProductionDefaults())

Traditional Instance-Based Usage

handler := assert.NewAssertHandler()
handler.SetExitFunc(func(code int) {
    // Custom exit behavior
})
handler.Assert(context.TODO(), false, "Traditional usage")

Features

  • 🛡️ Safe by Default: Assertions log errors but don't crash your program by default
  • ⚡ Zero Instance Required: Use package-level functions without creating handlers
  • 🔧 Function Options Pattern: Customize behavior on a per-assertion basis
  • 📊 Multiple Formatters: Text, JSON, YAML output formats
  • 🎯 Rich Assertion Types: Assert, Equal, NotEmpty, Contains, True/False, Nil checks
  • 🔄 Deferred Assertions: Batch process multiple assertions
  • 📝 Structured Logging: Context-based logging with stack traces
  • 🧪 Testing-Friendly: Built-in testing and production defaults

Available Assertions

Basic Assertions
  • Assert(ctx, condition, msg, opts...) - Basic truth assertion
  • True(ctx, value, msg, opts...) - Assert value is true
  • False(ctx, value, msg, opts...) - Assert value is false
Equality & Comparison
  • Equal(ctx, expected, actual, msg, opts...) - Assert values are equal
  • NotEqual(ctx, expected, actual, msg, opts...) - Assert values are different
Nil Checks
  • Nil(ctx, item, msg, opts...) - Assert item is nil
  • NotNil(ctx, item, msg, opts...) - Assert item is not nil
String Assertions
  • NotEmpty(ctx, str, msg, opts...) - Assert string is not empty
  • Contains(ctx, str, substr, msg, opts...) - Assert string contains substring
  • NotContains(ctx, str, substr, msg, opts...) - Assert string doesn't contain substring
Error Handling
  • NoError(ctx, err, msg, opts...) - Assert no error occurred
  • Never(ctx, msg, opts...) - Always fails (for unreachable code)

Available Options

Output Control
  • WithFormatter(&assert.JSONFormatter{}) - JSON output
  • WithFormatter(&assert.YAMLFormatter{}) - YAML output
  • WithWriter(writer) - Custom output writer
  • WithSilentMode() - No output
Debug & Verbosity Control
  • WithDebugMode() - Include stack traces in output (great for development)
  • WithVerboseMode() - Include stack traces + argument details
  • WithQuietMode() - Minimal output (default behavior)
Behavior Control
  • WithCrashOnFailure() - Exit program on assertion failure
  • WithPanicOnFailure() - Panic on assertion failure
  • WithExitFunc(func(int)) - Custom exit function
Convenience Presets
  • WithTestingDefaults() - Safe behavior + text format + debug info
  • WithProductionDefaults() - Safe behavior + JSON format + clean output

Examples

Run the examples to see different usage patterns:

go run examples/ergonomic_api.go      # Optimized ergonomic usage
go run examples/debug_modes.go       # Debug/verbose mode examples
go run examples/basic_assertion.go    # Traditional instance-based usage
go run examples/deferred_assertions.go # Batch processing
go run examples/custom_exit.go        # Custom exit behavior
go run examples/formater.go          # Different output formats

Output Modes Comparison

Default Mode (Clean)
ASSERT
   msg=Test assertion
   area=Assert
Debug Mode (With Stack Trace)
ASSERT
   msg=Test assertion
   area=Assert
goroutine 1 [running]:
runtime/debug.Stack()...
Verbose Mode (With Stack + Args)
ARGS: [key1 value1 key2 value2]
ASSERT
   msg=Test assertion
   area=Assert
goroutine 1 [running]:
runtime/debug.Stack()...
Production Mode (Clean JSON)
{
    "assertData": {
        "area": "Assert",
        "msg": "Test assertion"
    }
}

Philosophy

This library follows a safe-by-default philosophy:

  • Package-level functions won't crash your program by default
  • Stack traces are disabled by default for clean production logs
  • You opt-in to debug information and crashing behavior when needed
  • You opt-in to crashing behavior when needed
  • Rich context and structured logging help with debugging
  • Function Options pattern provides flexibility without complexity

Perfect for production systems where you want assertions for debugging but can't afford unexpected crashes.

Works very well with my errbuilder-go library.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Assert added in v1.3.0

func Assert(ctx context.Context, truth bool, msg string, opts ...Option)

Assert checks if the condition is true, failing if false

func AssertWithTimeout added in v1.3.0

func AssertWithTimeout(ctx context.Context, timeout time.Duration, truth bool, msg string, opts ...Option)

AssertWithTimeout checks if the condition is true with a timeout, failing if false

func Contains added in v1.3.0

func Contains(ctx context.Context, str, substr string, msg string, opts ...Option)

Contains checks if a string contains a substring, failing if it doesn't

func Equal added in v1.3.0

func Equal(ctx context.Context, expected, actual any, msg string, opts ...Option)

Equal checks if two values are equal, failing if they're not

func False added in v1.3.0

func False(ctx context.Context, value bool, msg string, opts ...Option)

False checks if a value is false, failing if true

func Never added in v1.3.0

func Never(ctx context.Context, msg string, opts ...Option)

Never always fails - use for code paths that should never be reached

func Nil added in v1.3.0

func Nil(ctx context.Context, item any, msg string, opts ...Option)

Nil checks if the item is nil, failing if not nil

func NoError added in v1.3.0

func NoError(ctx context.Context, err error, msg string, opts ...Option)

NoError checks if the error is nil, failing if not nil

func NotContains added in v1.3.0

func NotContains(ctx context.Context, str, substr string, msg string, opts ...Option)

NotContains checks if a string does not contain a substring, failing if it does

func NotEmpty added in v1.3.0

func NotEmpty(ctx context.Context, str string, msg string, opts ...Option)

NotEmpty checks if a string is not empty, failing if empty

func NotEqual added in v1.3.0

func NotEqual(ctx context.Context, expected, actual any, msg string, opts ...Option)

NotEqual checks if two values are not equal, failing if they are equal

func NotNil added in v1.3.0

func NotNil(ctx context.Context, item any, msg string, opts ...Option)

NotNil checks if the item is not nil, failing if nil

func ProcessDeferredAssertions added in v1.3.0

func ProcessDeferredAssertions(ctx context.Context, opts ...Option)

ProcessDeferredAssertions processes any deferred assertions on the default handler

func True added in v1.3.0

func True(ctx context.Context, value bool, msg string, opts ...Option)

True checks if a value is true, failing if false

Types

type AssertConfig added in v1.3.0

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

AssertConfig holds temporary configuration for assert operations

type AssertData

type AssertData interface {
	Dump() string
}

Define interfaces for logging/asserting

type AssertFlush

type AssertFlush interface {
	Flush()
}

type AssertHandler

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

Define the AssertHandler to encapsulate state

func NewAssertHandler

func NewAssertHandler() *AssertHandler

Add a constructor for the handler

func (*AssertHandler) AddAssertData

func (a *AssertHandler) AddAssertData(key string, value AssertData)

func (*AssertHandler) AddAssertFlush

func (a *AssertHandler) AddAssertFlush(flusher AssertFlush)

func (*AssertHandler) Assert

func (a *AssertHandler) Assert(ctx context.Context, truth bool, msg string, data ...any)

func (*AssertHandler) AssertWithTimeout

func (a *AssertHandler) AssertWithTimeout(ctx context.Context, timeout time.Duration, truth bool, msg string, data ...any)

func (*AssertHandler) Never

func (a *AssertHandler) Never(ctx context.Context, msg string, data ...any)

func (*AssertHandler) Nil

func (a *AssertHandler) Nil(ctx context.Context, item any, msg string, data ...any)

func (*AssertHandler) NoError

func (a *AssertHandler) NoError(ctx context.Context, err error, msg string, data ...any)

func (*AssertHandler) NotNil

func (a *AssertHandler) NotNil(ctx context.Context, item any, msg string, data ...any)

func (*AssertHandler) ProcessDeferredAssertions

func (a *AssertHandler) ProcessDeferredAssertions(ctx context.Context)

Process all deferred assertions at once, logging or exiting if needed

func (*AssertHandler) RemoveAssertData

func (a *AssertHandler) RemoveAssertData(key string)

func (*AssertHandler) SetDebugMode added in v1.3.1

func (a *AssertHandler) SetDebugMode(debugMode bool)

func (*AssertHandler) SetDeferAssertions

func (a *AssertHandler) SetDeferAssertions(deferMode bool)

SetDeferAssertions allows toggling deferred assertion mode

func (*AssertHandler) SetExitFunc

func (a *AssertHandler) SetExitFunc(exitFunc func(int))

func (*AssertHandler) SetFormatter

func (a *AssertHandler) SetFormatter(formatter Formatter)

func (*AssertHandler) SetVerboseMode added in v1.3.1

func (a *AssertHandler) SetVerboseMode(verboseMode bool)

func (*AssertHandler) ToWriter

func (a *AssertHandler) ToWriter(w io.Writer)

type Formatter

type Formatter interface {
	Format(assertData map[string]interface{}, stack string) string
}

Formatter interface for structured output

type JSONFormatter

type JSONFormatter struct{}

JSONFormatter for JSON output

func (*JSONFormatter) Format

func (f *JSONFormatter) Format(assertData map[string]interface{}, stack string) string

type Option added in v1.3.0

type Option func(*AssertConfig)

Option defines a function that can modify assert configuration

func WithCrashOnFailure added in v1.3.0

func WithCrashOnFailure() Option

Additional convenience options for common use cases

func WithDebugMode added in v1.3.1

func WithDebugMode() Option

func WithDeferMode added in v1.3.0

func WithDeferMode(deferMode bool) Option

func WithExitFunc added in v1.3.0

func WithExitFunc(f func(int)) Option

func WithFormatter added in v1.3.0

func WithFormatter(f Formatter) Option

Option functions for configuring assert behavior

func WithLogLevel added in v1.3.0

func WithLogLevel(level string) Option

func WithPanicOnFailure added in v1.3.0

func WithPanicOnFailure() Option

func WithProductionDefaults added in v1.3.0

func WithProductionDefaults() Option

func WithQuietMode added in v1.3.1

func WithQuietMode() Option

func WithSilentMode added in v1.3.0

func WithSilentMode() Option

func WithTestingDefaults added in v1.3.0

func WithTestingDefaults() Option

Combine multiple options into one

func WithVerboseMode added in v1.3.1

func WithVerboseMode() Option

func WithWriter added in v1.3.0

func WithWriter(w io.Writer) Option

type TextFormatter

type TextFormatter struct{}

TextFormatter is the default plain text output format

func (*TextFormatter) Format

func (f *TextFormatter) Format(assertData map[string]interface{}, stack string) string

type YAMLFormatter

type YAMLFormatter struct{}

YAMLFormatter for YAML output

func (*YAMLFormatter) Format

func (f *YAMLFormatter) Format(assertData map[string]interface{}, stack string) string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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