encoding_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package util
  2. import (
  3. "testing"
  4. "time"
  5. )
  6. type TestString string
  7. type SubStruct struct {
  8. A string
  9. B int
  10. }
  11. type MyStruct struct {
  12. SubStruct
  13. }
  14. type YourStruct struct {
  15. SubStruct SubStruct
  16. }
  17. func TestConvertToQueryValues2(t *testing.T) {
  18. result := ConvertToQueryValues(MyStruct{SubStruct: SubStruct{A: "A", B: 1}}).Encode()
  19. const expectedResult = "A=A&B=1"
  20. if result != expectedResult {
  21. // Sometimes result is not matched for the different orders
  22. t.Logf("Incorrect encoding: %s", result)
  23. }
  24. result2 := ConvertToQueryValues(YourStruct{SubStruct: SubStruct{A: "A2", B: 2}}).Encode()
  25. const expectedResult2 = "SubStruct.A=A2&SubStruct.B=2"
  26. if result2 != expectedResult2 {
  27. // Sometimes result is not matched for the different orders
  28. t.Logf("Incorrect encoding: %s", result2)
  29. }
  30. }
  31. type TestStruct struct {
  32. Format string
  33. Version string
  34. AccessKeyId string
  35. Timestamp time.Time
  36. Empty string
  37. IntValue int `ArgName:"int-value"`
  38. BoolPtr *bool `ArgName:"bool-ptr"`
  39. IntPtr *int `ArgName:"int-ptr"`
  40. StringArray []string `ArgName:"str-array"`
  41. StructArray []SubStruct
  42. SubStruct SubStruct
  43. test TestString
  44. tests []TestString
  45. Tag map[string]string
  46. }
  47. func TestConvertToQueryValues(t *testing.T) {
  48. boolValue := true
  49. request := TestStruct{
  50. Format: "JSON",
  51. Version: "1.0",
  52. Timestamp: time.Date(2015, time.Month(5), 26, 1, 2, 3, 4, time.UTC),
  53. IntValue: 10,
  54. BoolPtr: &boolValue,
  55. StringArray: []string{"abc", "xyz"},
  56. StructArray: []SubStruct{
  57. SubStruct{A: "a", B: 1},
  58. SubStruct{A: "x", B: 2},
  59. },
  60. SubStruct: SubStruct{A: "M", B: 0},
  61. test: TestString("test"),
  62. tests: []TestString{TestString("test1"), TestString("test2")},
  63. Tag: map[string]string{"abc": "xyz", "123": "456"},
  64. }
  65. result := ConvertToQueryValues(&request).Encode()
  66. const expectedResult = "Format=JSON&StructArray.1.A=a&StructArray.1.B=1&StructArray.2.A=x&StructArray.2.B=2&SubStruct.A=M&Tag.1.Key=abc&Tag.1.Value=xyz&Tag.2.Key=123&Tag.2.Value=456&Timestamp=2015-05-26T01%3A02%3A03Z&Version=1.0&bool-ptr=true&int-value=10&str-array=%5B%22abc%22%2C%22xyz%22%5D&test=test&tests=%5B%22test1%22%2C%22test2%22%5D"
  67. if result != expectedResult {
  68. // Sometimes result is not matched for the different orders
  69. t.Logf("Incorrect encoding: %s", result)
  70. }
  71. }