field_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package apijson
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/sst/opencode-sdk-go/internal/param"
  6. )
  7. type Struct struct {
  8. A string `json:"a"`
  9. B int64 `json:"b"`
  10. }
  11. type FieldStruct struct {
  12. A param.Field[string] `json:"a"`
  13. B param.Field[int64] `json:"b"`
  14. C param.Field[Struct] `json:"c"`
  15. D param.Field[time.Time] `json:"d" format:"date"`
  16. E param.Field[time.Time] `json:"e" format:"date-time"`
  17. F param.Field[int64] `json:"f"`
  18. }
  19. func TestFieldMarshal(t *testing.T) {
  20. tests := map[string]struct {
  21. value interface{}
  22. expected string
  23. }{
  24. "null_string": {param.Field[string]{Present: true, Null: true}, "null"},
  25. "null_int": {param.Field[int]{Present: true, Null: true}, "null"},
  26. "null_int64": {param.Field[int64]{Present: true, Null: true}, "null"},
  27. "null_struct": {param.Field[Struct]{Present: true, Null: true}, "null"},
  28. "string": {param.Field[string]{Present: true, Value: "string"}, `"string"`},
  29. "int": {param.Field[int]{Present: true, Value: 123}, "123"},
  30. "int64": {param.Field[int64]{Present: true, Value: int64(123456789123456789)}, "123456789123456789"},
  31. "struct": {param.Field[Struct]{Present: true, Value: Struct{A: "yo", B: 123}}, `{"a":"yo","b":123}`},
  32. "string_raw": {param.Field[int]{Present: true, Raw: "string"}, `"string"`},
  33. "int_raw": {param.Field[int]{Present: true, Raw: 123}, "123"},
  34. "int64_raw": {param.Field[int]{Present: true, Raw: int64(123456789123456789)}, "123456789123456789"},
  35. "struct_raw": {param.Field[int]{Present: true, Raw: Struct{A: "yo", B: 123}}, `{"a":"yo","b":123}`},
  36. "param_struct": {
  37. FieldStruct{
  38. A: param.Field[string]{Present: true, Value: "hello"},
  39. B: param.Field[int64]{Present: true, Value: int64(12)},
  40. D: param.Field[time.Time]{Present: true, Value: time.Date(2023, time.March, 18, 14, 47, 38, 0, time.UTC)},
  41. E: param.Field[time.Time]{Present: true, Value: time.Date(2023, time.March, 18, 14, 47, 38, 0, time.UTC)},
  42. },
  43. `{"a":"hello","b":12,"d":"2023-03-18","e":"2023-03-18T14:47:38Z"}`,
  44. },
  45. }
  46. for name, test := range tests {
  47. t.Run(name, func(t *testing.T) {
  48. b, err := Marshal(test.value)
  49. if err != nil {
  50. t.Fatalf("didn't expect error %v", err)
  51. }
  52. if string(b) != test.expected {
  53. t.Fatalf("expected %s, received %s", test.expected, string(b))
  54. }
  55. })
  56. }
  57. }