maker_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package reflectutils
  2. import (
  3. "fmt"
  4. "github.com/pkg/errors"
  5. "reflect"
  6. "testing"
  7. "time"
  8. )
  9. func TestStruct(t *testing.T) {
  10. name := "test"
  11. age := 18
  12. enterTime := time.Now().Local()
  13. studentStruct := NewStruct(
  14. StructFieldDefinition{
  15. Name: "Name",
  16. Type: reflect.TypeOf(""),
  17. Tag: "json:name",
  18. },
  19. StructFieldDefinition{
  20. Name: "Age",
  21. Type: reflect.TypeOf(0),
  22. Tag: "json:age",
  23. },
  24. StructFieldDefinition{
  25. Name: "EnterTime",
  26. Type: reflect.TypeOf(time.Time{}),
  27. Tag: "json:enterTime",
  28. },
  29. )
  30. studentStruct.SetFieldValues(map[string]any{
  31. "Name": name,
  32. "Age": age,
  33. "EnterTime": enterTime,
  34. })
  35. values := studentStruct.FieldValues("Name", "Age", "EnterTime")
  36. for fieldName, value := range values {
  37. switch fieldName {
  38. case "Name":
  39. if value != name {
  40. t.Fatalf("%+v\n", errors.Errorf("名字不一致: except: %v, actual: %v", name, value))
  41. }
  42. case "Age":
  43. if value != age {
  44. t.Fatalf("%+v\n", errors.Errorf("年龄不一致: except: %v, actual: %v", age, value))
  45. }
  46. case "EnterTime":
  47. if value != enterTime {
  48. t.Fatalf("%+v\n", errors.Errorf("入学时间不一致: except: %v, actual: %v", enterTime, value))
  49. }
  50. default:
  51. t.Fatalf("%+v\n", errors.New("不存在的字段"))
  52. }
  53. }
  54. studentStruct.MakeMethod(
  55. StructMethodDefinition{
  56. Name: "Print",
  57. ArgTypes: []reflect.Type{reflect.TypeOf("")},
  58. ReturnValueTypes: []reflect.Type{reflect.TypeOf(errors.New(""))},
  59. Body: func(s *Struct, args ...any) []any {
  60. values := studentStruct.FieldValues("Name", "Age", "EnterTime")
  61. fmt.Println("Student Info:")
  62. fmt.Println("Name:", values["Name"])
  63. fmt.Println("Age:", values["Age"])
  64. fmt.Println("EnterTime:", values["EnterTime"].(time.Time).Format(time.DateTime))
  65. fmt.Println("Arg:", args[0])
  66. return []any{nil}
  67. },
  68. },
  69. )
  70. returns := studentStruct.CallMethod("Print", "Hello Args")
  71. if returns[0] != nil {
  72. t.Fatalf("%+v\n", errors.Errorf("%v", returns[0]))
  73. }
  74. }
  75. func TestFunction(t *testing.T) {
  76. printHelloFunc := MakeFunction(FunctionDefinition{
  77. ArgTypes: []reflect.Type{reflect.TypeOf("")},
  78. ReturnValueTypes: []reflect.Type{reflect.TypeOf(errors.New(""))},
  79. Body: func(args ...any) []any {
  80. fmt.Printf("Hello %v!\n", args[0])
  81. return []any{nil}
  82. },
  83. })
  84. returns := printHelloFunc.Call("World")
  85. if returns[0] != nil {
  86. t.Fatalf("%+v\n", errors.Errorf("%v", returns[0]))
  87. }
  88. }