Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
dedalqq committed Oct 13, 2021
0 parents commit 8fa436e
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# omg.testingTools

---

3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module omg.testingtools

go 1.17
45 changes: 45 additions & 0 deletions setPrivateValue.go
Original file line number Diff line number Diff line change
@@ -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))
}
18 changes: 18 additions & 0 deletions setPrivateValue_test.go
Original file line number Diff line number Diff line change
@@ -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()
}
}
13 changes: 13 additions & 0 deletions testmodule/omg.go
Original file line number Diff line number Diff line change
@@ -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,
}
}

0 comments on commit 8fa436e

Please sign in to comment.