-
Notifications
You must be signed in to change notification settings - Fork 204
/
import.go
188 lines (157 loc) · 5.52 KB
/
import.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package hoverfly
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"strconv"
"github.com/SpectoLabs/hoverfly/core/delay"
v2 "github.com/SpectoLabs/hoverfly/core/handlers/v2"
"github.com/SpectoLabs/hoverfly/core/state"
"github.com/SpectoLabs/hoverfly/core/util"
"github.com/SpectoLabs/hoverfly/core/models"
log "github.com/sirupsen/logrus"
)
// Import is a function that based on input decides whether it is a local resource or whether
// it should fetch it from remote server. It then imports given payload into the database
// or returns an error
func (hf *Hoverfly) Import(uri string) error {
// assuming file URI is URL:
if util.IsURL(uri) {
log.WithFields(log.Fields{
"isURL": util.IsURL(uri),
"importFrom": uri,
}).Info("URL")
return hf.ImportFromURL(uri)
}
// assuming file URI is disk location
ext := path.Ext(uri)
if ext != ".json" {
return fmt.Errorf("Failed to import payloads, only JSON files are acceppted. Given file: %s", uri)
}
// checking whether it exists
exists, err := exists(uri)
if err != nil {
return fmt.Errorf("Failed to import payloads from %s. Got error: %s", uri, err.Error())
}
if exists {
// file is JSON and it exist
return hf.ImportFromDisk(uri)
}
return fmt.Errorf("Failed to import payloads, given file '%s' does not exist", uri)
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
// ImportFromDisk - takes one string value and tries to open a file, then parse it into recordedRequests structure
// (which is default format in which Hoverfly exports captured requests) and imports those requests into the database
func (hf *Hoverfly) ImportFromDisk(path string) error {
pairsFile, err := os.Open(path)
if err != nil {
return fmt.Errorf("Got error while opening payloads file, error %s", err.Error())
}
defer pairsFile.Close()
var simulation v2.SimulationViewV5
body, err := ioutil.ReadAll(pairsFile)
if err != nil {
return fmt.Errorf("Got error while parsing payloads, error %s", err.Error())
}
err = json.Unmarshal(body, &simulation)
if err != nil {
return fmt.Errorf("Got error while parsing payloads, error %s", err.Error())
}
return hf.PutSimulation(simulation).GetError()
}
// ImportFromURL - takes one string value and tries connect to a remote server, then parse response body into
// recordedRequests structure (which is default format in which Hoverfly exports captured requests) and
// imports those requests into the database
func (hf *Hoverfly) ImportFromURL(url string) error {
resp, err := http.DefaultClient.Get(url)
if err != nil {
return fmt.Errorf("Failed to fetch given URL, error %s", err.Error())
}
var simulation v2.SimulationViewV5
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Got error while parsing payloads, error %s", err.Error())
}
err = json.Unmarshal(body, &simulation)
if err != nil {
return fmt.Errorf("Got error while parsing payloads, error %s", err.Error())
}
return hf.PutSimulation(simulation).GetError()
}
// importRequestResponsePairViews along with custom data - a function to save given pairs into the database. custom data is loaded before request/response pair so that in case someone access it, it ll be able to render
func (hf *Hoverfly) importRequestResponsePairViewsWithCustomData(pairViews []v2.RequestMatcherResponsePairViewV5, literals []v2.GlobalLiteralViewV5, variables []v2.GlobalVariableViewV5) v2.SimulationImportResult {
importResult := v2.SimulationImportResult{}
initialStates := map[string]string{}
if len(pairViews) > 0 {
hf.SetLiterals(literals)
if err := hf.SetVariables(variables); err != nil {
importResult.SetError(err)
return importResult
}
success := 0
failed := 0
for i, pairView := range pairViews {
if _, ok := hf.PostServeActionDetails.Actions[pairView.Response.PostServeAction]; pairView.Response.PostServeAction != "" && !ok && hf.PostServeActionDetails.FallbackAction == nil {
importResult.SetError(fmt.Errorf("invalid post server action name provided"))
break
}
pair := models.NewRequestMatcherResponsePairFromView(&pairView)
if pairView.Response.LogNormalDelay != nil {
d := *pairView.Response.LogNormalDelay
if err := delay.ValidateLogNormalDelayOptions(d.Min, d.Max, d.Mean, d.Median); err != nil {
failed++
importResult.SetError(err)
break
}
}
var isPairAdded bool
if hf.Cfg.NoImportCheck {
hf.Simulation.AddPairWithoutCheck(pair)
isPairAdded = true
} else {
isPairAdded = hf.Simulation.AddPair(pair)
}
if isPairAdded {
for k, v := range pair.RequestMatcher.RequiresState {
initialStates[k] = v
}
success++
} else {
importResult.AddPairIgnoredWarning(i)
}
if len(pairView.Response.Headers["Content-Length"]) > 0 && len(pairView.Response.Headers["Transfer-Encoding"]) > 0 {
importResult.AddContentLengthAndTransferEncodingWarning(i)
}
if len(pairView.Response.Headers["Content-Length"]) > 0 {
contentLength, err := strconv.Atoi(pairView.Response.Headers["Content-Length"][0])
if err == nil && contentLength != len(pair.Response.Body) {
importResult.AddContentLengthMismatchWarning(i)
}
}
continue
}
if hf.state == nil {
hf.state = state.NewState()
}
hf.state.InitializeSequences(initialStates)
log.WithFields(log.Fields{
"total": len(pairViews),
"successful": success,
"failed": failed,
}).Info("payloads imported")
return importResult
}
return importResult
}