random

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

random

random is a Go library designed to facilitate the generation of random data for testing purposes. It uses reflection to recursively populate complex data structures such as structs, maps, slices, and arrays with random values.

Installation

go get github.com/zauberhaus/random

Usage

Generating Values

The primary entry point is RandomFor[T], which generates a random value of type T.

package main

import (
	"fmt"
	"github.com/zauberhaus/random"
)

func main() {
	// Generate a random integer
	i, _ := random.RandomFor[int]()
	fmt.Println("Random Int:", i)

	// Generate a random string
	s, _ := random.RandomFor[string]()
	fmt.Println("Random String:", s)
}
Working with Structs

random automatically populates exported fields of structs, including nested structures.

type User struct {
	ID       int
	Name     string
	IsActive bool
	Tags     map[string]int
}

func main() {
	user, err := random.RandomFor[User]()
	if err != nil {
		panic(err)
	}
	fmt.Printf("Random User: %+v\n", user)
}
Custom Generators

For types that require specific generation logic (like time.Time or types with validation rules), you can provide custom RandomGenerator implementations.

The library includes built-in generators for common types:

  • random.RandomTime: Generates time.Time
  • random.RandomDuration: Generates time.Duration
  • random.RandomRegexp: Generates *regexp.Regexp

To use them (or your own), pass them to RandomFor:

import (
	"time"
	"github.com/zauberhaus/random"
)

func main() {
	// Generate a random time using the specific generator
	t, _ := random.RandomFor[time.Time](random.RandomTime)
}
Helper Functions

The library provides helpers for selecting random items from collections.

  • RandomOfSlice(slice): Returns a random element from the provided slice.
  • RandomOfMap(map): Returns a random key from the provided map.
String Conversion

The String function provides a robust way to convert arbitrary values to strings. It handles various interfaces and complex types automatically.

Supported conversions:

  • encoding.TextMarshaler
  • yaml.Marshaler
  • fmt.Stringer
  • Slices and Arrays (comma-separated values)
  • Maps (key=value pairs, sorted by key)
  • Structs (serialized to JSON)
  • Basic types
Custom String Conversion

You can customize string conversion for specific types using StringHook.

type MyType struct {
	Value string
}

hook := random.NewStringHookFor[MyType](func(v any) (string, error) {
	return "custom:" + v.(MyType).Value, nil
})

val := MyType{Value: "test"}
str, err := random.String(val, hook)
// str: "custom:test"

Documentation

Index

Constants

This section is empty.

Variables

View Source
var RandomDuration = NewStrictRandomGenerator[time.Duration](func() (any, error) {
	duration := 24 * time.Hour
	randomNanos := random.Int64N(duration.Nanoseconds())
	value := time.Duration(randomNanos) * time.Nanosecond
	return value, nil
})
View Source
var RandomRegexp = NewRandomGenerator[*regexp.Regexp](func() (any, error) {
	txt := autoname.Generate("-")
	return regexp.Compile(txt)
})
View Source
var RandomTime = NewRandomGenerator[time.Time](func() (any, error) {
	start := time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)
	end := time.Date(2025, time.December, 31, 23, 59, 59, 0, time.UTC)

	duration := end.Sub(start)
	randomNanos := random.Int64N(duration.Nanoseconds())
	randomDuration := time.Duration(randomNanos) * time.Nanosecond

	value := start.Add(randomDuration)
	return value, nil

})

Functions

func ConvertTo

func ConvertTo(value any, t reflect.Type) (any, error)

func NewConcurrentSource added in v1.0.1

func NewConcurrentSource(source rand.Source) rand.Source

func Random

func Random(t reflect.Type, generators ...RandomGenerator) (any, error)

func RandomFor

func RandomFor[T any](generators ...RandomGenerator) (T, error)

func RandomOfMap

func RandomOfMap[Map ~map[K]V, K comparable, V any](m Map) K

func RandomOfSlice

func RandomOfSlice[Slice ~[]V, V any](s Slice) V

Types

type ConcurrentSource added in v1.0.1

type ConcurrentSource struct {
	rand.Source
	// contains filtered or unexported fields
}

func (*ConcurrentSource) Uint64 added in v1.0.1

func (c *ConcurrentSource) Uint64() uint64

type RandomGenerator

type RandomGenerator interface {
	Can(t reflect.Type) bool
	Random() (any, error)
}

func NewRandomGenerator

func NewRandomGenerator[T any](random func() (any, error)) RandomGenerator

func NewStrictRandomGenerator

func NewStrictRandomGenerator[T any](random func() (any, error)) RandomGenerator

Directories

Path Synopsis
examples
Basic command
CustomGenerator command
pkg

Jump to

Keyboard shortcuts

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