-
Notifications
You must be signed in to change notification settings - Fork 0
/
report.go
106 lines (90 loc) · 2.18 KB
/
report.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
package grpcdiff
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"time"
"github.com/sergi/go-diff/diffmatchpatch"
)
type Report struct {
input string
resA []byte
resB []byte
durA time.Duration
durB time.Duration
diffs []diffmatchpatch.Diff
dmp *diffmatchpatch.DiffMatchPatch
}
func NewReport(input string, resA, resB []byte, durA, durB time.Duration) *Report {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(string(resA), string(resB), true)
return &Report{
input: input,
resA: resA,
resB: resB,
durA: durA,
durB: durB,
diffs: diffs,
dmp: dmp,
}
}
func (r *Report) Report() string {
if r.HasDiff() {
filenameA, filenameB := r.WriteResToFile()
return fmt.Sprintf("input %s has diff that you can see at %s and %s", r.input, filenameA, filenameB)
}
return fmt.Sprintf("input %s: %s", r.input, r.GetDurationAnalysis())
}
func (r *Report) HasDiff() bool {
for _, diff := range r.diffs {
if diff.Type != diffmatchpatch.DiffEqual {
return true
}
}
return false
}
func (r *Report) GetFormattedDiff() string {
return r.dmp.DiffPrettyText(r.diffs)
}
func (r *Report) GetDurationAnalysis() string {
var longger = "A"
var durLong time.Duration
var durShort time.Duration
if r.durA > r.durB {
longger = "A"
durLong = r.durA
durShort = r.durB
} else if r.durB > r.durA {
longger = "B"
durLong = r.durB
durShort = r.durA
} else {
return "duration is exactly equals"
}
comparison := float64(durLong)/float64(durShort) - 1.0
if comparison > 0.1 {
return fmt.Sprintf("%s takes more %.02fx times (durA: %v, durB: %v)", longger, comparison, r.durA, r.durB)
}
return "duration is quite same"
}
func (r *Report) WriteResToFile() (filenameA, filenameB string) {
filename := r.generateFileName()
filenameA = filename + "-A.json"
filenameB = filename + "-B.json"
r.writeFile(filenameA, r.resA)
r.writeFile(filenameB, r.resB)
return
}
func (r *Report) writeFile(filename string, content []byte) {
err := ioutil.WriteFile(filename, content, os.ModePerm)
if err != nil {
panic(err)
}
}
func (r *Report) generateFileName() string {
randBytes := make([]byte, 16)
rand.Read(randBytes)
return hex.EncodeToString(randBytes)
}