-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
data.rs
497 lines (435 loc) · 13.7 KB
/
data.rs
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
extern crate serde_regex;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fmt;
use std::fmt::Debug;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// A general abstraction of an HTTP request of `httpmock`.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HttpMockRequest {
pub path: String,
pub method: String,
pub headers: Option<Vec<(String, String)>>,
pub query_params: Option<Vec<(String, String)>>,
pub body: Option<Vec<u8>>,
}
impl HttpMockRequest {
pub fn new(method: String, path: String) -> Self {
Self {
path,
method,
headers: None,
query_params: None,
body: None,
}
}
pub fn with_headers(mut self, arg: Vec<(String, String)>) -> Self {
self.headers = Some(arg);
self
}
pub fn with_query_params(mut self, arg: Vec<(String, String)>) -> Self {
self.query_params = Some(arg);
self
}
pub fn with_body(mut self, arg: Vec<u8>) -> Self {
self.body = Some(arg);
self
}
}
/// A general abstraction of an HTTP response for all handlers.
#[derive(Serialize, Deserialize, Clone)]
pub struct MockServerHttpResponse {
pub status: Option<u16>,
pub headers: Option<Vec<(String, String)>>,
#[serde(default, with = "opt_vector_serde_base64")]
pub body: Option<Vec<u8>>,
pub delay: Option<Duration>,
}
impl MockServerHttpResponse {
pub fn new() -> Self {
Self {
status: None,
headers: None,
body: None,
delay: None,
}
}
}
impl Default for MockServerHttpResponse {
fn default() -> Self {
Self::new()
}
}
/// Serializes and deserializes the response body to/from a Base64 string.
mod opt_vector_serde_base64 {
use serde::{Deserialize, Deserializer, Serializer};
// See the following references:
// https://github.com/serde-rs/serde/blob/master/serde/src/ser/impls.rs#L99
// https://github.com/serde-rs/serde/issues/661
pub fn serialize<T, S>(bytes: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
where
T: AsRef<[u8]>,
S: Serializer,
{
match bytes {
Some(ref value) => serializer.serialize_bytes(base64::encode(value).as_bytes()),
None => serializer.serialize_none(),
}
}
// See the following references:
// https://github.com/serde-rs/serde/issues/1444
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct Wrapper(#[serde(deserialize_with = "from_base64")] Vec<u8>);
let v = Option::deserialize(deserializer)?;
Ok(v.map(|Wrapper(a)| a))
}
fn from_base64<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
D: Deserializer<'de>,
{
let vec = Vec::deserialize(deserializer)?;
base64::decode(vec).map_err(serde::de::Error::custom)
}
}
/// Prints the response body as UTF8 string
impl fmt::Debug for MockServerHttpResponse {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MockServerHttpResponse")
.field("status", &self.status)
.field("headers", &self.headers)
.field(
"body",
&self
.body
.as_ref()
.map(|x| String::from_utf8_lossy(x.as_ref()).to_string()),
)
.field("delay", &self.delay)
.finish()
}
}
/// A general abstraction of an HTTP request for all handlers.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Pattern {
#[serde(with = "serde_regex")]
pub regex: Regex,
}
impl Pattern {
pub fn from_regex(regex: Regex) -> Pattern {
Pattern { regex }
}
}
impl Ord for Pattern {
fn cmp(&self, other: &Self) -> Ordering {
self.regex.as_str().cmp(other.regex.as_str())
}
}
impl PartialOrd for Pattern {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Pattern {
fn eq(&self, other: &Self) -> bool {
self.regex.as_str() == other.regex.as_str()
}
}
impl Eq for Pattern {}
pub type MockMatcherFunction = fn(&HttpMockRequest) -> bool;
/// A general abstraction of an HTTP request for all handlers.
#[derive(Serialize, Deserialize, Clone)]
pub struct RequestRequirements {
pub path: Option<String>,
pub path_contains: Option<Vec<String>>,
pub path_matches: Option<Vec<Pattern>>,
pub method: Option<String>,
pub headers: Option<Vec<(String, String)>>,
pub header_exists: Option<Vec<String>>,
pub cookies: Option<Vec<(String, String)>>,
pub cookie_exists: Option<Vec<String>>,
pub body: Option<String>,
pub json_body: Option<Value>,
pub json_body_includes: Option<Vec<Value>>,
pub body_contains: Option<Vec<String>>,
pub body_matches: Option<Vec<Pattern>>,
pub query_param_exists: Option<Vec<String>>,
pub query_param: Option<Vec<(String, String)>>,
pub x_www_form_urlencoded_key_exists: Option<Vec<String>>,
pub x_www_form_urlencoded: Option<Vec<(String, String)>>,
#[serde(skip_serializing, skip_deserializing)]
pub matchers: Option<Vec<MockMatcherFunction>>,
}
impl Default for RequestRequirements {
fn default() -> Self {
Self::new()
}
}
impl RequestRequirements {
pub fn new() -> Self {
Self {
path: None,
path_contains: None,
path_matches: None,
method: None,
headers: None,
header_exists: None,
cookies: None,
cookie_exists: None,
body: None,
json_body: None,
json_body_includes: None,
body_contains: None,
body_matches: None,
query_param_exists: None,
query_param: None,
x_www_form_urlencoded: None,
x_www_form_urlencoded_key_exists: None,
matchers: None,
}
}
pub fn with_path(mut self, arg: String) -> Self {
self.path = Some(arg);
self
}
pub fn with_method(mut self, arg: String) -> Self {
self.method = Some(arg);
self
}
pub fn with_body(mut self, arg: String) -> Self {
self.body = Some(arg);
self
}
pub fn with_json_body(mut self, arg: Value) -> Self {
self.json_body = Some(arg);
self
}
pub fn with_path_contains(mut self, arg: Vec<String>) -> Self {
self.path_contains = Some(arg);
self
}
pub fn with_path_matches(mut self, arg: Vec<Pattern>) -> Self {
self.path_matches = Some(arg);
self
}
pub fn with_headers(mut self, arg: Vec<(String, String)>) -> Self {
self.headers = Some(arg);
self
}
pub fn with_header_exists(mut self, arg: Vec<String>) -> Self {
self.header_exists = Some(arg);
self
}
pub fn with_cookies(mut self, arg: Vec<(String, String)>) -> Self {
self.cookies = Some(arg);
self
}
pub fn with_cookie_exists(mut self, arg: Vec<String>) -> Self {
self.cookie_exists = Some(arg);
self
}
pub fn with_json_body_includes(mut self, arg: Vec<Value>) -> Self {
self.json_body_includes = Some(arg);
self
}
pub fn with_body_contains(mut self, arg: Vec<String>) -> Self {
self.body_contains = Some(arg);
self
}
pub fn with_body_matches(mut self, arg: Vec<Pattern>) -> Self {
self.body_matches = Some(arg);
self
}
pub fn with_query_param_exists(mut self, arg: Vec<String>) -> Self {
self.query_param_exists = Some(arg);
self
}
pub fn with_query_param(mut self, arg: Vec<(String, String)>) -> Self {
self.query_param = Some(arg);
self
}
}
/// A Request that is made to set a new mock.
#[derive(Serialize, Deserialize, Clone)]
pub struct MockDefinition {
pub request: RequestRequirements,
pub response: MockServerHttpResponse,
}
impl MockDefinition {
pub fn new(req: RequestRequirements, mock: MockServerHttpResponse) -> Self {
Self {
request: req,
response: mock,
}
}
}
#[derive(Serialize, Deserialize)]
pub struct MockRef {
pub mock_id: usize,
}
impl MockRef {
pub fn new(mock_id: usize) -> Self {
Self { mock_id }
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct ActiveMock {
pub id: usize,
pub call_counter: usize,
pub definition: MockDefinition,
pub is_static: bool,
}
impl ActiveMock {
pub fn new(id: usize, mock_definition: MockDefinition, is_static: bool) -> Self {
ActiveMock {
id,
definition: mock_definition,
call_counter: 0,
is_static,
}
}
}
#[derive(Serialize, Deserialize)]
pub struct ClosestMatch {
pub request: HttpMockRequest,
pub request_index: usize,
pub mismatches: Vec<Mismatch>,
}
#[derive(Serialize, Deserialize)]
pub struct ErrorResponse {
pub message: String,
}
impl ErrorResponse {
pub fn new<T>(message: &T) -> ErrorResponse
where
T: ToString,
{
ErrorResponse {
message: message.to_string(),
}
}
}
// *************************************************************************************************
// Diff and Change correspond to difference::Changeset and Difference structs. They are duplicated
// here only for the reason to make them serializable/deserializable using serde.
// *************************************************************************************************
#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub enum Diff {
Same(String),
Add(String),
Rem(String),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DiffResult {
pub differences: Vec<Diff>,
pub distance: f32,
pub tokenizer: Tokenizer,
}
#[derive(PartialEq, Debug, Serialize, Deserialize, Clone, Copy)]
pub enum Tokenizer {
Line,
Word,
Character,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Reason {
pub expected: String,
pub actual: String,
pub comparison: String,
pub best_match: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Mismatch {
pub title: String,
pub reason: Option<Reason>,
pub diff: Option<DiffResult>,
}
#[cfg(test)]
mod test {
use std::collections::BTreeMap;
use regex::Regex;
use serde_json::json;
use crate::common::data::{Pattern, RequestRequirements};
/// This test makes sure that adding the matching rules to a mock fills the struct as expected.
#[test]
fn fill_mock_requirements() {
// Arrange
let with_path = "with_path";
let with_path_contains = vec!["with_path_contains".into()];
let with_path_matches = vec![Pattern::from_regex(
Regex::new(r#"with_path_matches"#).unwrap(),
)];
let mut with_headers = Vec::new();
with_headers.push(("test".into(), "value".into()));
let with_method = "GET";
let with_body = "with_body";
let with_body_contains = vec!["body_contains".into()];
let with_body_matches = vec![Pattern::from_regex(
Regex::new(r#"with_body_matches"#).unwrap(),
)];
let with_json_body = json!(12.5);
let with_json_body_includes = vec![json!(12.5)];
let with_query_param_exists = vec!["with_query_param_exists".into()];
let mut with_query_param = Vec::new();
with_query_param.push(("with_query_param".into(), "value".into()));
let with_header_exists = vec!["with_header_exists".into()];
// Act
let rr = RequestRequirements::new()
.with_path(with_path.clone().into())
.with_path_contains(with_path_contains.clone())
.with_path_matches(with_path_matches.clone())
.with_headers(with_headers.clone())
.with_method(with_method.clone().into())
.with_body(with_body.clone().into())
.with_body_contains(with_body_contains.clone())
.with_body_matches(with_body_matches.clone())
.with_json_body(with_json_body.clone())
.with_json_body_includes(with_json_body_includes.clone())
.with_query_param_exists(with_query_param_exists.clone())
.with_query_param(with_query_param.clone())
.with_header_exists(with_header_exists.clone());
// Assert
assert_eq!(rr.path.as_ref().unwrap(), with_path.clone());
assert_eq!(
rr.path_contains.as_ref().unwrap(),
&with_path_contains.clone()
);
assert_eq!(
rr.path_matches.as_ref().unwrap(),
&with_path_matches.clone()
);
assert_eq!(rr.headers.as_ref().unwrap(), &with_headers.clone());
assert_eq!(rr.body.as_ref().unwrap(), with_body.clone());
assert_eq!(
rr.body_contains.as_ref().unwrap(),
&with_body_contains.clone()
);
assert_eq!(
rr.body_matches.as_ref().unwrap(),
&with_body_matches.clone()
);
assert_eq!(rr.json_body.as_ref().unwrap(), &with_json_body.clone());
assert_eq!(
rr.json_body_includes.as_ref().unwrap(),
&with_json_body_includes.clone()
);
assert_eq!(
rr.query_param_exists.as_ref().unwrap(),
&with_query_param_exists.clone()
);
assert_eq!(rr.query_param.as_ref().unwrap(), &with_query_param.clone());
assert_eq!(
rr.header_exists.as_ref().unwrap(),
&with_header_exists.clone()
);
}
}