From 8fa436ed1ac4200ff58b9f2c688c6e65dfac7500 Mon Sep 17 00:00:00 2001 From: "dedal.qq" Date: Wed, 13 Oct 2021 16:51:36 +0300 Subject: [PATCH] first commit --- README.md | 4 ++++ go.mod | 3 +++ setPrivateValue.go | 45 +++++++++++++++++++++++++++++++++++++++++ setPrivateValue_test.go | 18 +++++++++++++++++ testmodule/omg.go | 13 ++++++++++++ 5 files changed, 83 insertions(+) create mode 100644 README.md create mode 100644 go.mod create mode 100644 setPrivateValue.go create mode 100644 setPrivateValue_test.go create mode 100644 testmodule/omg.go diff --git a/README.md b/README.md new file mode 100644 index 0000000..af3c1b2 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +# omg.testingTools + +--- + diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e03836f --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module omg.testingtools + +go 1.17 diff --git a/setPrivateValue.go b/setPrivateValue.go new file mode 100644 index 0000000..f73f17a --- /dev/null +++ b/setPrivateValue.go @@ -0,0 +1,45 @@ +package testingtools + +import ( + "fmt" + "reflect" + "unsafe" +) + +func SetPrivateValue(obj interface{}, fieldName string, value interface{}) { + reflectValue := reflect.ValueOf(obj) + + if reflectValue.Kind() != reflect.Ptr { + panic("object is not a pointer") + } + + reflectValue = reflectValue.Elem() + reflectType := reflect.TypeOf(obj).Elem() + + if reflectValue.Kind() != reflect.Struct { + panic("object is not a pointer to struct") + } + + newReflectValueType := reflect.TypeOf(value) + + var offset uintptr + + for i := 0; i < reflectValue.NumField(); i++ { + if reflectType.Field(i).Name == fieldName { + currentFieldType := reflectType.Field(i).Type.String() + + if newReflectValueType.String() != currentFieldType { + panic(fmt.Sprintf("incorrect type: must be %s", currentFieldType)) + } + + fieldPtr := unsafe.Pointer(reflectValue.UnsafeAddr() + offset) + reflect.NewAt(newReflectValueType, fieldPtr).Elem().Set(reflect.ValueOf(value)) + + return + } + + offset += reflectValue.Field(i).Type().Size() + } + + panic(fmt.Sprintf("Field [%s] not found in struct", fieldName)) +} diff --git a/setPrivateValue_test.go b/setPrivateValue_test.go new file mode 100644 index 0000000..d2078f5 --- /dev/null +++ b/setPrivateValue_test.go @@ -0,0 +1,18 @@ +package testingtools + +import ( + "fmt" + "omg.testingtools/testmodule" + "testing" +) + +func TestSetPrivateValue(t *testing.T) { + qq := testmodule.NewQQ(123, "abc", []int{5, 6, 7}) + + SetPrivateValue(&qq, "c", []int{1, 2, 3, 4}) + SetPrivateValue(&qq, "b", "qwe") + + if fmt.Sprint(qq) != "{123 qwe [1 2 3 4]}" { + t.Fail() + } +} diff --git a/testmodule/omg.go b/testmodule/omg.go new file mode 100644 index 0000000..be4af55 --- /dev/null +++ b/testmodule/omg.go @@ -0,0 +1,13 @@ +package testmodule + +type TestStruct struct { + a int + b string + c []int +} + +func NewQQ(a int, b string, c []int) TestStruct { + return TestStruct{ + a, b, c, + } +}