testutils

package module
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: May 15, 2025 License: MIT Imports: 9 Imported by: 1

README

TestUtils - Go Testing Utilities Library

A comprehensive testing utilities library for Go that provides colorized output, easy debugging, benchmarking, and random test data generation.

Features

  • Colorized Test Output: Clear visual distinction between success, failure, and debug information
  • Simple Test Framework: Easy-to-use testing function with customizable behavior
  • Benchmark Tool: Measure and compare execution times of multiple code blocks
  • Random Data Generation: Generate random test data for any type
  • Stack Trace Utilities: Access and format stack traces for better debugging
  • Panic Handler: Simplified error handling with panic option

Installation

go get github.com/HashemJaafar7/testutils

Quick Start

package main

import (
    "fmt"
    "github.com/HashemJaafar7/testutils"
)

func main() {
	// Simple test
	actual := 42
	expected := 42
	testutils.Test(false, true, true, 8, "v", actual, expected)

	// Debug output
	value := "debug this"
	testutils.Debug("v", value)

	// Benchmark comparison
	testutils.Benchmark(1000,
		func() { /* First operation */ },
		func() { /* Second operation */ },
	)
}

API Reference

Test Function
func Test[t any](isPanic, print, isEqual bool, line uint16, format string, actual, expected t)

Parameters:

  • isPanic: Exit program if test fails
  • print: Print results regardless of pass/fail
  • isEqual: Expected equality relationship
  • line: Stack trace line number (must be > 8)
  • format: Printf format string for output
  • actual: Value being tested
  • expected: Value to test against

Example:

// Test for equality with output
testutils.Test(false, true, true, 8, "%v", result, expectedResult)

// Test for inequality with panic on failure
testutils.Test(true, false, false, 8, "%v", value1, value2)
Debug Function
func Debug(format string, a any)

Prints formatted debug information with stack trace and variable name.

Example:

complexValue := calculateSomething()
testutils.Debug("+v", complexValue)
Benchmark Function
func Benchmark(loops uint, codesBlocks ...func())

Measures execution time of multiple code blocks.

Example:

testutils.Benchmark(1000,
    func() { method1() },
    func() { method2() },
    func() { method3() },
)
Random Data Generation
func Rand[t any]() t

Generates random values of any type using fuzzing.

Example:

randomInt := testutils.Rand[int]()
randomString := testutils.Rand[string]()
randomStruct := testutils.Rand[MyStruct]()
Stack Trace Utility
func Stack(line uint16) string

Retrieves specific line from stack trace.

Example:

stackLine := testutils.Stack(6)
Panic If Error
func PanicIfErr(err error)

Panics if error is not nil.

Example:

testutils.PanicIfErr(err)

Color Constants

The library provides color constants for output formatting:

const (
    ColorReset   = "\033[0m"
    ColorRed     = "\033[31m" // Failure
    ColorGreen   = "\033[32m" // Success
    ColorYellow  = "\033[33m" // Actual value
    ColorBlue    = "\033[34m" // Expected value
    ColorMagenta = "\033[35m" // Debug
    ColorCyan    = "\033[36m" // Benchmark
)

Best Practices

  1. Test Line Numbers

    • Use appropriate line numbers (> 8) for stack traces
    • Keep line numbers consistent within test suites
  2. Benchmarking

    • Use sufficient loop counts for accurate measurements
    • Keep benchmark functions focused and isolated
    • Compare similar operations in the same benchmark
  3. Debug Output

    • Use descriptive format strings
    • Debug complex structures with +v
    • Keep debug statements organized
  4. Random Testing

    • Use Rand() with appropriate types
    • Validate generated data meets requirements
    • Consider edge cases

Example Use Cases

