From b42cc5c8111592220ee5000708c364f6324936a1 Mon Sep 17 00:00:00 2001 From: Dmitry Anderson <4nd3r5z0n@gmail.com> Date: Tue, 12 Nov 2024 11:34:15 +0100 Subject: [PATCH] GetEntityPtrs test added --- reflect/extract_by_tags.go | 3 +-- reflect/extract_by_tags_test.go | 39 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 reflect/extract_by_tags_test.go diff --git a/reflect/extract_by_tags.go b/reflect/extract_by_tags.go index 97aa10e..663fb80 100644 --- a/reflect/extract_by_tags.go +++ b/reflect/extract_by_tags.go @@ -19,8 +19,7 @@ func GetEntityPtrs(dstItem any, tag string) (dstItemPtrsMap map[string]any, err field := t.Field(i) dbTag := field.Tag.Get(tag) if dbTag != "" { - valueField := v.Field(i).Addr().Interface() - dstItemPtrsMap[dbTag] = &valueField + dstItemPtrsMap[dbTag] = v.Field(i).Addr().Interface() } } diff --git a/reflect/extract_by_tags_test.go b/reflect/extract_by_tags_test.go new file mode 100644 index 0000000..cd463c0 --- /dev/null +++ b/reflect/extract_by_tags_test.go @@ -0,0 +1,39 @@ +package reflectUtils + +import "testing" + +type TestStruct struct { + TestVal1 string `test:"test1"` + TestVal2 string `test:"test2"` + TestVal3 string `test:"test3"` +} + +func TestGetEntityPtrs(t *testing.T) { + dst := &TestStruct{ + TestVal1: "test1", + TestVal2: "test2", + TestVal3: "test3", + } + ptrsMap, err := GetEntityPtrs(dst, "test") + if err != nil { + t.Fatal(err.Error()) + } + + valsCounter := 0 + for tag, ptr := range ptrsMap { + if ptr == nil { + t.Fatalf("unexpected nil pointer in a structure") + return + } + val, ok := ptr.(*string) + if !ok { + t.Fatal("failed to extract ptr") + } else if *val != tag { + t.Fatalf("unecpected value: expected test, but got %s", *val) + } + valsCounter++ + } + if valsCounter != 3 { + t.Fatalf("some values are missing") + } +}