123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- // Copyright 2022 EMQ Technologies Co., Ltd.
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- package json
- import (
- "encoding/base64"
- "fmt"
- "os"
- "path"
- "reflect"
- "testing"
- )
- func TestMessageDecode(t *testing.T) {
- image, err := os.ReadFile(path.Join("../../../docs", "cover.jpg"))
- if err != nil {
- t.Errorf("Cannot read image: %v", err)
- }
- b64img := base64.StdEncoding.EncodeToString(image)
- tests := []struct {
- payload []byte
- format string
- result map[string]interface{}
- results []interface{}
- }{
- {
- payload: []byte(fmt.Sprintf(`{"format":"jpg","content":"%s"}`, b64img)),
- format: "json",
- result: map[string]interface{}{
- "format": "jpg",
- "content": b64img,
- },
- },
- {
- payload: []byte(`[{"a":1},{"a":2}]`),
- format: "json",
- results: []interface{}{
- map[string]interface{}{
- "a": float64(1),
- },
- map[string]interface{}{
- "a": float64(2),
- },
- },
- },
- }
- conv, _ := GetConverter()
- for i, tt := range tests {
- result, err := conv.Decode(tt.payload)
- if err != nil {
- t.Errorf("%d decode error: %v", i, err)
- }
- if len(tt.results) > 0 {
- if !reflect.DeepEqual(tt.results, result) {
- t.Errorf("%d result mismatch:\n\nexp=%s\n\ngot=%s\n\n", i, tt.result, result)
- }
- } else {
- if !reflect.DeepEqual(tt.result, result) {
- t.Errorf("%d result mismatch:\n\nexp=%s\n\ngot=%s\n\n", i, tt.result, result)
- }
- }
- }
- }
|