types_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package api
  2. import (
  3. "encoding/json"
  4. "math"
  5. "testing"
  6. "time"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/stretchr/testify/require"
  9. )
  10. func TestKeepAliveParsingFromJSON(t *testing.T) {
  11. tests := []struct {
  12. name string
  13. req string
  14. exp *Duration
  15. }{
  16. {
  17. name: "Positive Integer",
  18. req: `{ "keep_alive": 42 }`,
  19. exp: &Duration{42 * time.Second},
  20. },
  21. {
  22. name: "Positive Float",
  23. req: `{ "keep_alive": 42.5 }`,
  24. exp: &Duration{42 * time.Second},
  25. },
  26. {
  27. name: "Positive Integer String",
  28. req: `{ "keep_alive": "42m" }`,
  29. exp: &Duration{42 * time.Minute},
  30. },
  31. {
  32. name: "Negative Integer",
  33. req: `{ "keep_alive": -1 }`,
  34. exp: &Duration{math.MaxInt64},
  35. },
  36. {
  37. name: "Negative Float",
  38. req: `{ "keep_alive": -3.14 }`,
  39. exp: &Duration{math.MaxInt64},
  40. },
  41. {
  42. name: "Negative Integer String",
  43. req: `{ "keep_alive": "-1m" }`,
  44. exp: &Duration{math.MaxInt64},
  45. },
  46. }
  47. for _, test := range tests {
  48. t.Run(test.name, func(t *testing.T) {
  49. var dec ChatRequest
  50. err := json.Unmarshal([]byte(test.req), &dec)
  51. require.NoError(t, err)
  52. assert.Equal(t, test.exp, dec.KeepAlive)
  53. })
  54. }
  55. }
  56. func TestDurationMarshalUnmarshal(t *testing.T) {
  57. tests := []struct {
  58. name string
  59. input time.Duration
  60. expected time.Duration
  61. }{
  62. {
  63. "negative duration",
  64. time.Duration(-1),
  65. time.Duration(math.MaxInt64),
  66. },
  67. {
  68. "positive duration",
  69. 42 * time.Second,
  70. 42 * time.Second,
  71. },
  72. {
  73. "another positive duration",
  74. 42 * time.Minute,
  75. 42 * time.Minute,
  76. },
  77. {
  78. "zero duration",
  79. time.Duration(0),
  80. time.Duration(0),
  81. },
  82. {
  83. "max duration",
  84. time.Duration(math.MaxInt64),
  85. time.Duration(math.MaxInt64),
  86. },
  87. }
  88. for _, test := range tests {
  89. t.Run(test.name, func(t *testing.T) {
  90. b, err := json.Marshal(Duration{test.input})
  91. require.NoError(t, err)
  92. var d Duration
  93. err = json.Unmarshal(b, &d)
  94. require.NoError(t, err)
  95. assert.Equal(t, test.expected, d.Duration, "input %v, marshalled %v, got %v", test.input, string(b), d.Duration)
  96. })
  97. }
  98. }