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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
use crate::api::spec::{Then, When};
use crate::api::{LocalMockServerAdapter, MockServerAdapter, RemoteMockServerAdapter};
use crate::common::data::{MockDefinition, MockServerHttpResponse, RequestRequirements};
use crate::common::util::{read_env, with_retry, Join};
use crate::server::{start_server, MockServerState};
use crate::Mock;
use async_object_pool::Pool;
use std::cell::Cell;
use std::net::{SocketAddr, ToSocketAddrs};
use std::rc::Rc;
use std::sync::Arc;
use std::thread;
use tokio::task::LocalSet;
pub struct MockServer {
pub(crate) server_adapter: Option<Arc<dyn MockServerAdapter + Send + Sync>>,
pool: Arc<Pool<Arc<dyn MockServerAdapter + Send + Sync>>>,
}
impl MockServer {
async fn from(
server_adapter: Arc<dyn MockServerAdapter + Send + Sync>,
pool: Arc<Pool<Arc<dyn MockServerAdapter + Send + Sync>>>,
) -> Self {
with_retry(5, || server_adapter.ping())
.await
.expect("Cannot ping mock server.");
with_retry(5, || server_adapter.delete_all_mocks())
.await
.expect("Cannot reset mock server (task: delete mocks).");
with_retry(5, || server_adapter.delete_history())
.await
.expect("Cannot reset mock server (task: delete request history).");
Self {
server_adapter: Some(server_adapter),
pool,
}
}
pub async fn connect_async(address: &str) -> Self {
let addr = address
.to_socket_addrs()
.expect("Cannot parse address")
.find(|addr| addr.is_ipv4())
.expect("Not able to resolve the provided host name to an IPv4 address");
let adapter = REMOTE_SERVER_POOL_REF
.take_or_create(|| Arc::new(RemoteMockServerAdapter::new(addr)))
.await;
Self::from(adapter, REMOTE_SERVER_POOL_REF.clone()).await
}
pub fn connect(address: &str) -> Self {
Self::connect_async(address).join()
}
pub async fn connect_from_env_async() -> Self {
let host = read_env("HTTPMOCK_HOST", "127.0.0.1");
let port = read_env("HTTPMOCK_PORT", "5000")
.parse::<u16>()
.expect("Cannot parse environment variable HTTPMOCK_PORT to an integer");
Self::connect_async(&format!("{}:{}", host, port)).await
}
pub fn connect_from_env() -> Self {
Self::connect_from_env_async().join()
}
pub async fn start_async() -> Self {
let adapter = LOCAL_SERVER_POOL_REF
.take_or_create(LOCAL_SERVER_ADAPTER_GENERATOR)
.await;
Self::from(adapter, LOCAL_SERVER_POOL_REF.clone()).await
}
pub fn start() -> MockServer {
Self::start_async().join()
}
pub fn host(&self) -> String {
self.server_adapter.as_ref().unwrap().host()
}
pub fn port(&self) -> u16 {
self.server_adapter.as_ref().unwrap().port()
}
pub fn address(&self) -> &SocketAddr {
self.server_adapter.as_ref().unwrap().address()
}
pub fn url<S: Into<String>>(&self, path: S) -> String {
format!("http://{}{}", self.address(), path.into())
}
pub fn base_url(&self) -> String {
self.url("")
}
pub fn mock<F>(&self, config_fn: F) -> Mock
where
F: FnOnce(When, Then),
{
self.mock_async(config_fn).join()
}
pub async fn mock_async<'a, F>(&'a self, spec_fn: F) -> Mock<'a>
where
F: FnOnce(When, Then),
{
let mut req = Rc::new(Cell::new(RequestRequirements::new()));
let mut res = Rc::new(Cell::new(MockServerHttpResponse::new()));
spec_fn(
When {
expectations: req.clone(),
},
Then {
response_template: res.clone(),
},
);
let response = self
.server_adapter
.as_ref()
.unwrap()
.create_mock(&MockDefinition {
request: req.take(),
response: res.take(),
})
.await
.expect("Cannot deserialize mock server response");
Mock {
id: response.mock_id,
server: self,
}
}
}
impl Drop for MockServer {
fn drop(&mut self) {
let adapter = self.server_adapter.take().unwrap();
self.pool.put(adapter).join();
}
}
const LOCAL_SERVER_ADAPTER_GENERATOR: fn() -> Arc<dyn MockServerAdapter + Send + Sync> = || {
let (addr_sender, addr_receiver) = tokio::sync::oneshot::channel::<SocketAddr>();
let state = Arc::new(MockServerState::default());
let server_state = state.clone();
thread::spawn(move || {
let server_state = server_state.clone();
let srv = start_server(0, false, &server_state, Some(addr_sender), false);
let mut runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("Cannot build local tokio runtime");
LocalSet::new().block_on(&mut runtime, srv)
});
let addr = addr_receiver.join().expect("Cannot get server address");
Arc::new(LocalMockServerAdapter::new(addr, state))
};
lazy_static! {
static ref LOCAL_SERVER_POOL_REF: Arc<Pool<Arc<dyn MockServerAdapter + Send + Sync>>> = {
let max_servers = read_env("HTTPMOCK_MAX_SERVERS", "25")
.parse::<usize>()
.expect("Cannot parse environment variable HTTPMOCK_MAX_SERVERS to an integer");
Arc::new(Pool::new(max_servers))
};
static ref REMOTE_SERVER_POOL_REF: Arc<Pool<Arc<dyn MockServerAdapter + Send + Sync>>> =
Arc::new(Pool::new(1));
}