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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use crate::respond::Respond;
use crate::{MockServer, Request, ResponseTemplate};
use std::fmt::{Debug, Formatter};
use std::ops::{
    Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
};

/// Anything that implements `Match` can be used to constrain when a [`Mock`] is activated.
///
/// `Match` can be used to extend the set of matchers provided out-of-the-box by `wiremock` to
/// cater to your specific testing needs:
/// ```rust
/// use wiremock::{Match, MockServer, Mock, Request, ResponseTemplate};
/// use wiremock::matchers::HeaderExactMatcher;
/// use std::convert::TryInto;
///
/// // Check that a header with the specified name exists and its value has an odd length.
/// pub struct OddHeaderMatcher(http_types::headers::HeaderName);
///
/// impl Match for OddHeaderMatcher {
///     fn matches(&self, request: &Request) -> bool {
///         match request.headers.get(&self.0) {
///             // We are ignoring multi-valued headers for simplicity
///             Some(values) => values[0].as_str().len() % 2 == 1,
///             None => false
///         }
///     }
/// }
///
/// #[async_std::main]
/// async fn main() {
///     // Arrange
///     let mock_server = MockServer::start().await;
///
///     Mock::given(OddHeaderMatcher("custom".try_into().unwrap()))
///         .respond_with(ResponseTemplate::new(200))
///         .mount(&mock_server)
///         .await;
///     
///     // Even length
///     let status = surf::get(&mock_server.uri())
///         .header("custom", "even")
///         .await
///         .unwrap()
///         .status();
///     assert_eq!(status, 404);
///
///     // Odd length
///     let status = surf::get(&mock_server.uri())
///         .header("custom", "odd")
///         .await
///         .unwrap()
///         .status();
///     assert_eq!(status, 200);
/// }
/// ```
///
/// Anonymous functions that take a reference to a [`Request`] as input and return a boolean
/// as output automatically implement the `Match` trait.
///
/// The previous example could be rewritten as follows:
/// ```rust
/// use wiremock::{Match, MockServer, Mock, Request, ResponseTemplate};
/// use wiremock::matchers::HeaderExactMatcher;
/// use std::convert::TryInto;
///
/// #[async_std::main]
/// async fn main() {
///     // Arrange
///     let mock_server = MockServer::start().await;
///     
///     let header_name: http_types::headers::HeaderName = "custom".try_into().unwrap();
///     // Check that a header with the specified name exists and its value has an odd length.
///     let matcher = move |request: &Request| {
///         match request.headers.get(&header_name) {
///             Some(values) => values[0].as_str().len() % 2 == 1,
///             None => false
///         }
///     };
///
///     Mock::given(matcher)
///         .respond_with(ResponseTemplate::new(200))
///         .mount(&mock_server)
///         .await;
///     
///     // Even length
///     let status = surf::get(&mock_server.uri())
///         .header("custom", "even")
///         .await
///         .unwrap()
///         .status();
///     assert_eq!(status, 404);
///
///     // Odd length
///     let status = surf::get(&mock_server.uri())
///         .header("custom", "odd")
///         .await
///         .unwrap()
///         .status();
///     assert_eq!(status, 200);
/// }
/// ```
pub trait Match: Send + Sync {
    /// Given a reference to a `Request`, determine if it should match or not given
    /// a specific criterion.
    fn matches(&self, request: &Request) -> bool;
}

/// Wrapper around a `Match` trait object.
///
/// We need the wrapper to provide a (fake) implementation of `Debug`,
/// thus allowing us to pass this struct around as a `bastion` message.
/// This is because Rust's closures do not implement `Debug`.
///
/// We wouldn't need this if `bastion` didn't require `Debug` as a trait bound for its Message trait
/// or if Rust automatically implemented `Debug` for closures.
pub(crate) struct Matcher(Box<dyn Match>);

impl Match for Matcher {
    fn matches(&self, request: &Request) -> bool {
        self.0.matches(request)
    }
}

impl Debug for Matcher {
    fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
        // Dummy `Debug` implementation to allow us to pass `Matcher` as a message in `bastion`.
        // It's needed because closures do not implement `Debug` and we really want to enable
        // closures as matchers from an API perspective.
        // Might re-think this in the future.
        Ok(())
    }
}

