converter_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. var tests = []struct {
  30. payload []byte
  31. format string
  32. result map[string]interface{}
  33. }{
  34. {
  35. payload: []byte(fmt.Sprintf(`{"format":"jpg","content":"%s"}`, b64img)),
  36. format: "json",
  37. result: map[string]interface{}{
  38. "format": "jpg",
  39. "content": b64img,
  40. },
  41. },
  42. }
  43. conv, _ := GetConverter()
  44. for i, tt := range tests {
  45. result, err := conv.Decode(tt.payload)
  46. if err != nil {
  47. t.Errorf("%d decode error: %v", i, err)
  48. }
  49. if !reflect.DeepEqual(tt.result, result) {
  50. t.Errorf("%d result mismatch:\n\nexp=%s\n\ngot=%s\n\n", i, tt.result, result)
  51. }
  52. }
  53. }