|
| 1 | +package io |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/stretchr/testify/assert" |
| 5 | + "go-utils/fs" |
| 6 | + "math" |
| 7 | + "testing" |
| 8 | +) |
| 9 | + |
| 10 | +func TestWriteJsonProvideJsonExpectJsonWritten(t *testing.T) { |
| 11 | + a := assert.New(t) |
| 12 | + |
| 13 | + fs.SetFileSystem(fs.MemFs) |
| 14 | + |
| 15 | + type SampleJson struct { |
| 16 | + Name string |
| 17 | + Des string |
| 18 | + } |
| 19 | + |
| 20 | + sampleJson := SampleJson{ |
| 21 | + Name: "Waterloop", |
| 22 | + Des: "Cool", |
| 23 | + } |
| 24 | + |
| 25 | + err := WriteJson("jsonFile.json", &sampleJson) |
| 26 | + if a.Nil(err) { |
| 27 | + a.True(fs.PathExists("jsonFile.json")) |
| 28 | + } |
| 29 | + |
| 30 | + text, err := fs.ReadFile("jsonFile.json") |
| 31 | + if err != nil { |
| 32 | + t.Fatal(err) |
| 33 | + } |
| 34 | + a.Equal(string(text), `{ |
| 35 | + "Name": "Waterloop", |
| 36 | + "Des": "Cool" |
| 37 | +}`) |
| 38 | +} |
| 39 | + |
| 40 | +func TestWriteJsonProvideInvalidJsonExpectError(t *testing.T) { |
| 41 | + a := assert.New(t) |
| 42 | + |
| 43 | + fs.SetFileSystem(fs.MemFs) |
| 44 | + |
| 45 | + type SampleJson struct { |
| 46 | + Name string |
| 47 | + Des float64 |
| 48 | + } |
| 49 | + |
| 50 | + err := WriteJson("jsonFile.json", &SampleJson{Des: math.NaN()}) |
| 51 | + a.NotNil(err) |
| 52 | + |
| 53 | +} |
| 54 | + |
| 55 | +func TestWriteYamlProvideYamlExpectYamlWritten(t *testing.T) { |
| 56 | + a := assert.New(t) |
| 57 | + |
| 58 | + fs.SetFileSystem(fs.MemFs) |
| 59 | + |
| 60 | + type SampleJson struct { |
| 61 | + Name string |
| 62 | + Des string |
| 63 | + Slice []string `yaml:"slice,omitempty,flow"` |
| 64 | + Map map[string]string `yaml:"map,omitempty"` |
| 65 | + } |
| 66 | + |
| 67 | + sampleJson := SampleJson{ |
| 68 | + Name: "Waterloop", |
| 69 | + Des: "Cool", |
| 70 | + Slice: []string{"Hello"}, |
| 71 | + Map: map[string]string{ |
| 72 | + "1": "One", |
| 73 | + "2": "Two", |
| 74 | + }, |
| 75 | + } |
| 76 | + |
| 77 | + err := WriteYaml("yamlFile.yaml", &sampleJson) |
| 78 | + if a.Nil(err) { |
| 79 | + a.True(fs.PathExists("yamlFile.yaml")) |
| 80 | + } |
| 81 | + |
| 82 | + text, err := fs.ReadFile("yamlFile.yaml") |
| 83 | + if err != nil { |
| 84 | + t.Fatal(err) |
| 85 | + } |
| 86 | + a.Equal(string(text), `name: Waterloop |
| 87 | +des: Cool |
| 88 | +slice: [Hello] |
| 89 | +map: |
| 90 | + "1": One |
| 91 | + "2": Two |
| 92 | +`) |
| 93 | +} |
| 94 | + |
| 95 | +func TestWriteJsonProvideInvalidYamlExpectPanic(t *testing.T) { |
| 96 | + a := assert.New(t) |
| 97 | + |
| 98 | + fs.SetFileSystem(fs.MemFs) |
| 99 | + |
| 100 | + type SampleJson struct { |
| 101 | + Name string `yaml:"name"` |
| 102 | + Des float64 `yaml:"name"` |
| 103 | + } |
| 104 | + |
| 105 | + panicFunc := func() { |
| 106 | + WriteYaml("yamlFile.yaml", &SampleJson{Des: math.NaN()}) |
| 107 | + } |
| 108 | + |
| 109 | + a.Panics(panicFunc) |
| 110 | +} |
0 commit comments