/// Given a set of matchers, a `Mock` instructs an instance of [`MockServer`] to return a pre-determined response if the matching conditions are satisfied.
///
/// `Mock`s have to be mounted (or registered) with a [`MockServer`] to become effective.
///
/// ### Example (using [`register`]):
/// ```rust
/// use wiremock::{MockServer, Mock, ResponseTemplate};
/// use wiremock::matchers::method;
///
/// #[async_std::main]
/// async fn main() {
///     // Arrange
///     let mock_server = MockServer::start().await;
///
///     let response = ResponseTemplate::new(200);
///
///     let mock = Mock::given(method("GET")).respond_with(response.clone());
///     // Registering the mock with the mock server - it's now effective!
///     mock_server.register(mock).await;
///
///     // We won't register this mock instead.
///     let unregistered_mock = Mock::given(method("GET")).respond_with(response);
///     
///     // Act
///     let status = surf::get(&mock_server.uri())
///         .await
///         .unwrap()
///         .status();
///     assert_eq!(status, 200);
///
///     // This would have matched `unregistered_mock`, but we haven't registered it!
///     // Hence it returns a 404, the default response when no mocks matched on the mock server.
///     let status = surf::post(&mock_server.uri())
///         .await
///         .unwrap()
///         .status();
///     assert_eq!(status, 404);
/// }
/// ```
///
/// ### Example (using [`mount`]):
///
/// If you prefer a fluent style, you can use the [`mount`] method on the `Mock` itself
/// instead of [`register`].
/// ```rust
/// use wiremock::{MockServer, Mock, ResponseTemplate};
/// use wiremock::matchers::method;
///
/// #[async_std::main]
/// async fn main() {
///     // Arrange
///     let mock_server = MockServer::start().await;
///
///     Mock::given(method("GET"))
///         .respond_with(ResponseTemplate::new(200))
///         .up_to_n_times(1)
///         // Mounting the mock on the mock server - it's now effective!
///         .mount(&mock_server)
///         .await;
///     
///     // Act
///     let status = surf::get(&mock_server.uri())
///         .await
///         .unwrap()
///         .status();
///     assert_eq!(status, 200);
/// }
/// ```
///
/// Both `register` and `mount` are asynchronous methods - don't forget to `.await` them!
///
/// [`register`]: MockServer::register
/// [`mount`]: Mock::mount
pub struct Mock {
    pub(crate) matchers: Vec<Matcher>,
    pub(crate) response: Box<dyn Respond>,
    /// Maximum number of times (inclusive) we should return a response from this Mock on
    /// matching requests.
    /// If `None`, there is no cap and we will respond to all incoming matching requests.
    /// If `Some(max_n_matches)`, when `max_n_matches` matching incoming requests have been processed,
    /// [`crate::active_mock::ActiveMock::matches`] should start returning `false`, regardless of the incoming request.
    pub(crate) max_n_matches: Option<u64>,
    /// The friendly mock name specified by the user.  
    /// Used in diagnostics and error messages if the mock expectations are not satisfied.
    pub(crate) name: Option<String>,
    /// The expectation is satisfied if the number of incoming requests falls within `expectation_range`.
    pub(crate) expectation_range: Times,
}

/// A fluent builder to construct a [`Mock`] instance given matchers and a [`ResponseTemplate`].
#[derive(Debug)]
pub struct MockBuilder {
    pub(crate) matchers: Vec<Matcher>,
}

