Documentation
¶
Overview ¶
The clone package provides the ability to verify that the functions for cloning structures with complex fields work correctly.
The main goal ¶
Structures containing fields with types such as slice, mapping and pointer must be cloned with an explicit copying of the data to which they point. For example:
type myStruct struct {items []string}
func (ms *myStruct) Clone() *myStruct {
rv := *ms
// Allocating separate memory for items and copy original items
rv.items = make([]string, len(ms.items))
copy(rv.items, ms.items)
return &rv
}
Adding a new field to myStruct, it is possible to forget to add allocation and copy operations corresponding to this field, thus leading to a situation where the original structure and the clone share the same memory. Usually, this is not expected behavior and causes difficult-to-catch bugs.
The clone package functionality (StructVerifier.Verify) reveals situations where changes to the clone data cause changes to the original structure data, which usually means that the cloning operation is incorrect.
See also verification restrictions.
How to use ¶
An example of the configuration structure with complex fields and the Clone method to make a clone of the configuration:
type Config struct {
Int64param int64
Int64list []int64
StringList []string
MapVals map[string]any
// XXX The following fields are not exported and cannot be verified:
test int64
_Test int64
}
func NewConfig() *Config {
return &Config{}
}
func (c *Config) Clone() *Config {
// Make a simple copy of the original structure
rv := *c
// XXX Further, we need to clone all complex fields (slices, maps, etc...)
rv.Int64list = make([]int64, len(c.Int64list))
copy(rv.Int64list, c.Int64list)
rv.StringList = make([]string, len(c.StringList))
copy(rv.StringList, c.StringList)
rv.MapVals = make(map[string]any, len(c.MapVals))
for k, v := range c.MapVals {
rv.MapVals[k] = v
}
return &rv
}
Now, we can verify Config.Clone method using clone.StructVerifier:
package main
import (
"fmt"
"github.com/r-che/testing/clone"
)
func main() {
sv := clone.NewStructVerifier(
// Creator function
func() any { return NewConfig() },
// Cloner function
func(x any) any {
if c, ok := x.(*Config); ok {
return c.Clone()
}
panic(fmt.Sprintf("unsupported type: got - %T, want - *Config", x))
})
if err := sv.Verify(); err != nil {
fmt.Printf("ERROR: %v\n", err)
} else {
fmt.Printf("Verification successful")
}
}
See more examples in the Examples section.
Example (VerifySuccess) ¶
// Define struct type that need to be tested
type myStruct struct {
Int64 int64
Ints []int
Map map[string]any
}
// Create cloner-function that creates a clone of the myStruct type structure.
// Note: it can also be a structure method, like: func (ms *myStruct) Clone() *myStruct
goodCloner := func(orig *myStruct) *myStruct {
// Make a simple copy of the original structure
rv := *orig
// XXX Further, we need to clone all complex fields (slices, maps, etc...)
// Clone slice with integer using standard copy function
rv.Ints = make([]int, len(orig.Ints))
copy(rv.Ints, orig.Ints)
// Copy all key-value pairs from the map one by one
rv.Map = make(map[string]any, len(orig.Map))
for k, v := range orig.Map {
rv.Map[k] = v
}
// Clone process done, return the created clone
return &rv
}
// intSliceSetter creates a Setter function that will used to fill fields with the type []int
intSliceSetter := func() Setter {
var nextIntVal int
return func(v reflect.Value) any {
if _, ok := v.Interface().([]int); !ok {
return nil
}
nextIntVal++
newLen := nextIntVal * 2 // slice length
s := make([]int, 0, newLen)
for i := 0; i < newLen; i++ {
s = append(s, nextIntVal+i)
}
return s
}
}
// Provide user-defined changer function for []int fields
// intSliceChanger multiplies each []int slice element by two
intSliceChanger := func(v reflect.Value) bool {
is, ok := v.Interface().([]int)
if !ok {
return false
}
for i := range is {
is[i] *= 2
}
return true
}
// Create a new StructVerifier, you must provide the correct creator and cloning functions
verifier := NewStructVerifier(
// Creator function - just return new empty structure
func() any { return &myStruct{} },
// Cloner function
func(x any) any {
// Need to check that the given argument has the correct type
v, ok := x.(*myStruct)
if !ok {
panic(fmt.Sprintf("unsupported type to clone: got - %T, want - *myStruct", x))
}
// Call clone function to return clone of it
return goodCloner(v)
}).
// Add setter function for the []int type
AddSetters(intSliceSetter).
// Add user-defined changer for the []int type
AddChangers(intSliceChanger)
// Perform the verification, expecting it to be successful
err := verifier.Verify()
if err != nil {
fmt.Printf("ERROR: %v\n", err)
} else {
fmt.Printf("Verification successful\n")
}
Output: Verification successful
Example (VerifySuccessComplex) ¶
The code below demonstrates how to use the verifier for the Clone method on the testComplexStruct type, containing fields with complex types like slice and map
package main
import (
"fmt"
"reflect"
)
// testComplexStruct is an example of a structure including fields
// of complex types - slices and map and unused unexported fields
type testComplexStruct struct {
Int64param int64
IntList []int
Int64List []int64
StringList []string
MapVals map[string]any
// XXX The following fields are not exported and cannot be verified
unexported1 bool //nolint:unused // required for testing
_Unexported2 any //nolint:unused // required for testing
}
func newTestComplexStruct() *testComplexStruct {
return &testComplexStruct{}
}
// Clone correctly clones the object on which it is called,
// including copying fields of complex types
func (c *testComplexStruct) Clone() *testComplexStruct {
// Create a simple copy of the configuration
rv := *c
//
// Need to copy all complex fields (slices, maps)
//
rv.IntList = make([]int, len(c.IntList))
copy(rv.IntList, c.IntList)
rv.Int64List = make([]int64, len(c.Int64List))
copy(rv.Int64List, c.Int64List)
rv.StringList = make([]string, len(c.StringList))
copy(rv.StringList, c.StringList)
rv.MapVals = make(map[string]any, len(c.MapVals))
for k, v := range c.MapVals {
rv.MapVals[k] = v
}
return &rv
}
// intSliceSetter creates a Setter function that will used to fill fields with the type []int
func intSliceSetter() Setter {
var initVal int
return func(v reflect.Value) any {
if _, ok := v.Interface().([]int); !ok {
return nil
}
initVal++
l := initVal * 2 // slice length
s := make([]int, 0, l)
for i := 0; i < l; i++ {
s = append(s, initVal+i)
}
return s
}
}
// intSliceChanger multiplies each []int slice element by two
func intSliceChanger(v reflect.Value) bool {
is, ok := v.Interface().([]int)
if !ok {
return false
}
for i := range is {
is[i] *= 2
}
return true
}
// The code below demonstrates how to use the verifier for the Clone method on
// the testComplexStruct type, containing fields with complex types like slice and map
func main() {
// Create verifier
sv := NewStructVerifier(
// Creator function
func() any { return newTestComplexStruct() },
// Cloner function
func(x any) any {
if c, ok := x.(*testComplexStruct); ok {
return c.Clone()
}
panic(fmt.Sprintf("unsupported type: got - %T, want - *Config", x))
}).
// Add our custom setter for the []int type
AddSetters(intSliceSetter).
// Add our custom changer for the []int type
AddChangers(intSliceChanger)
// Perform the verification, expecting it to be successful
if err := sv.Verify(); err != nil {
fmt.Printf("verification error: %v", err)
} else {
fmt.Printf("Verification successful\n")
}
}
Output: Verification successful
Example (VerifyUnsuccessful) ¶
// Define struct type that need to be tested
type myStruct struct {
Int64 int64
Map map[string]any
}
// Creation of buggy cloner function that creates a clone of myStruct type structure
// without actually copying values of Map field
//
// Note: it can also be a structure method, like: func (ms *myStruct) Clone() *myStruct
buggyCloner := func(orig *myStruct) *myStruct {
// Make a simple copy of the original structure
rv := *orig
// XXX We do NOT copy complex fields to make a bug!
// Instead, return the created clone immediately
return &rv
}
// Create a new StructVerifier, you must provide the correct creator and cloning functions
verifier := NewStructVerifier(
// Creator function - just return new empty structure
func() any { return &myStruct{} },
// Cloner function
func(x any) any {
// Need to check that the given argument has the correct type
v, ok := x.(*myStruct)
if !ok {
panic(fmt.Sprintf("unsupported type to clone: got - %T, want - *myStruct", x))
}
// Call clone function to return clone of it
return buggyCloner(v)
})
// Perform the verification, expecting it to be unsuccessful
err := verifier.Verify()
if err == nil {
fmt.Println("ERROR: verifier did not catch the original structure modification")
} else {
fmt.Printf("Got expected error: %T\n", err)
}
Output: Got expected error: *clone.ErrSVOrigChanged
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Changer ¶
Changer defines the type of function used in StructVerifier.Verify to automatically change the field of the appropriate type.
The Changer function must check that the actual data type of the given field is the type that it can change.
If so, it should perform some correct operations to change the data of the given field and return true, that will stop the lookup of a proper Changer to change the field data, after that the verification process will go on to change the next field.
Otherwise, it must return false to allow the field to be passed to the next Changer function.
Set of Changer functions supported by default provided by EmbChangers.
You can define and provide your own Changer functions.
Provide your own Changer ¶
An example of the Changer function to change a field with type []int:
// intSliceChanger multiplies each slice element by two
func intSliceChanger(v reflect.Value) bool {
// Check that the appropriate type of field is passed
is, ok := v.Interface().([]int)
if !ok {
return false
}
// Modify the field value
for i := range is {
is[i] *= 2
}
return true
}
Then, you need to pass this function to the verifier using StructVerifier.AddChangers.
func EmbChangers ¶
func EmbChangers() []Changer
EmbChangers returns a set of embedded Changer functions for the following field types:
- int
- int64
- []int
- []int64
- []string
- map[string]any
type ClonerFunc ¶
ClonerFunc defines the type of function that takes a pointer to a structure of the tested type (created by CreatorFunc) and returns its clone. See NewStructVerifier for more details.
type CreatorFunc ¶
type CreatorFunc func() any
CreatorFunc defines a function type to create a structure of the tested type and return a pointer to it. See NewStructVerifier for more details.
type ErrSVChange ¶
type ErrSVChange struct {
// contains filtered or unexported fields
}
ErrSVChange represents an error that occurs when the value of a field in the tested structure cannot be changed.
type ErrSVCloneOrigEqual ¶
type ErrSVCloneOrigEqual struct {
// contains filtered or unexported fields
}
ErrSVCloneOrigEqual represents an error occurred when the initial value of a cloned structure field was not changed after the Setter function was applied to it.
type ErrSVCloneOrigNotEqual ¶
type ErrSVCloneOrigNotEqual struct {
// contains filtered or unexported fields
}
ErrSVCloneOrigNotEqual represents an error if the original and the cloned structures are different immediately after creation (before the clone changes).
type ErrSVFieldNotFound ¶
type ErrSVFieldNotFound struct {
// contains filtered or unexported fields
}
ErrSVFieldNotFound represents the error which occurs if a clone does not contain the original structure field.
type ErrSVOrigChanged ¶
type ErrSVOrigChanged struct {
// contains filtered or unexported fields
}
ErrSVOrigChanged represents the error occurred when the initial structure (cloning source) was changed after modification of the cloned structure.
type ErrSVOrigFill ¶
type ErrSVOrigFill struct {
// contains filtered or unexported fields
}
ErrSVOrigFill represents an error, that occurs if the source structure cannot be filled automatically.
type ErrSVRefFill ¶
type ErrSVRefFill struct {
// contains filtered or unexported fields
}
ErrSVRefFill represents an error that occurs if the reference structure cannot be automatically filled.
type ErrSVRefOrigEqual ¶
type ErrSVRefOrigEqual struct {
// contains filtered or unexported fields
}
ErrSVRefOrigEqual represents an error if the original and the reference structures are different immediately after creation (before the clone changes).
type Setter ¶
Setter defines the type of function used in StructVerifier.Verify method to automatically create a value appropriate for the field of a given type. The value returned by this function will be assigned to the field of the structure of the corresponding type.
The Setter function must check that the actual data type of the given field is the type of value it can create. In this case, it allocates memory for the new value, fills it with some data valid for that type, then returns the created value.
Otherwise, it must return nil to allow the field to be passed to the next Setter function.
Set of Setter functions supported by default provided by EmbSetters.
Note: for adding your own Setter functions, you must pass a value of type SetterCreator, not Setter, to StructVerifier.AddSetters. See SetterCreator for details.
func EmbSetters ¶
func EmbSetters() []Setter
EmbSetters returns a set of embedded Setter functions for the following field types:
- int
- int64
- []int
- []int64
- []string
- map[string]any
type SetterCreator ¶
type SetterCreator func() Setter
SetterCreator defines the type of function used by the Verify method to create Setter functions.
For automatic initialization of the structure fields, two conditions must be satisfied:
- The same fields of two different structures of the same type must have the same values after initialization - only in this case the equivalence check of the original and the reference will make sense.
- Meanwhile, different fields of the same type must be filled with different data sets. This ensures that cloning errors of the original value will be detected. For example, when field2 is added to the structure, the code that fills it takes the old field field1, which has the same type, as a source instead of the original field2 (Ctrl+C,Ctrl+V programming). If in the original field values of both fields (field1 and field2) initialized by the same values, then in the clone field2 value will match the value of field2 in the source (because field1 and field2 have the same value). Therefore, the error of incomplete cloning will not be detected.
To satisfy both conditions, StructVerifier.AddSetters takes a function that creates a Setter function that uses some initializing value defined by the function that spawned it. For example, the SetterCreator function for fields of type []int can be like this:
func intSliceSetter() Setter {
var initVal int
return func(v reflect.Value) any {
if _, ok := v.Interface().([]int); !ok {
return nil
}
initVal++
l := initVal * 2 // slice length
s := make([]int, 0, l)
for i := 0; i < l; i++ {
s = append(s, initVal + i)
}
return s
}
}
When filling the original structure, the function intSliceSetter is called, which returns a Setter function consistently applied to all fields of type []int. As the result, the first field of type []int will get value []int{1, 2}, the next field of the same type will get value []int{2, 3, 4, 5}, and so on.
When filling the reference structure, the intSliceSetter function will be called again to get a Setter function in which the value of the initVal initializing variable will again be zero, hence - the fields of the reference structure will have the same values as the original one.
type StructVerifier ¶
type StructVerifier struct {
// contains filtered or unexported fields
}
func NewStructVerifier ¶
func NewStructVerifier(creator CreatorFunc, cloner ClonerFunc) *StructVerifier
NewStructVerifier returns the pointer to the created StructVerifier. It takes the creator function that creates a new instance of the structure, and the cloner function, that creates a clone of the given argument and return it. These functions will be used to create the original, reference and cloned objects during the verification process.
See StructVerifier.Verify for how they are used during verification.
func (*StructVerifier) AddChangers ¶
func (sv *StructVerifier) AddChangers(changers ...Changer) *StructVerifier
AddChangers adds a user-defined Changer function that allows you to change the values of fields with a type not supported by the set of Setter functions provided by EmbChangers, or to replace them. User-defined functions added using AddChangers take precedence over embedded Changer functions.
See Changer to understand how to create your own Changer function, and the Examples section.
func (*StructVerifier) AddSetters ¶
func (sv *StructVerifier) AddSetters(setters ...SetterCreator) *StructVerifier
AddChangers adds a user-defined SetterCreator function that allows you to initialize the values of fields with a type not supported by the set of Setter functions provided by EmbSetters, or to replace them. User-defined functions added using AddSetters take precedence over embedded Setter functions.
See Setter and SetterCreator to understand how to create your own Setter function.
func (*StructVerifier) Verify ¶
func (sv *StructVerifier) Verify() error
Verify performs the verification process. It returns an error if the structure clonning process is not correct.
During verification, the following objects are created and used:
- Original object - will be created by calling the creator function as a clone sample, it will be passed as a parameter to the cloner function
- Reference object - is created by calling the creator function and is used for: 1) checking that the creator function works properly - the original object and the reference object are compare before cloning verification, if they are equal then creator works correctly; 2) checking that the original object was not changed during modifications of the clone object created from it
- Cloned object - created by calling the cloner function that takes the original object as a parameter.
The verification process consists of:
- Creation of original and reference objects, compare them with each other - they must be equal.
- Creation of a clone object from the original object using the cloner function.
- Comparison of the original object with the clone - they must be equal.
- Automatically change the data of the exported fields of the clone object using the Setter functions that match the field types.
- Verification that the original object is the same as the reference one - it means that modifications of the clone object did not affect the original object (or if you have a very bad design, also affected the reference object by changing it simultaneously with the original).
- Verification that the clone object is different from the original object, which should reveal the situation of simultaneous modification of all three objects, or incorrect work of Changer-functions.
Verification is considered successful when all the checks are passed.
Only exported fields cloning can be verified ¶
The reason for this is that all fields of the structure need to be modified for a full verification. Go, however, forbids changing the values of non-exportable fields by a code not related to the package of the verified structure.
Your structure can contain non-exported fields, they will be skipped during verification.