...
1
2
3 package ldcontext
4
5 import (
6 "testing"
7
8 "github.com/launchdarkly/go-sdk-common/v3/lderrors"
9
10 "github.com/launchdarkly/go-test-helpers/v3/jsonhelpers"
11
12 "github.com/mailru/easyjson"
13 "github.com/mailru/easyjson/jlexer"
14 "github.com/stretchr/testify/assert"
15 "github.com/stretchr/testify/require"
16 )
17
18 func easyJSONMarshalTestFn(c *Context) ([]byte, error) {
19 return easyjson.Marshal(c)
20 }
21
22 func easyJSONUnmarshalTestFn(c *Context, data []byte) error {
23 return easyjson.Unmarshal(data, c)
24 }
25
26 func easyJSONUnmarshalArrayTestFn(cs *[]Context, data []byte) error {
27 in := jlexer.Lexer{Data: data}
28 in.Delim('[')
29 for !in.IsDelim(']') {
30 var c Context
31 c.UnmarshalEasyJSON(&in)
32 *cs = append(*cs, c)
33 in.WantComma()
34 }
35 in.Delim(']')
36 return in.Error()
37 }
38
39 func TestContextEasyJSONMarshal(t *testing.T) {
40 contextMarshalingTests(t, easyJSONMarshalTestFn)
41 }
42
43 func TestContextEasyJSONUnmarshal(t *testing.T) {
44 contextUnmarshalingTests(t, easyJSONUnmarshalTestFn, easyJSONUnmarshalArrayTestFn)
45 }
46
47 func TestContextEasyJSONMarshalEventOutputFormat(t *testing.T) {
48 for _, p := range makeContextMarshalingEventOutputFormatParams() {
49 t.Run(p.json, func(t *testing.T) {
50 ec := EventOutputContext{Context: p.context}
51 data, err := easyjson.Marshal(ec)
52 assert.NoError(t, err)
53 jsonhelpers.AssertEqual(t, p.json, data)
54 })
55 }
56
57 t.Run("invalid context", func(t *testing.T) {
58 c := New("")
59 ec := EventOutputContext{Context: c}
60 _, err := easyjson.Marshal(ec)
61 require.Error(t, err)
62 assert.Contains(t, err.Error(), lderrors.ErrContextKeyEmpty{}.Error())
63 })
64
65 t.Run("uninitialized context", func(t *testing.T) {
66 var c Context
67 ec := EventOutputContext{Context: c}
68 _, err := easyjson.Marshal(ec)
69 require.Error(t, err)
70 assert.Contains(t, err.Error(), lderrors.ErrContextUninitialized{}.Error())
71 })
72 }
73
74 func TestContextEasyJSONUnmarshalEventOutputFormat(t *testing.T) {
75 t.Run("valid data", func(t *testing.T) {
76 for _, p := range makeAllContextUnmarshalingEventOutputFormatParams() {
77 t.Run(p.json, func(t *testing.T) {
78 var ec EventOutputContext
79 err := easyjson.Unmarshal([]byte(p.json), &ec)
80 assert.NoError(t, err)
81 assert.Equal(t, p.context, ec.Context)
82 })
83 }
84 })
85
86 t.Run("error cases", func(t *testing.T) {
87 for _, badJSON := range makeContextUnmarshalingEventOutputFormatErrorInputs() {
88 t.Run(badJSON, func(t *testing.T) {
89 var c EventOutputContext
90 in := jlexer.Lexer{Data: []byte(badJSON)}
91 ContextSerialization.UnmarshalFromEasyJSONLexerEventOutput(&in, &c)
92 assert.Error(t, in.Error())
93 })
94 }
95 })
96 }
97
View as plain text