| 1 |
package utils |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"testing" |
| 6 |
|
| 7 |
"github.com/stretchr/testify/require" |
| 8 |
) |
| 9 |
|
| 10 |
type sampleStructure struct { |
| 11 |
ImportantString string `json:"important_string"` |
| 12 |
} |
| 13 |
|
| 14 |
func Test_GolangJSONEncoder(t *testing.T) { |
| 15 |
t.Parallel() |
| 16 |
|
| 17 |
var ( |
| 18 |
ss = &sampleStructure{ |
| 19 |
ImportantString: "Hello World", |
| 20 |
} |
| 21 |
importantString = `{"important_string":"Hello World"}` |
| 22 |
jsonEncoder JSONMarshal = json.Marshal |
| 23 |
) |
| 24 |
|
| 25 |
raw, err := jsonEncoder(ss) |
| 26 |
require.NoError(t, err) |
| 27 |
|
| 28 |
require.Equal(t, string(raw), importantString) |
| 29 |
} |
| 30 |
|
| 31 |
func Test_DefaultJSONEncoder(t *testing.T) { |
| 32 |
t.Parallel() |
| 33 |
|
| 34 |
var ( |
| 35 |
ss = &sampleStructure{ |
| 36 |
ImportantString: "Hello World", |
| 37 |
} |
| 38 |
importantString = `{"important_string":"Hello World"}` |
| 39 |
jsonEncoder JSONMarshal = json.Marshal |
| 40 |
) |
| 41 |
|
| 42 |
raw, err := jsonEncoder(ss) |
| 43 |
require.NoError(t, err) |
| 44 |
|
| 45 |
require.Equal(t, string(raw), importantString) |
| 46 |
} |
| 47 |
|
| 48 |
func Test_DefaultJSONDecoder(t *testing.T) { |
| 49 |
t.Parallel() |
| 50 |
|
| 51 |
var ( |
| 52 |
ss sampleStructure |
| 53 |
importantString = []byte(`{"important_string":"Hello World"}`) |
| 54 |
jsonDecoder JSONUnmarshal = json.Unmarshal |
| 55 |
) |
| 56 |
|
| 57 |
err := jsonDecoder(importantString, &ss) |
| 58 |
require.NoError(t, err) |
| 59 |
require.Equal(t, "Hello World", ss.ImportantString) |
| 60 |
} |
| 61 |
|
| 62 |
func Test_JSONDecodeInvalid(t *testing.T) { |
| 63 |
t.Parallel() |
| 64 |
|
| 65 |
var ss sampleStructure |
| 66 |
err := json.Unmarshal([]byte("{invalid}"), &ss) |
| 67 |
require.Error(t, err) |
| 68 |
} |