2021-04-12 16:54:00 +03:00
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"testing"
|
2021-09-24 00:00:41 +03:00
|
|
|
|
2024-09-17 00:38:06 +03:00
|
|
|
"go.unistack.org/micro/v3/broker"
|
2021-10-03 18:43:19 +03:00
|
|
|
"go.unistack.org/micro/v3/codec"
|
2021-04-12 16:54:00 +03:00
|
|
|
)
|
|
|
|
|
2024-09-17 00:38:06 +03:00
|
|
|
func TestRawMessage(t *testing.T) {
|
|
|
|
b := &broker.Message{}
|
|
|
|
buf, err := NewCodec().Marshal(b)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
t.Logf("%s", buf)
|
|
|
|
}
|
|
|
|
|
2021-09-24 00:00:41 +03:00
|
|
|
func TestFrame(t *testing.T) {
|
|
|
|
s := &codec.Frame{Data: []byte("test")}
|
|
|
|
|
|
|
|
buf, err := NewCodec().Marshal(s)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
if !bytes.Equal(buf, []byte(`test`)) {
|
|
|
|
t.Fatalf("bytes not equal %s != %s", buf, `test`)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestFrameFlatten(t *testing.T) {
|
|
|
|
s := &struct {
|
|
|
|
One string
|
|
|
|
Name *codec.Frame `json:"name" codec:"flatten"`
|
|
|
|
}{
|
|
|
|
One: "xx",
|
|
|
|
Name: &codec.Frame{Data: []byte("test")},
|
|
|
|
}
|
|
|
|
|
2024-09-17 00:38:06 +03:00
|
|
|
buf, err := NewCodec(codec.Flatten(true)).Marshal(s)
|
2021-09-24 00:00:41 +03:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
if !bytes.Equal(buf, []byte(`test`)) {
|
|
|
|
t.Fatalf("bytes not equal %s != %s", buf, `test`)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-25 22:46:40 +03:00
|
|
|
func TestStructByTag(t *testing.T) {
|
|
|
|
type Str struct {
|
|
|
|
Name []string `json:"name" codec:"flatten"`
|
|
|
|
}
|
|
|
|
|
|
|
|
val := &Str{Name: []string{"first", "second"}}
|
|
|
|
|
2024-09-17 00:38:06 +03:00
|
|
|
c := NewCodec(codec.Flatten(true))
|
2021-05-25 22:46:40 +03:00
|
|
|
buf, err := c.Marshal(val)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
if !bytes.Equal(buf, []byte(`["first","second"]`)) {
|
2024-09-17 00:38:06 +03:00
|
|
|
t.Fatalf("invalid marshal: %s != %s", buf, []byte(`["first","second"]`))
|
2021-05-25 22:46:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
err = c.Unmarshal([]byte(`["1","2"]`), val)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(val.Name) != 2 {
|
|
|
|
t.Fatalf("invalid unmarshal: %v", val)
|
|
|
|
}
|
|
|
|
}
|