forked from torbinsky/jsonbuilder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonbuilder_test.go
54 lines (45 loc) · 1.44 KB
/
jsonbuilder_test.go
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
package jsonbuilder_test
import (
"bytes"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/torbinsky/jsonbuilder"
)
type Foo struct {
Name string
Age int
Address string
}
func TestCustomMarshallingUsed(t *testing.T) {
// Test a marshaller that is different but actually gonna make some valid JSON
m := func(i interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
enc := json.NewEncoder(buf)
// Default marshaller uses default encoding settings, so we try to set them to non-default values
enc.SetIndent("", " ")
enc.SetEscapeHTML(false)
err := enc.Encode(i)
return buf.Bytes(), err
}
foo := Foo{"someone", 25, "earth"}
// Marshall and compare result with what comes out of the original function. They should be the same.
a, _ := m(foo)
jh := jsonbuilder.FromMarshaller(foo, m)
b := jh.Marshal()
// Use JSONEq because things like field ordering may change, but the effective JSON should be equivalent
assert.JSONEq(t, string(a), b, "The encodings should produce the same effective JSON.")
// Try something a little more obvious now
m = func(i interface{}) ([]byte, error) {
return []byte("test"), nil
}
jh = jsonbuilder.FromMarshaller(foo, m)
b = jh.Marshal()
assert.Equal(t, "test", b, `"We should get "test"`)
}
func TestMarshallBytes(t *testing.T) {
foo := Foo{"anyone", 42, "mars"}
jh := jsonbuilder.From(foo)
b := jh.MarshalBytes()
assert.NoError(t, json.Unmarshal(b, &foo))
}