Skip to content

Commit

Permalink
add tests to Clone
Browse files Browse the repository at this point in the history
  • Loading branch information
alichay committed Apr 5, 2023
1 parent f343156 commit f53090c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
7 changes: 4 additions & 3 deletions helpers/clone.go
Expand Up @@ -29,11 +29,12 @@ func CloneFallible[T any](v T) (T, error) {

var nilT T

vPtr := reflectedValue.Interface()
cloned := reflect.New(reflect.Indirect(reflectedValue).Type())
if cloned.Interface() == nil {
if reflectedValue.IsNil() {
return nilT, nil
}

vPtr := reflectedValue.Interface()
cloned := reflect.New(reflect.Indirect(reflectedValue).Type())
err := copier.CopyWithOption(cloned.Interface(), vPtr, copier.Option{IgnoreEmpty: true, DeepCopy: true})
if err != nil {
return nilT, err
Expand Down
46 changes: 46 additions & 0 deletions helpers/clone_test.go
@@ -0,0 +1,46 @@
package helpers

import (
"testing"

"github.com/stretchr/testify/assert"
)

type child struct {
name string
}

type cloneable struct {
a string
b int
c float32
d child
}

func TestClone(t *testing.T) {
cloneMe := cloneable{
a: "abcd",
b: 123,
c: 1.5,
d: child{
name: "aname",
},
}

cloned := Clone(cloneMe)

assert.Equal(t, cloneMe, cloned)

cloneMePtr := &cloneMe

clonedPtr := Clone(cloneMePtr)

assert.NotEmpty(t, clonedPtr)

assert.Equal(t, *cloneMePtr, *clonedPtr)

clonedPtr = nil
clonedNil := Clone(clonedPtr)

assert.Empty(t, clonedNil)
}

0 comments on commit f53090c

Please sign in to comment.