converter_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package json
  15. import (
  16. "encoding/base64"
  17. "fmt"
  18. "os"
  19. "path"
  20. "reflect"
  21. "testing"
  22. )
  23. func TestMessageDecode(t *testing.T) {
  24. image, err := os.ReadFile(path.Join("../../../docs", "cover.jpg"))
  25. if err != nil {
  26. t.Errorf("Cannot read image: %v", err)
  27. }
  28. b64img := base64.StdEncoding.EncodeToString(image)
  29. tests := []struct {
  30. payload []byte
  31. format string
  32. result map[string]interface{}
  33. results []interface{}
  34. }{
  35. {
  36. payload: []byte(fmt.Sprintf(`{"format":"jpg","content":"%s"}`, b64img)),
  37. format: "json",
  38. result: map[string]interface{}{
  39. "format": "jpg",
  40. "content": b64img,
  41. },
  42. },
  43. {
  44. payload: []byte(`[{"a":1},{"a":2}]`),
  45. format: "json",
  46. results: []interface{}{
  47. map[string]interface{}{
  48. "a": float64(1),
  49. },
  50. map[string]interface{}{
  51. "a": float64(2),
  52. },
  53. },
  54. },
  55. }
  56. conv, _ := GetConverter()
  57. for i, tt := range tests {
  58. result, err := conv.Decode(tt.payload)
  59. if err != nil {
  60. t.Errorf("%d decode error: %v", i, err)
  61. }
  62. if len(tt.results) > 0 {
  63. if !reflect.DeepEqual(tt.results, result) {
  64. t.Errorf("%d result mismatch:\n\nexp=%s\n\ngot=%s\n\n", i, tt.result, result)
  65. }
  66. } else {
  67. if !reflect.DeepEqual(tt.result, result) {
  68. t.Errorf("%d result mismatch:\n\nexp=%s\n\ngot=%s\n\n", i, tt.result, result)
  69. }
  70. }
  71. }
  72. }