impl Mock {
    /// Start building a `Mock` specifying the first matcher.
    ///
    /// It returns an instance of [`MockBuilder`].
    pub fn given<M: 'static + Match>(matcher: M) -> MockBuilder {
        MockBuilder {
            matchers: vec![Matcher(Box::new(matcher))],
        }
    }

    /// Specify an upper limit to the number of times you would like this `Mock` to respond to
    /// incoming requests that satisfy the conditions imposed by your [`matchers`].
    ///
    /// ### Example:
    ///
    /// ```rust
    /// use wiremock::{MockServer, Mock, ResponseTemplate};
    /// use wiremock::matchers::method;
    ///
    /// #[async_std::main]
    /// async fn main() {
    ///     // Arrange
    ///     let mock_server = MockServer::start().await;
    ///
    ///     Mock::given(method("GET"))
    ///         .respond_with(ResponseTemplate::new(200))
    ///         // Default behaviour will have this Mock responding to any incoming request
    ///         // that satisfied our matcher (e.g. being a GET request).
    ///         // We can opt out of the default behaviour by setting a cap on the number of
    ///         // matching requests this Mock should respond to.
    ///         //
    ///         // In this case, once one matching request has been received, the mock will stop
    ///         // matching additional requests and you will receive a 404 if no other mock
    ///         // matches on those requests.
    ///         .up_to_n_times(1)
    ///         .mount(&mock_server)
    ///         .await;
    ///     
    ///     // Act
    ///
    ///     // The first request matches, as expected.
    ///     let status = surf::get(&mock_server.uri())
    ///         .await
    ///         .unwrap()
    ///         .status();
    ///     assert_eq!(status, 200);
    ///
    ///     // The second request does NOT match given our `up_to_n_times(1)` setting.
    ///     let status = surf::get(&mock_server.uri())
    ///         .await
    ///         .unwrap()
    ///         .status();
    ///     assert_eq!(status, 404);
    /// }
    /// ```
    ///
    /// [`matchers`]: crate::matchers
    pub fn up_to_n_times(mut self, n: u64) -> Mock {
        assert!(n > 0, "n must be strictly greater than 0!");
        self.max_n_matches = Some(n);
        self
    }

    /// Set an expectation on the number of times this `Mock` should match in the current
    /// test case.
    /// Expectations are verified when the [`MockServer`] is shutting down: if the expectation
    /// is not satisfied, the [`MockServer`] will panic and the `error_message` is shown.
    ///
    /// By default, no expectation is set for `Mock`s.
    ///
    /// ### When is this useful?
    ///
    /// `expect` can turn out handy when you'd like to verify that a certain side-effect has
    /// (or has not!) taken place.
    ///
    /// For example:
    /// - check that a 3rd party notification API (e.g. email service) is called when an event
    ///   in your application is supposed to trigger a notification;
    /// - check that a 3rd party API is NOT called when the response of a call is expected
    ///   to be retrieved from a cache (`.expect(0)`).
    ///
    /// This technique is also called [spying](https://martinfowler.com/bliki/TestDouble.html).
    ///
    /// ### Example:
    ///
    /// ```rust
    /// use wiremock::{MockServer, Mock, ResponseTemplate};
    /// use wiremock::matchers::method;
    ///
    /// #[async_std::main]
    /// async fn main() {
    ///     // Arrange
    ///     let mock_server = MockServer::start().await;
    ///
    ///     Mock::given(method("GET"))
    ///         .respond_with(ResponseTemplate::new(200))
    ///         .up_to_n_times(2)
    ///         // We expect the mock to be called at least once.
    ///         // If that does not happen, the `MockServer` will panic on shutdown,
    ///         // causing the whole test to fail.
    ///         .expect(1..)
    ///         // We assign a name to the mock - it will be shown in error messages
    ///         // if our expectation is not verified!
    ///         .named("Root GET")
    ///         .mount(&mock_server)
    ///         .await;
    ///     
    ///     // Act
    ///     let status = surf::get(&mock_server.uri())
    ///         .await
    ///         .unwrap()
    ///         .status();
    ///     assert_eq!(status, 200);
    ///
    ///     // Assert
    ///     // We made at least one matching request, the expectation is satisfied.
    ///     // The `MockServer` will shutdown peacefully, without panicking.
    /// }
    /// ```
    pub fn expect<T: Into<Times>>(mut self, r: T) -> Self {
        let range = r.into();
        self.expectation_range = range;

        self
    }

    /// Assign a name to your mock.  
    ///
    /// The mock name will be used in error messages (e.g. if the mock expectation
    /// is not satisfied) and debug logs to help you identify what failed.
    ///
    /// ### Example:
    ///
    /// ```should_panic
    /// use wiremock::{MockServer, Mock, ResponseTemplate};
    /// use wiremock::matchers::method;
    ///
    /// #[async_std::main]
    /// async fn main() {
    ///     // Arrange
    ///     let mock_server = MockServer::start().await;
    ///
    ///     // We have two mocks in the same test - how do we find out
    ///     // which one failed when the test panics?
    ///     // Assigning a name to each mock with `named` gives us better error
    ///     // messages and makes it much easier to debug why a test is failing!
    ///     Mock::given(method("GET"))
    ///         .respond_with(ResponseTemplate::new(200))
    ///         .up_to_n_times(2)
    ///         .expect(1..)
    ///         // We assign a name to the mock - it will be shown in error messages
    ///         // if our expectation is not verified!
    ///         .named("Root GET")
    ///         .mount(&mock_server)
    ///         .await;
    ///
    ///     Mock::given(method("POST"))
    ///         .respond_with(ResponseTemplate::new(200))
    ///         .up_to_n_times(2)
    ///         .expect(1..)
    ///         // We assign a name to the mock - it will be shown in error messages
    ///         // if our expectation is not verified!
    ///         .named("Root POST")
    ///         .mount(&mock_server)
    ///         .await;
    ///     
    ///     // Act
    ///     let status = surf::get(&mock_server.uri())
    ///         .await
    ///         .unwrap()
    ///         .status();
    ///     assert_eq!(status, 200);
    ///
    ///     // Assert
    ///     // We did not make a POST request, therefore the expectation on `Root POST`
    ///     // is not satisfied and the test will panic.
    /// }
    /// ```
    pub fn named<T: Into<String>>(mut self, mock_name: T) -> Self {
        self.name = Some(mock_name.into());
        self
    }

    /// Mount a `Mock` on an instance of [`MockServer`].
    ///
    /// Be careful! `Mock`s are not effective until they are [`mount`]ed or [`register`]ed on a [`MockServer`].
    ///
    /// [`mount`] is an asynchronous method, make sure to `.await` it!
    ///
    /// [`register`]: MockServer::register
    /// [`mount`]: Mock::mount
    pub async fn mount(self, server: &MockServer) {
        server.register(self).await;
    }

    /// Given a [`Request`](crate::Request) build an instance a [`ResponseTemplate`] using
    /// the responder associated with the `Mock`.
    pub(crate) fn response_template(&self, request: &Request) -> ResponseTemplate {
        self.response.respond(request)
    }
}

