-
Notifications
You must be signed in to change notification settings - Fork 2
/
diff.go
83 lines (71 loc) · 1.57 KB
/
diff.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
package testingutils
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"github.com/pmezard/go-difflib/difflib"
)
/*
It convert the two objects into pretty json, and diff them, output the result.
*/
func PrettyJsonDiff(expected interface{}, actual interface{}) (r string) {
actualJson := marshalIfNotStringOrReader(actual)
expectedJson := marshalIfNotStringOrReader(expected)
if actualJson != expectedJson {
diff := difflib.UnifiedDiff{
A: difflib.SplitLines(expectedJson),
B: difflib.SplitLines(actualJson),
FromFile: "Expected",
ToFile: "Actual",
Context: 3,
}
r, _ = difflib.GetUnifiedDiffString(diff)
}
return
}
func PrintlnJson(vals ...interface{}) {
var newvals []interface{}
for _, v := range vals {
if s, ok := v.(string); ok {
newvals = append(newvals, s)
continue
}
j, _ := json.MarshalIndent(v, "", "\t")
newvals = append(newvals, "\n", string(j))
}
fmt.Println(newvals...)
}
func marshalIfNotStringOrReader(v interface{}) (r string) {
var ok bool
if r, ok = v.(string); ok {
r = formatIfJson(r)
return
}
var rd io.Reader
if rd, ok = v.(io.Reader); ok {
bs, _ := ioutil.ReadAll(rd)
r = string(bs)
return
}
rbytes, _ := json.MarshalIndent(v, "", "\t")
r = string(rbytes)
return
}
func formatIfJson(input string) (r string) {
var inputRawM json.RawMessage
var err error
err = json.Unmarshal([]byte(input), &inputRawM)
if err != nil {
r = input
return
}
var rbytes []byte
rbytes, err = json.MarshalIndent(inputRawM, "", "\t")
if err != nil {
r = input
return
}
r = string(rbytes)
return
}