### Integrate randfill with go-fuzz for Testing Source: https://github.com/kubernetes-sigs/randfill/blob/main/README.md Provides an example of how to use randfill within a go-fuzz test to convert a byte slice into a Go type for fuzzing. This simplifies the process of generating varied inputs for testing functions. ```go // +build gofuzz package mypackage import "sigs.k8s.io/randfill" func Fuzz(data []byte) int { var i int randfill.NewFromGoFuzz(data).Fill(&i) MyFunc(i) return 0 } ``` -------------------------------- ### Skip Fields Matching Patterns in Go with randfill Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Illustrates how to skip fields that match specific regular expression patterns using `SkipFieldsWithPattern` in `randfill`. This is particularly useful for ignoring fields like protobuf's `XXX_` prefixed fields, ensuring they are not accidentally filled. It helps in controlling which fields are randomized. ```go package main import ( "fmt" "regexp" "sigs.k8s.io/randfill" ) func main() { type ProtoMessage struct { Name string Value int XXX_NoUnkeyedLiteral struct{} XXX_unrecognized []byte XXX_sizecache int32 RegularField string } // Skip all fields starting with "XXX_" f := randfill.New(). NilChance(0). SkipFieldsWithPattern(regexp.MustCompile(`^XXX_`)) msg := ProtoMessage{} f.Fill(&msg) fmt.Printf("Name: %s (filled)\n", msg.Name) fmt.Printf("Value: %d (filled)\n", msg.Value) fmt.Printf("RegularField: %s (filled)\n", msg.RegularField) fmt.Printf("XXX_sizecache: %d (not filled, should be 0)\n", msg.XXX_sizecache) } ``` -------------------------------- ### Basic Object Filling with randfill Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Demonstrates how to fill a Go struct with random values using the default configuration of the randfill library. It initializes a `Filler` and uses the `Fill` method on a struct instance. ```go package main import ( "fmt" "sigs.k8s.io/randfill" ) func main() { type MyType struct { A string B int C float64 D bool } f := randfill.New() obj := MyType{} f.Fill(&obj) fmt.Printf("Filled object: %+v\n", obj) // Output: Filled object: {A:蓋ᐸ氀 B:5577006791947779410 C:0.6046602879796196 D:false} } ``` -------------------------------- ### Initialize and Fill a Single Variable with randfill Source: https://github.com/kubernetes-sigs/randfill/blob/main/README.md Demonstrates the basic usage of randfill to generate a random value for a single Go variable. It requires importing the randfill library. ```go import "sigs.k8s.io/randfill" f := randfill.New() var myInt int f.Fill(&myInt) // myInt gets a random value. ``` -------------------------------- ### Controlling Collection Sizes (Maps, Slices, Arrays) Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Demonstrates how to specify the minimum and maximum number of elements for maps, slices, and arrays using the `NumElements` method. This allows control over the size of collections generated by the filler. ```go package main import ( "fmt" "sigs.k8s.io/randfill" ) func main() { type Collections struct { Items map[string]int Tags []string } // NumElements(min, max) controls collection sizes f := randfill.New().NilChance(0).NumElements(3, 5) obj := Collections{} f.Fill(&obj) fmt.Printf("Map size: %d (between 3 and 5)\n", len(obj.Items)) fmt.Printf("Slice size: %d (between 3 and 5)\n", len(obj.Tags)) // Exact size: NumElements(1, 1) fExact := randfill.New().NilChance(0).NumElements(1, 1) obj2 := Collections{} fExact.Fill(&obj2) fmt.Printf("Exact map size: %d, exact slice size: %d\n", len(obj2.Items), len(obj2.Tags)) } ``` -------------------------------- ### Deterministic Random Filling with Specific Seed Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Shows how to achieve reproducible random data generation by seeding the random number generator. This is useful for consistent test results. The `RandSource` method is used to provide a seeded `rand.Source`. ```go package main import ( "fmt" "math/rand" "sigs.k8s.io/randfill" ) func main() { type User struct { Name string Age int Score float64 } // Using RandSource for deterministic output f := randfill.New().RandSource(rand.NewSource(42)) user1 := User{} f.Fill(&user1) fmt.Printf("First fill: %+v\n", user1) // Reset with same seed for identical results f.RandSource(rand.NewSource(42)) user2 := User{} f.Fill(&user2) fmt.Printf("Second fill: %+v\n", user2) fmt.Printf("Are they equal? %v\n", user1 == user2) // Output: Are they equal? true } ``` -------------------------------- ### Recursive Filling with Continue in Go Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Demonstrates how to use the Continue interface within custom fill functions for recursive object filling. This allows custom logic to be applied while still leveraging randfill's abilities to fill nested or related structures according to the same rules. ```go package main import ( "fmt" "sigs.k8s.io/randfill" ) func main() { type Author struct { Name string Age int } type Book struct { Title string Author Author Pages int } f := randfill.New().Funcs( func(book *Book, c randfill.Continue) { // Use Continue methods for random values book.Title = c.String(50) // Random string up to 50 chars book.Pages = int(c.Uint64() % 1000) // Use Continue.Fill for recursive filling c.Fill(&book.Author) // Continue embeds *rand.Rand for direct access if c.Bool() { book.Pages += 100 } }, ) book := Book{} f.Fill(&book) fmt.Printf("Book: %s by %s, %d pages\n", book.Title, book.Author.Name, book.Pages) } ``` -------------------------------- ### Controlling Nil Probability for Pointers, Maps, and Slices Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Illustrates how to control the likelihood of pointers, maps, and slices being assigned `nil` values. The `NilChance` method takes a float64 between 0.0 and 1.0 to set the probability. 0 means no nils, 1 means all nils. ```go package main import ( "fmt" "sigs.k8s.io/randfill" ) func main() { type Container struct { Ptr1 *string Ptr2 *string Ptr3 *string Map map[string]int Slice []int } // NilChance(0) means no nils fNoNils := randfill.New().NilChance(0) obj1 := Container{} fNoNils.Fill(&obj1) fmt.Printf("No nils - Ptr1 is nil: %v, Map is nil: %v, Slice is nil: %v\n", obj1.Ptr1 == nil, obj1.Map == nil, obj1.Slice == nil) // NilChance(1) means all nils fAllNils := randfill.New().NilChance(1) obj2 := Container{} fAllNils.Fill(&obj2) fmt.Printf("All nils - Ptr1 is nil: %v, Map is nil: %v, Slice is nil: %v\n", obj2.Ptr1 == nil, obj2.Map == nil, obj2.Slice == nil) // NilChance(0.5) means 50% probability fHalfNils := randfill.New().NilChance(0.5) obj3 := Container{} fHalfNils.Fill(&obj3) fmt.Printf("Half nils - Ptr1 is nil: %v\n", obj3.Ptr1 == nil) } ``` -------------------------------- ### Generate Strings from Specific Unicode Ranges in Go Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Shows how to generate random strings within specified Unicode ranges using `randfill`. This is useful for creating constrained random text, such as usernames or passwords, by defining single or multiple Unicode ranges. The `CustomStringFillFunc` method is used to apply these ranges. ```go package main import ( "fmt" "sigs.k8s.io/randfill" ) func main() { type Credentials struct { Username string Password string } // Single range: lowercase letters only lowercaseRange := randfill.UnicodeRange{First: 'a', Last: 'z'} // Multiple ranges: alphanumeric alphanumericRanges := randfill.UnicodeRanges{ {First: 'a', Last: 'z'}, {First: 'A', Last: 'Z'}, {First: '0', Last: '9'}, } f := randfill.New().Funcs( alphanumericRanges.CustomStringFillFunc(12), // max length 12 ) creds := Credentials{} f.Fill(&creds) fmt.Printf("Username: %s\n", creds.Username) fmt.Printf("Password: %s\n", creds.Password) // Both fields contain only alphanumeric characters } ``` -------------------------------- ### Deterministic Fuzzing with ByteSource in Go Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Explains how to use randfill's ByteSource for deterministic fuzzing. By providing a fixed byte slice to ByteSource, randfill can generate reproducible random data, which is useful for debugging test failures. ```go package main import ( "fmt" "sigs.k8s.io/randfill" "sigs.k8s.io/randfill/bytesource" ) func main() { type TestCase struct { Input string Count int Active bool } // Deterministic byte source data := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08} bs := bytesource.New(data) f := randfill.New().RandSource(bs) test1 := TestCase{} f.Fill(&test1) fmt.Printf("Test case: %+v\n", test1) // Same bytes produce same output bs2 := bytesource.New(data) f2 := randfill.New().RandSource(bs2) test2 := TestCase{} f2.Fill(&test2) fmt.Printf("Reproducible: %v\n", test1 == test2) // Output: Reproducible: true } ``` -------------------------------- ### Fill a Map with Specific Constraints using randfill Source: https://github.com/kubernetes-sigs/randfill/blob/main/README.md Shows how to populate a Go map with random values using randfill, with specific constraints on the number of elements and nil chance. The `NilChance` and `NumElements` methods are used for customization. ```go import "sigs.k8s.io/randfill" f := randfill.New().NilChance(0).NumElements(1, 1) var myMap map[ComplexKeyType]string f.Fill(&myMap) // myMap will have exactly one element. ``` -------------------------------- ### Implement Self-Filling Types in Go using Interfaces Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Explains how to implement custom randomization logic within types using the `SimpleSelfFiller` and `NativeSelfFiller` interfaces in `randfill`. `SimpleSelfFiller` is for basic types, while `NativeSelfFiller` allows for recursive filling of nested structures. This provides a way to embed randomization directly into type definitions. ```go package main import ( "fmt" "math/rand" "sigs.k8s.io/randfill" ) // SimpleSelfFiller: simple types without recursion type Temperature float64 func (t *Temperature) RandFill(r *rand.Rand) { // Generate realistic temperature between -50 and 50 celsius *t = Temperature(r.Float64()*100 - 50) } // NativeSelfFiller: complex types that need to fill child objects type Coordinate struct { Latitude float64 Longitude float64 } func (c *Coordinate) RandFill(cont randfill.Continue) { // Use Continue for access to randomness and recursive filling c.Latitude = cont.Float64()*180 - 90 c.Longitude = cont.Float64()*360 - 180 } func main() { f := randfill.New() var temp Temperature f.Fill(&temp) fmt.Printf("Temperature: %.2f°C\n", temp) var coord Coordinate f.Fill(&coord) fmt.Printf("Coordinate: %.4f, %.4f\n", coord.Latitude, coord.Longitude) } ``` -------------------------------- ### Filling Complex Nested Structures in Go Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Illustrates randfill's capability to handle complex and deeply nested data structures, including maps of structs, slices of pointers, and nested compositions. Configuration options like NilChance, NumElements, and MaxDepth control the generation process. ```go package main import ( "encoding/json" "fmt" "sigs.k8s.io/randfill" ) func main() { type Address struct { Street string City string ZipCode string } type Person struct { Name string Addresses map[string]Address Friends []*Person Metadata *map[string]interface{} } f := randfill.New(). NilChance(0.3). NumElements(1, 3). MaxDepth(10) person := Person{} f.Fill(&person) // Serialize to JSON to see structure jsonData, _ := json.MarshalIndent(person, "", " ") fmt.Printf("Complex structure:\n%s\n", string(jsonData)) } ``` -------------------------------- ### Register Custom Fill Functions for Types in Go Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Demonstrates how to register custom functions to control how specific types are filled by randfill. This allows for fine-grained control over the randomization process for custom structs and enums. It leverages the `Funcs` method to provide type-specific filling logic. ```go package main import ( "fmt" "sigs.k8s.io/randfill" ) func main() { type MyEnum string const ( TypeA MyEnum = "TYPE_A" TypeB MyEnum = "TYPE_B" ) type MyInfo struct { Type MyEnum AData *string BData *string } counter := 0 f := randfill.New().NilChance(0).Funcs( // Custom function for int types - must take (*T, Continue) func(i *int, c randfill.Continue) { *i = counter counter++ }, // Custom function for MyInfo ensures consistent state func(info *MyInfo, c randfill.Continue) { switch c.Intn(2) { case 0: info.Type = TypeA c.Fill(&info.AData) case 1: info.Type = TypeB c.Fill(&info.BData) } }, ) obj := MyInfo{} f.Fill(&obj) fmt.Printf("Type: %s, AData: %v, BData: %v\n", obj.Type, obj.AData, obj.BData) // Either AData or BData will be set based on Type } ``` -------------------------------- ### Custom Randomization Logic with randfill Funcs Source: https://github.com/kubernetes-sigs/randfill/blob/main/README.md Demonstrates advanced customization of randfill's behavior by providing custom functions. This allows for complex conditional filling of struct fields, ensuring that related fields are populated consistently. ```go import "sigs.k8s.io/randfill" type MyEnum string const ( A MyEnum = "A" B MyEnum = "B" ) type MyInfo struct { Type MyEnum AInfo *string BInfo *string } f := randfill.New().NilChance(0).Funcs( func(e *MyInfo, c randfill.Continue) { switch c.Intn(2) { case 0: e.Type = A c.Fill(&e.AInfo) case 1: e.Type = B c.Fill(&e.BInfo) } }, ) var myObject MyInfo f.Fill(&myObject) // Type will correspond to whether A or B info is set. ``` -------------------------------- ### Fill Unexported Fields in Go Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Demonstrates how to fill unexported (private) fields of a struct using the randfill library. By default, unexported fields are ignored, but enabling AllowUnexportedFields(true) will fill them. ```go package main import ( "fmt" "sigs.k8s.io/randfill" ) func main() { type InternalState struct { PublicField string privateField string counter int } // By default, unexported fields are not filled f1 := randfill.New() obj1 := InternalState{} f1.Fill(&obj1) fmt.Printf("Default: PublicField=%q, privateField=%q\n", obj1.PublicField, obj1.privateField) // AllowUnexportedFields(true) enables filling private fields f2 := randfill.New().AllowUnexportedFields(true) obj2 := InternalState{} f2.Fill(&obj2) fmt.Printf("With unexported: PublicField=%q, privateField=%q\n", obj2.PublicField, obj2.privateField) } ``` -------------------------------- ### Control Maximum Recursion Depth in Go with randfill Source: https://context7.com/kubernetes-sigs/randfill/llms.txt Demonstrates how to prevent infinite recursion in cyclic or deeply nested structures using `MaxDepth` in `randfill`. This is crucial for avoiding stack overflows when dealing with complex data structures like trees. The `MaxDepth` option sets a limit on how many levels deep `randfill` will recurse. ```go package main import ( "fmt" "sigs.k8s.io/randfill" ) func main() { type TreeNode struct { Value int Left *TreeNode Right *TreeNode } // MaxDepth limits recursion depth f := randfill.New().NilChance(0).MaxDepth(5) root := TreeNode{} f.Fill(&root) // Count depth depth := 0 current := &root for current.Left != nil { depth++ current = current.Left } fmt.Printf("Tree depth: %d (limited by MaxDepth)\n", depth) // Depth will be limited to prevent stack overflow } ``` -------------------------------- ### Customize Nil Pointer Chance with randfill Source: https://github.com/kubernetes-sigs/randfill/blob/main/README.md Illustrates how to control the probability of nil pointers being generated when filling a struct with pointers using randfill. The `NilChance` method takes a float between 0 and 1. ```go import "sigs.k8s.io/randfill" f := randfill.New().NilChance(.5) var fancyStruct struct { A, B, C, D *string } f.Fill(&fancyStruct) // About half the pointers should be set. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.