summaryrefslogtreecommitdiff
path: root/plugins/grpc/codec/codec_test.go
blob: 60efb07293f623ccc2f4a3a62fbf3a99bbde9fd6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package codec

import (
	"testing"

	json "github.com/json-iterator/go"
	"github.com/stretchr/testify/assert"
)

type jsonCodec struct{}

func (jsonCodec) Marshal(v interface{}) ([]byte, error) {
	return json.Marshal(v)
}

func (jsonCodec) Unmarshal(data []byte, v interface{}) error {
	return json.Unmarshal(data, v)
}

func (jsonCodec) Name() string {
	return "json"
}

func TestCodec_String(t *testing.T) {
	c := Codec{jsonCodec{}}

	assert.Equal(t, "raw:json", c.String())

	r := RawMessage{}
	r.Reset()
	r.ProtoMessage()
	assert.Equal(t, "rawMessage", r.String())
}

func TestCodec_Unmarshal_ByPass(t *testing.T) {
	c := Codec{jsonCodec{}}

	s := struct {
		Name string
	}{}

	assert.NoError(t, c.Unmarshal([]byte(`{"name":"name"}`), &s))
	assert.Equal(t, "name", s.Name)
}

func TestCodec_Marshal_ByPass(t *testing.T) {
	c := Codec{jsonCodec{}}

	s := struct {
		Name string
	}{
		Name: "name",
	}

	d, err := c.Marshal(s)
	assert.NoError(t, err)

	assert.Equal(t, `{"Name":"name"}`, string(d))
}

func TestCodec_Unmarshal_Raw(t *testing.T) {
	c := Codec{jsonCodec{}}

	s := RawMessage{}

	assert.NoError(t, c.Unmarshal([]byte(`{"name":"name"}`), &s))
	assert.Equal(t, `{"name":"name"}`, string(s))
}

func TestCodec_Marshal_Raw(t *testing.T) {
	c := Codec{jsonCodec{}}

	s := RawMessage(`{"Name":"name"}`)

	d, err := c.Marshal(s)
	assert.NoError(t, err)

	assert.Equal(t, `{"Name":"name"}`, string(d))
}