struct_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package test
  2. import (
  3. "testing"
  4. "github.com/modern-go/reflect2"
  5. "github.com/v2pro/plz/test"
  6. "github.com/v2pro/plz/countlog"
  7. "unsafe"
  8. "github.com/v2pro/plz/test/must"
  9. )
  10. func Test_struct(t *testing.T) {
  11. type TestObject struct {
  12. Field1 int
  13. Field2 int
  14. }
  15. var pInt = func(val int) *int {
  16. return &val
  17. }
  18. t.Run("New", testOp(func(api reflect2.API) interface{} {
  19. valType := api.TypeOf(TestObject{})
  20. obj := valType.New()
  21. obj.(*TestObject).Field1 = 20
  22. obj.(*TestObject).Field2 = 100
  23. return obj
  24. }))
  25. t.Run("PackEFace", test.Case(func(ctx *countlog.Context) {
  26. valType := reflect2.TypeOf(TestObject{})
  27. ptr := valType.UnsafeNew()
  28. must.Equal(&TestObject{}, valType.PackEFace(ptr))
  29. }))
  30. t.Run("Indirect", test.Case(func(ctx *countlog.Context) {
  31. valType := reflect2.TypeOf(TestObject{})
  32. must.Equal(TestObject{}, valType.Indirect(&TestObject{}))
  33. }))
  34. t.Run("SetIndex", testOp(func(api reflect2.API) interface{} {
  35. valType := api.TypeOf(TestObject{}).(reflect2.StructType)
  36. field1 := valType.FieldByName("Field1")
  37. obj := TestObject{}
  38. field1.Set(&obj, pInt(100))
  39. return obj
  40. }))
  41. t.Run("UnsafeSetIndex", test.Case(func(ctx *countlog.Context) {
  42. valType := reflect2.TypeOf(TestObject{}).(reflect2.StructType)
  43. field1 := valType.FieldByName("Field1")
  44. obj := TestObject{}
  45. field1.UnsafeSet(unsafe.Pointer(&obj), reflect2.PtrOf(100))
  46. must.Equal(100, obj.Field1)
  47. }))
  48. t.Run("GetIndex", testOp(func(api reflect2.API) interface{} {
  49. obj := TestObject{Field1: 100}
  50. valType := api.TypeOf(obj).(reflect2.StructType)
  51. field1 := valType.FieldByName("Field1")
  52. return field1.Get(&obj)
  53. }))
  54. t.Run("UnsafeGetIndex", test.Case(func(ctx *countlog.Context) {
  55. obj := TestObject{Field1: 100}
  56. valType := reflect2.TypeOf(obj).(reflect2.StructType)
  57. field1 := valType.FieldByName("Field1")
  58. value := field1.UnsafeGet(unsafe.Pointer(&obj))
  59. must.Equal(100, *(*int)(value))
  60. }))
  61. }