/
mock_service.go
217 lines (189 loc) · 6.33 KB
/
mock_service.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Code generated by zanzibar
// @generated
// Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package echogatewayservicegeneratedmock
import (
"context"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/uber/zanzibar/config"
zanzibar "github.com/uber/zanzibar/runtime"
service "github.com/uber/zanzibar/examples/example-gateway/build/services/echo-gateway"
)
// MockService interface
type MockService interface {
MakeHTTPRequest(
method string,
url string,
headers map[string]string,
body io.Reader,
) (*http.Response, error)
MakeTChannelRequest(
ctx context.Context,
thriftService string,
method string,
headers map[string]string,
req, resp zanzibar.RWTStruct,
timeoutAndRetryCfg *zanzibar.TimeoutAndRetryOptions,
) (bool, map[string]string, error)
MockClients() *MockClientNodes
Server() *zanzibar.Gateway
Start()
Stop()
}
type mockService struct {
started bool
server *zanzibar.Gateway
ctrl *gomock.Controller
mockClients *MockClientNodes
httpClient *http.Client
tChannelClient zanzibar.TChannelCaller
}
// MustCreateTestService creates a new MockService, panics if it fails doing so.
// Optional testConfigPaths specifies runtime config files used in tests, it
// should be paths that are relative to "$GOPATH/src".
// If testConfigPaths is absent, a default test config file is used.
// The default test config file is chosen base on existence in order below:
// - "../../config/test.yaml" where current dir is the dir of service-config.yaml for the mocked service
// - "config/test.yaml" where current dir is the project root
func MustCreateTestService(t *testing.T, testConfigPaths ...string) MockService {
if len(testConfigPaths) == 0 {
configPath := filepath.Join("src", "github.com/uber/zanzibar/examples/example-gateway/config/test.yaml")
defaultPath := filepath.Join(os.Getenv("GOPATH"), configPath)
// This is a temporary solution for running tests using bazel
// see https://docs.bazel.build/versions/master/test-encyclopedia.html for relevant env vars
// TODO: need long term solution to avoid hardcoding bazel specifics
bazelPath := filepath.Join(os.Getenv("TEST_SRCDIR"), os.Getenv("TEST_WORKSPACE"), configPath)
testConfigPaths = append(
testConfigPaths,
defaultPath,
bazelPath,
)
}
c := config.NewRuntimeConfigOrDie(testConfigPaths, nil)
server, err := zanzibar.CreateGateway(c, nil)
if err != nil {
panic(err)
}
ctrl := gomock.NewController(t)
_, dependencies, mockNodes := InitializeDependenciesMock(server, ctrl)
registerErr := service.RegisterDeps(server, dependencies)
if registerErr != nil {
panic(registerErr)
}
httpClient := &http.Client{
Transport: &http.Transport{
DisableKeepAlives: false,
MaxIdleConns: 500,
MaxIdleConnsPerHost: 500,
},
}
// TChannel clients must have a timeout defined, so defining a long timeout that should not realistically
// be hit in tests.
timeout := time.Duration(5) * time.Minute
timeoutPerAttempt := time.Duration(1) * time.Minute
tchannelClient := zanzibar.NewRawTChannelClient(
server.ServerTChannel,
server.ContextLogger,
server.RootScope,
&zanzibar.TChannelClientOption{
ServiceName: server.ServiceName,
ClientID: "TestClient",
Timeout: timeout,
TimeoutPerAttempt: timeoutPerAttempt,
},
)
return &mockService{
server: server,
ctrl: ctrl,
mockClients: mockNodes,
httpClient: httpClient,
tChannelClient: tchannelClient,
}
}
// Server returns the mock server
func (m *mockService) Server() *zanzibar.Gateway {
return m.server
}
// Start starts the mock server, panics if fails doing so
func (m *mockService) Start() {
if err := m.server.Bootstrap(); err != nil {
panic(err)
}
m.started = true
}
// Stop stops the mock server
func (m *mockService) Stop() {
// m.ctrl.Finish() calls runtime.Goexit() on errors
// put it in defer so cleanup is always done
defer func() {
m.server.Shutdown()
m.started = false
}()
m.ctrl.Finish()
}
// MockClients returns the mock clients
func (m *mockService) MockClients() *MockClientNodes {
return m.mockClients
}
// MakeHTTPRequest makes a HTTP request to the mock server
func (m *mockService) MakeHTTPRequest(
method string,
url string,
headers map[string]string,
body io.Reader,
) (*http.Response, error) {
if !m.started {
return nil, errors.New("mock server is not started")
}
client := m.httpClient
fullURL := "http://" + m.server.RealHTTPAddr + url
req, err := http.NewRequest(method, fullURL, body)
for headerName, headerValue := range headers {
req.Header.Set(headerName, headerValue)
}
if err != nil {
return nil, err
}
return client.Do(req)
}
// MakeTChannelRequest makes a TChannel request to the mock server
func (m *mockService) MakeTChannelRequest(
ctx context.Context,
thriftService string,
method string,
headers map[string]string,
req, res zanzibar.RWTStruct,
timeoutAndRetryCfg *zanzibar.TimeoutAndRetryOptions,
) (bool, map[string]string, error) {
if !m.started {
return false, nil, errors.New("mock server is not started")
}
sc := m.server.ServerTChannel.GetSubChannel(m.server.ServiceName)
sc.Peers().Add(m.server.RealTChannelAddr)
return m.tChannelClient.Call(ctx, thriftService, method, headers, req, res, timeoutAndRetryCfg)
}