-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_test.go
108 lines (99 loc) · 2.36 KB
/
json_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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package json
import (
"encoding/json"
"fmt"
"io"
"math"
"os"
"reflect"
"testing"
)
func TestMarshal(t *testing.T) {
// Marshal map
maps := map[string]any{}
file, err := os.Open("unit_test_files/test.json")
if err != nil {
t.Errorf("Error: %v", err)
}
defer file.Close()
fileContent, _ := io.ReadAll(file)
err = json.Unmarshal(fileContent, &maps)
if err != nil {
t.Errorf("Error: %v", err)
}
expected, _ := json.Marshal(maps)
actual, err := Marshal(maps)
if err != nil {
t.Errorf("Error: %v", err)
}
if string(expected) != actual {
t.Errorf("Expected %v, got %v", expected, actual)
}
// Marshal map array
var maps2 []map[string]any
file2, err := os.Open("unit_test_files/test2.json")
if err != nil {
t.Errorf("Error: %v", err)
}
defer file2.Close()
fileContent, err = io.ReadAll(file2)
if err != nil {
t.Errorf("Error: %v", err)
}
err = json.Unmarshal(fileContent, &maps2)
if err != nil {
t.Errorf("Error: %v", err)
}
expected, _ = json.Marshal(maps2)
actual, err = Marshal(maps2)
if err != nil {
t.Errorf("Error: %v", err)
}
if string(expected) != actual {
t.Errorf("Expected %v, got %v", expected, actual)
}
// Marshal crash test
invalidMap := map[string]any{"invalid": math.Inf(-1)}
res, err := Marshal(invalidMap)
fmt.Println(res)
if err == nil {
t.Errorf("Expected error, got %v", err)
}
}
func TestUnmarshal(t *testing.T) {
// Unmarshal Json file
var expected map[string]any
file, _ := os.Open("unit_test_files/test.json")
defer file.Close()
fileContent, _ := io.ReadAll(file)
_ = json.Unmarshal(fileContent, &expected)
actual, err := Unmarshal(string(fileContent))
if err != nil {
t.Errorf("Error: %v", err)
}
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected %v, got %v", expected, actual)
}
// Unmarshal Json Array File
var expect []map[string]any
file2, _ := os.Open("unit_test_files/test2.json")
defer file2.Close()
fileContent2, _ := io.ReadAll(file2)
_ = json.Unmarshal(fileContent2, &expect)
actual, err = Unmarshal(string(fileContent2))
if err != nil {
t.Errorf("Error: %v", err)
}
if !reflect.DeepEqual(expect, actual) {
t.Errorf("Expected %v, got %v", expect, actual)
}
// Unmarshal crash test
_, err = Unmarshal("invalid json")
if err == nil {
t.Errorf("Expected error, got nil")
}
_, err = Unmarshal("[invalid json")
if err == nil {
t.Errorf("Expected error, got nil")
}
}