1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-14 11:57:48 +00:00

chore: add data utils package unit tests (#5802)

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
This commit is contained in:
Charles-Edouard Brétéché 2022-12-29 15:30:36 +01:00 committed by GitHub
parent 7efd40adcd
commit 490e799b77
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 112 additions and 0 deletions

View file

@ -17,6 +17,9 @@ func CopyMap(m map[string]interface{}) map[string]interface{} {
// CopySliceOfMaps creates a full copy of the target slice
func CopySliceOfMaps(s []map[string]interface{}) []interface{} {
if s == nil {
return nil
}
sliceCopy := make([]interface{}, len(s))
for i, v := range s {
sliceCopy[i] = CopyMap(v)

View file

@ -1,6 +1,7 @@
package data
import (
"reflect"
"testing"
"gotest.tools/assert"
@ -93,3 +94,111 @@ func TestSliceContains(t *testing.T) {
})
}
}
func TestToMap(t *testing.T) {
type data struct {
Dummy string
}
type args struct {
data interface{}
}
tests := []struct {
name string
args args
want map[string]interface{}
wantErr bool
}{
{
name: "with map[string]interface{}",
args: args{
data: map[string]interface{}{},
},
want: map[string]interface{}{},
wantErr: false,
},
{
name: "with string",
args: args{
data: "foo",
},
want: nil,
wantErr: true,
},
{
name: "with nil",
args: args{
data: nil,
},
want: nil,
wantErr: false,
},
{
name: "with struct",
args: args{
data: data{Dummy: "foo"},
},
want: map[string]interface{}{
"Dummy": "foo",
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ToMap(tt.args.data)
if (err != nil) != tt.wantErr {
t.Errorf("ToMap() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("ToMap() = %v, want %v", got, tt.want)
}
})
}
}
func TestCopySliceOfMaps(t *testing.T) {
originalMap := map[string]interface{}{
"rsc": 3711,
"r": 2138,
"gri": 1908,
"adg": 912,
}
type args struct {
s []map[string]interface{}
}
tests := []struct {
name string
args args
want []interface{}
}{
{
name: "with nil",
args: args{
s: nil,
},
want: nil,
},
{
name: "with empty",
args: args{
s: []map[string]interface{}{},
},
want: []interface{}{},
},
{
name: "with data",
args: args{
s: []map[string]interface{}{originalMap},
},
want: []interface{}{originalMap},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := CopySliceOfMaps(tt.args.s); !reflect.DeepEqual(got, tt.want) {
t.Errorf("CopySliceOfMaps() = %v, want %v", got, tt.want)
}
})
}
}