impl MockBuilder {
    /// Add another request matcher to the mock you are building.
    ///
    /// **All** specified [`matchers`] must match for the overall [`Mock`] to match an incoming request.
    ///
    /// [`matchers`]: crate::matchers
    pub fn and<M: Match + 'static>(mut self, matcher: M) -> Self {
        self.matchers.push(Matcher(Box::new(matcher)));
        self
    }

    /// Establish what [`ResponseTemplate`] should be used to generate a response when an incoming
    /// request matches.
    ///
    /// `respond_with` finalises the `MockBuilder` and returns you a [`Mock`] instance, ready to
    /// be [`register`]ed or [`mount`]ed on a [`MockServer`]!
    ///
    /// [`register`]: MockServer::register
    /// [`mount`]: Mock::mount
    pub fn respond_with<R: Respond + 'static>(self, responder: R) -> Mock {
        Mock {
            matchers: self.matchers,
            response: Box::new(responder),
            max_n_matches: None,
            name: None,
            expectation_range: Times(TimesEnum::Unbounded(RangeFull)),
        }
    }
}

/// Specify how many times we expect a [`Mock`] to match via [`expect`].
/// It is used to set expectations on the usage of a [`Mock`] in a test case.
///
/// You can either specify an exact value, e.g.
/// ```rust
/// use wiremock::Times;
///
/// let times: Times = 10.into();
/// ```
/// or a range
/// ```rust
/// use wiremock::Times;
///
/// // Between 10 and 15 (not included) times
/// let times: Times = (10..15).into();
/// // Between 10 and 15 (included) times
/// let times: Times = (10..=15).into();
/// // At least 10 times
/// let times: Times = (10..).into();
/// // Strictly less than 15 times
/// let times: Times = (..15).into();
/// // Strictly less than 16 times
/// let times: Times = (..=15).into();
/// ```
///
/// [`expect`]: Mock::expect
#[derive(Clone, Debug)]
pub struct Times(TimesEnum);

