Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

clone

v0.1.3
github.com/r-che/testing/clone

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

37 matches

Top ↑

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:

Config

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
	}

	goodCloner := func(orig *myStruct) *myStruct {

		rv := *orig

		rv.Ints = make([]int, len(orig.Ints))
		copy(rv.Ints, orig.Ints)

		rv.Map = make(map[string]any, len(orig.Map))
		for k, v := range orig.Map {
			rv.Map[k] = v
		}

		return &rv
	}

	intSliceSetter := func() Setter {
		var nextIntVal int
		return func(v reflect.Value) any {
			if _, ok := v.Interface().([]int); !ok {
				return nil
			}
			nextIntVal++

			newLen := nextIntVal * 2
			s := make([]int, 0, newLen)
			for i := 0; i < newLen; i++ {
				s = append(s, nextIntVal+i)
			}

			return s
		}
	}

	intSliceChanger := func(v reflect.Value) bool {
		is, ok := v.Interface().([]int)
		if !ok {
			return false
		}
		for i := range is {
			is[i] *= 2
		}
		return true
	}

	verifier := NewStructVerifier(

		func() any { return &myStruct{} },

		func(x any) any {

			v, ok := x.(*myStruct)
			if !ok {
				panic(fmt.Sprintf("unsupported type to clone: got - %T, want - *myStruct", x))
			}

			return goodCloner(v)
		}).
		AddSetters(intSliceSetter).
		AddChangers(intSliceChanger)

	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 clone

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 Example_verifySuccessComplex() {
	// 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
}
Output:
Verification successful

Example (verifyUnsuccessful)

{
	// Define struct type that need to be tested
	type myStruct struct {
		Int64 int64
		Map   map[string]any
	}

	buggyCloner := func(orig *myStruct) *myStruct {

		rv := *orig

		return &rv
	}

	verifier := NewStructVerifier(

		func() any { return &myStruct{} },

		func(x any) any {

			v, ok := x.(*myStruct)
			if !ok {
				panic(fmt.Sprintf("unsupported type to clone: got - %T, want - *myStruct", x))
			}

			return buggyCloner(v)
		})

	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

Types

Changer

type Changer func(v reflect.Value) bool

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.

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

ClonerFunc

type ClonerFunc func(x any) any

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.

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.

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.

ErrSVChange.Error

func (esv ErrSVChange) Error() string

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.

ErrSVCloneOrigEqual.Error

func (esv ErrSVCloneOrigEqual) Error() string

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).

ErrSVCloneOrigNotEqual.Error

func (esv ErrSVCloneOrigNotEqual) Error() string

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.

ErrSVFieldNotFound.Error

func (esv ErrSVFieldNotFound) Error() string

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.

ErrSVOrigChanged.Error

func (esv ErrSVOrigChanged) Error() string

ErrSVOrigFill

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

ErrSVOrigFill represents an error, that occurs if the source structure cannot be filled automatically.

ErrSVOrigFill.Error

func (esv ErrSVOrigFill) Error() string

ErrSVRefFill

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

ErrSVRefFill represents an error that occurs if the reference structure cannot be automatically filled.

ErrSVRefFill.Error

func (esv ErrSVRefFill) Error() string

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).

ErrSVRefOrigEqual.Error

func (esv ErrSVRefOrigEqual) Error() string

Setter

type Setter func(v reflect.Value) any

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.

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

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:

  1. 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.
  2. 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.

StructVerifier

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

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.

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.

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.

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:

  1. Creation of original and reference objects, compare them with each other - they must be equal.
  2. Creation of a clone object from the original object using the cloner function.
  3. Comparison of the original object with the clone - they must be equal.
  4. Automatically change the data of the exported fields of the clone object using the Setter functions that match the field types.
  5. 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).
  6. 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.

Dependency graph