-
Notifications
You must be signed in to change notification settings - Fork 20
/
mock.go
58 lines (49 loc) · 1.84 KB
/
mock.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
package rest
import (
"encoding/json"
)
// MockServerSource is a version of the server source which allows requests to be mocked for testing
type MockServerSource struct {
ServerSource
mockResponses map[string]json.RawMessage
mockedRequests []string
}
// NewMockServerSource creates a new mocked asset server for testing
func NewMockServerSource(cache *AssetCache) *MockServerSource {
s := &MockServerSource{
ServerSource: ServerSource{typeURLs: map[AssetType]string{
assetTypeChannel: "http://testserver/assets/channel/",
assetTypeField: "http://testserver/assets/field/",
assetTypeFlow: "http://testserver/assets/flow/",
assetTypeGroup: "http://testserver/assets/group/",
assetTypeLabel: "http://testserver/assets/label/",
assetTypeLocationHierarchy: "http://testserver/assets/location_hierarchy/",
assetTypeResthook: "http://testserver/assets/resthook/",
}, cache: cache},
mockResponses: map[string]json.RawMessage{},
mockedRequests: []string{},
}
s.ServerSource.fetcher = s
return s
}
// MockResponse creates a new mocked response for the given URL
func (s *MockServerSource) MockResponse(url string, response json.RawMessage) {
s.mockResponses[url] = response
}
// MockedRequests returns all mocked requests made so far
func (s *MockServerSource) MockedRequests() []string {
return s.mockedRequests
}
func (s *MockServerSource) fetchAsset(url string, itemType AssetType) ([]byte, error) {
s.mockedRequests = append(s.mockedRequests, url)
assetBuf, found := s.mockResponses[url]
if !found {
return []byte(`{"results":[]}`), nil
}
return assetBuf, nil
}
// MarshalJSON marshals this mock asset server into JSON
func (s *MockServerSource) MarshalJSON() ([]byte, error) {
envelope := &serverSourceEnvelope{TypeURLs: s.typeURLs}
return json.Marshal(envelope)
}