forked from emicklei/go-restful-openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_test.go
100 lines (90 loc) · 2.52 KB
/
utils_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
package restfulspec
import (
"bytes"
"encoding/json"
"fmt"
restful "github.com/emicklei/go-restful/v3"
"github.com/go-openapi/spec"
"reflect"
"strings"
"testing"
)
func dummy(i *restful.Request, o *restful.Response) {}
type Sample struct {
ID string `swagger:"required"`
Root Item `json:"root" description:"root desc"`
Items []Item
}
type Item struct {
ItemName string `json:"name"`
}
func asJSON(v interface{}) string {
data, _ := json.MarshalIndent(v, " ", " ")
return string(data)
}
func compareJSON(t *testing.T, actualJSONAsString string, expectedJSONAsString string) bool {
success := false
var actualMap map[string]interface{}
json.Unmarshal([]byte(actualJSONAsString), &actualMap)
var expectedMap map[string]interface{}
err := json.Unmarshal([]byte(expectedJSONAsString), &expectedMap)
if err != nil {
var actualArray []interface{}
json.Unmarshal([]byte(actualJSONAsString), &actualArray)
var expectedArray []interface{}
err := json.Unmarshal([]byte(expectedJSONAsString), &expectedArray)
success = reflect.DeepEqual(actualArray, expectedArray)
if err != nil {
t.Fatalf("Unparsable expected JSON: %s, actual: %v, expected: %v", err, actualJSONAsString, expectedJSONAsString)
}
} else {
success = reflect.DeepEqual(actualMap, expectedMap)
}
if !success {
t.Log("---- expected -----")
t.Log(withLineNumbers(expectedJSONAsString))
t.Log("---- actual -----")
t.Log(withLineNumbers(actualJSONAsString))
t.Log("---- raw -----")
t.Log(actualJSONAsString)
t.Error("there are differences")
return false
}
return true
}
// nolint:unused
func withLineNumbers(content string) string {
var buffer bytes.Buffer
lines := strings.Split(content, "\n")
for i, each := range lines {
buffer.WriteString(fmt.Sprintf("%d:%s\n", i, each))
}
return buffer.String()
}
// mergeStrings returns a new string slice without duplicates.
func mergeStrings(left, right []string) (merged []string) {
include := func(next string) {
for _, dup := range merged {
if next == dup {
return
}
}
merged = append(merged, next)
}
for _, each := range left {
include(each)
}
for _, each := range right {
include(each)
}
return
}
func definitionsFromStructWithConfig(sample interface{}, config Config) spec.Definitions {
definitions := spec.Definitions{}
builder := definitionBuilder{Definitions: definitions, Config: config}
builder.addModelFrom(sample)
return definitions
}
func definitionsFromStruct(sample interface{}) spec.Definitions {
return definitionsFromStructWithConfig(sample, Config{})
}