decode_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2021 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 message
  15. import (
  16. "encoding/base64"
  17. "fmt"
  18. "io/ioutil"
  19. "path"
  20. "reflect"
  21. "testing"
  22. )
  23. func TestMessageDecode(t *testing.T) {
  24. image, err := ioutil.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: image,
  36. format: "binary",
  37. result: map[string]interface{}{
  38. "self": image,
  39. },
  40. }, {
  41. payload: []byte(fmt.Sprintf(`{"format":"jpg","content":"%s"}`, b64img)),
  42. format: "json",
  43. result: map[string]interface{}{
  44. "format": "jpg",
  45. "content": b64img,
  46. },
  47. },
  48. }
  49. for i, tt := range tests {
  50. result, err := Decode(tt.payload, tt.format)
  51. if err != nil {
  52. t.Errorf("%d decode error: %v", i, err)
  53. }
  54. if !reflect.DeepEqual(tt.result, result) {
  55. t.Errorf("%d result mismatch:\n\nexp=%s\n\ngot=%s\n\n", i, tt.result, result)
  56. }
  57. }
  58. }