impl Times {
    pub(crate) fn contains(&self, n_calls: u64) -> bool {
        match &self.0 {
            TimesEnum::Exact(e) => e == &n_calls,
            TimesEnum::Unbounded(r) => r.contains(&n_calls),
            TimesEnum::Range(r) => r.contains(&n_calls),
            TimesEnum::RangeFrom(r) => r.contains(&n_calls),
            TimesEnum::RangeTo(r) => r.contains(&n_calls),
            TimesEnum::RangeToInclusive(r) => r.contains(&n_calls),
            TimesEnum::RangeInclusive(r) => r.contains(&n_calls),
        }
    }
}

impl std::fmt::Display for Times {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            TimesEnum::Exact(e) => write!(f, "== {}", e),
            TimesEnum::Unbounded(_) => write!(f, "0 <= x"),
            TimesEnum::Range(r) => write!(f, "{} <= x < {}", r.start, r.end),
            TimesEnum::RangeFrom(r) => write!(f, "{} <= x", r.start),
            TimesEnum::RangeTo(r) => write!(f, "0 <= x < {}", r.end),
            TimesEnum::RangeToInclusive(r) => write!(f, "0 <= x <= {}", r.end),
            TimesEnum::RangeInclusive(r) => write!(f, "{} <= x <= {}", r.start(), r.end()),
        }
    }
}

// Implementation notes: this has gone through a couple of iterations before landing to
// what you see now.
//
// The original draft had Times itself as an enum with two variants (Exact and Range), with
// the Range variant generic over `R: RangeBounds<u64>`.
//
// We switched to a generic struct wrapper around a private `R: RangeBounds<u64>` when we realised
// that you would have had to specify a range type when creating the Exact variant
// (e.g. as you do for `Option` when creating a `None` variant).
//
// We achieved the same functionality with a struct wrapper, but exact values had to converted
// to ranges with a single element (e.g. 15 -> 15..16).
// Not the most expressive representation, but we would have lived with it.
//
// We changed once again when we started to update our `MockActor`: we are storing all `Mock`s
// in a vector. Being generic over `R`, the range type leaked into the overall `Mock` (and `ActiveMock`)
// type, thus making those generic as well over `R`.
// To store them in a vector all mocks would have had to use the same range internally, which is
// obviously an unreasonable restrictions.
// At the same time, we can't have a Box<dyn RangeBounds<u64>> because `contains` is a generic
// method hence the requirements for object safety are not satisfied.
//
// Thus we ended up creating this master enum that wraps all range variants with the addition
// of the Exact variant.
// If you can do better, please submit a PR.
// We keep them enum private to the crate to allow for future refactoring.
#[derive(Clone, Debug)]
pub(crate) enum TimesEnum {
    Exact(u64),
    Unbounded(RangeFull),
    Range(Range<u64>),
    RangeFrom(RangeFrom<u64>),
    RangeTo(RangeTo<u64>),
    RangeToInclusive(RangeToInclusive<u64>),
    RangeInclusive(RangeInclusive<u64>),
}

impl From<u64> for Times {
    fn from(x: u64) -> Self {
        Times(TimesEnum::Exact(x))
    }
}

// A quick macro to help easing the implementation pain.
macro_rules! impl_from_for_range {
    ($type_name:ident) => {
        impl From<$type_name<u64>> for Times {
            fn from(r: $type_name<u64>) -> Self {
                Times(TimesEnum::$type_name(r))
            }
        }
    };
}

impl_from_for_range!(Range);
impl_from_for_range!(RangeTo);
impl_from_for_range!(RangeFrom);
impl_from_for_range!(RangeInclusive);
impl_from_for_range!(RangeToInclusive);