Complex Testing Scenario
func TestComplexOperation() {
    input := testutils.Rand[MyStruct]()
    result := ComplexOperation(input)

    // Test with output and panic on failure
    testutils.Test(true, true, true, 8, "+v",
        result,
        expectedResult,
    )
}
Performance Comparison
func BenchmarkAlgorithms() {
    data := generateTestData()

    testutils.Benchmark(1000,
        func() { algorithm1(data) },
        func() { algorithm2(data) },
        func() { algorithm3(data) },
    )
}
Debugging Complex Structures
func ProcessData() {
    result := complexCalculation()
    testutils.Debug("+v", result)

    // Continue processing...
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

License

MIT

Documentation

Overview

Example
package main

import (
	"time"

	"github.com/HashemJaafar7/testutils"
)

func main() {
	// Example of error handling
	testutils.PanicIfErr(nil)

	// Examples of random value generation
	randomInt := testutils.Rand[int]()
	testutils.Debug("v", randomInt)

	randomString := testutils.Rand[string]()
	testutils.Debug("v", randomString)

	// Example of stack trace
	stackTrace := testutils.Stack(8)
	testutils.Debug("v", stackTrace)

	// Examples of Test function
	testutils.Test(true, true, true, 8, "v", 42, 42)            // Equal values
	testutils.Test(true, true, false, 8, "v", "hello", "world") // Different values

	// Example with slices
	slice1 := []int{1, 2, 3}
	slice2 := []int{1, 2, 3}
	testutils.Test(true, true, true, 8, "v", slice1, slice2)

	// Example of struct comparison
	type Person struct {
		Name string
		Age  int
	}
	p1 := Person{"John", 30}
	p2 := Person{"John", 30}
	testutils.Test(true, true, true, 8, "v", p1, p2)

	// Example of Benchmark
	testutils.Benchmark(5,
		func() {
			time.Sleep(10 * time.Millisecond)
			testutils.Debug("v", "Fast operation")
		},
		func() {
			time.Sleep(50 * time.Millisecond)
			testutils.Debug("v", "Medium operation")
		},
		func() {
			time.Sleep(100 * time.Millisecond)
			testutils.Debug("v", "Slow operation")
		},
	)
}

Index

Examples

Constants

View Source
const (
	ColorReset = "\033[0m"

	ColorBlack   = "\033[30m"
	ColorRed     = "\033[31m" //for fail
	ColorGreen   = "\033[32m" //for success
	ColorYellow  = "\033[33m" //for actual
	ColorBlue    = "\033[34m" //for expected
	ColorMagenta = "\033[35m" //for Debug
	ColorCyan    = "\033[36m" //for Benchmark
	ColorWhite   = "\033[37m"
)

Variables

This section is empty.

Functions

func Benchmark

func Benchmark(loops uint, codesBlocks ...func())

Benchmark measures the execution time of one or more code blocks over a specified number of loops and prints the results in ascending order of execution time.

Parameters:

  • loops: The number of times each code block should be executed.
  • codesBlocks: A variadic parameter representing one or more functions (code blocks) to benchmark.

Behavior:

  • Each code block is executed the specified number of times.
  • The total execution time for each code block is measured and stored.
  • The results are sorted by execution time in ascending order.
  • The function prints the stack trace, followed by the execution time for each code block and the average time per loop.

Example:

Benchmark(1000, func() {
    // Code block 1
}, func() {
    // Code block 2
})

Output:

The function outputs the benchmark results to the console, including:
  - The block index.
  - The total execution time for the block.
  - The average execution time per loop.

Notes:

  • The function uses the `time` package to measure execution time.
  • The `sort` package is used to sort the results by execution time.

func Debug

func Debug(format string, a any)

Debug prints debugging information to the console, including the call stack, the name of the variable being debugged, and its value formatted according to the specified format string.

Parameters:

  • format: A format string that specifies how the value should be displayed.
  • a: The value to be debugged.

The function extracts the call stack, highlights it in magenta, and retrieves the line of code where the Debug function was called. It then parses the line to extract the variable name and prints the variable name and its value in yellow, followed by a separator line for clarity.

func PanicIfErr

func PanicIfErr(err error)

PanicIfErr checks if the provided error is not nil, and if so, it panics with the error. This function is useful for quickly handling unexpected errors in situations where error recovery is not required or desired.

Parameters:

  • err: The error to check. If it is nil, the function does nothing.

func Rand

func Rand[t any]() t

Rand generates a random value of any type `t` using fuzzing. It initializes a variable of type `t`, applies fuzzing to populate it with random data, and then returns the result. A small delay is introduced to ensure randomness.

Type Parameters:

  • t: The type of the value to be generated.

Returns:

A randomly generated value of type `t`.

func Stack

func Stack(line uint16) string

func Test

func Test[t any](isPanic, print, isEqual bool, line uint16, format string, actual, expected t)

Test is a generic testing function that compares two values and provides formatted output.

Parameters:

  • t: Any type parameter for the values being compared
  • isPanic: If true, exits program when test fails
  • print: If true, prints test results regardless of pass/fail
  • isEqual: Expected equality relationship between actual and expected
  • line: Line number for stack trace (must be > 8)
  • format: Printf format string for value output
  • actual: The value being tested
  • expected: The value to test against

The function:

  • Validates line number is > 8
  • Compares actual vs expected using reflect.DeepEqual
  • Prints colored stack traces and formatted values
  • Can exit program on test failure if isPanic is true
  • Supports testing for both equality and inequality based on isEqual flag

Example usage:

Test(true, false, true, 10, "%v", actual, expected) // Test equality with panic on failure
Test(false, true, false, 8, "%d", val1, val2) // Test inequality with output

Types

This section is empty.

Jump to

Keyboard shortcuts

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