zebra_test/mock_service.rs
1//! Some helpers to make it simpler to mock Tower services.
2//!
3//! A [`MockService`] is a generic [`tower::Service`] implementation that allows intercepting
4//! requests, responding to them individually, and checking that there are no requests to be
5//! received (at least during a period of time). The [`MockService`] can be built for proptests or
6//! for normal Rust unit tests.
7//!
8//! # Example
9//!
10//! ```
11//! use zebra_test::mock_service::MockService;
12//! # use tower::ServiceExt;
13//!
14//! # let reactor = tokio::runtime::Builder::new_current_thread()
15//! # .enable_all()
16//! # .build()
17//! # .expect("Failed to build Tokio runtime");
18//! #
19//! # reactor.block_on(async {
20//! let mut mock_service = MockService::build().for_unit_tests();
21//! let mut service = mock_service.clone();
22//! #
23//! # // Add types to satisfy the compiler's type inference for the `Error` type.
24//! # let _typed_mock_service: MockService<_, _, _> = mock_service.clone();
25//!
26//! let call = tokio::spawn(mock_service.clone().oneshot("hello"));
27//!
28//! mock_service
29//! .expect_request("hello").await
30//! .respond("hi!");
31//!
32//! mock_service.expect_no_requests().await;
33//!
34//! let response = call
35//! .await
36//! .expect("Failed to run call on the background")
37//! .expect("Failed to receive response from service");
38//!
39//! assert_eq!(response, "hi!");
40//! # });
41//! ```
42
43use std::{
44 fmt::Debug,
45 marker::PhantomData,
46 sync::{
47 atomic::{AtomicUsize, Ordering},
48 Arc,
49 },
50 task::{Context, Poll},
51 time::Duration,
52};
53
54use futures::{future::BoxFuture, FutureExt};
55use proptest::prelude::*;
56use tokio::{
57 sync::{
58 broadcast::{self, error::RecvError},
59 oneshot, Mutex,
60 },
61 time::timeout,
62};
63use tower::{BoxError, Service};
64
65/// The default size of the channel that forwards received requests.
66///
67/// If requests are received faster than the test code can consume them, reading from the lagged
68/// receiver panics rather than silently ignoring requests.
69///
70/// This value can be configured in the [`MockService`] using
71/// [`MockServiceBuilder::with_proxy_channel_size`].
72const DEFAULT_PROXY_CHANNEL_SIZE: usize = 100;
73
74/// The default observation window for absence checks and optional request reads.
75///
76/// Positive expectations use a separate 10-second default so slow scheduling does not fail tests.
77/// Both deadlines can be overridden with [`MockServiceBuilder::with_max_request_delay`].
78///
79/// Note that if a test checks that no requests are received, each check has to wait for this
80/// amount of time, so this may affect the test execution time.
81///
82/// We've seen delays up to 67ms on busy Linux and macOS machines,
83/// and some other timeout failures even with a 150ms timeout.
84pub const DEFAULT_REQUEST_OBSERVATION_TIMEOUT: Duration = Duration::from_millis(300);
85
86/// Maximum wait for positive expectations, which only costs time when a request is missing.
87const DEFAULT_EXPECTED_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
88
89/// An internal type representing the item that's sent in the [`broadcast`] channel.
90///
91/// The actual type that matters is the [`ResponseSender`] but since there could be more than one
92/// [`MockService`] verifying requests, the type must be wrapped so that it can be shared by all
93/// receivers:
94///
95/// - The [`Arc`] makes sure the instance is on the heap, and can be shared properly between
96/// threads and dropped when no longer needed.
97/// - The [`Mutex`] ensures only one [`MockService`] instance can reply to the received request.
98/// - The [`Option`] forces the [`MockService`] that handles the request to take ownership of it
99/// because sending a response also forces the [`ResponseSender`] to be dropped.
100type ProxyItem<Request, Response, Error> =
101 Arc<Mutex<Option<ResponseSender<Request, Response, Error>>>>;
102
103/// A service implementation that allows intercepting requests for checking them.
104///
105/// The type is generic over the request and response types, and also has an extra generic type
106/// parameter that's used as a tag to determine if the internal assertions should panic or return
107/// errors for proptest minimization. See [`AssertionType`] for more information.
108///
109/// The mock service can be cloned, and provides methods for checking the received requests as well
110/// as responding to them individually.
111///
112/// Internally, the instance that's operating as the service will forward requests to a
113/// [`broadcast`] channel that the other instances listen to.
114///
115/// See the [module-level documentation][`super::mock_service`] for an example.
116pub struct MockService<Request, Response, Assertion, Error = BoxError> {
117 receiver: broadcast::Receiver<ProxyItem<Request, Response, Error>>,
118 sender: broadcast::Sender<ProxyItem<Request, Response, Error>>,
119 poll_count: Arc<AtomicUsize>,
120 request_observation_timeout: Duration,
121 expected_request_timeout: Duration,
122 _assertion_type: PhantomData<Assertion>,
123}
124
125/// A builder type to create a [`MockService`].
126///
127/// Allows changing specific parameters used by the [`MockService`], if necessary. The default
128/// parameters should be reasonable for most cases.
129#[derive(Default)]
130pub struct MockServiceBuilder {
131 proxy_channel_size: Option<usize>,
132 max_request_delay: Option<Duration>,
133}
134
135/// A helper type for responding to incoming requests.
136///
137/// An instance of this type is created for each request received by the [`MockService`]. It
138/// contains the received request and a [`oneshot::Sender`] that can be used to respond to the
139/// request.
140///
141/// If dropped without sending a response, the channel is closed and the caller's response future
142/// panics when polled.
143#[must_use = "Tests may fail if a response is not sent back to the caller"]
144pub struct ResponseSender<Request, Response, Error> {
145 request: Request,
146 response_sender: oneshot::Sender<Result<Response, Error>>,
147}
148
149/// The [`tower::Service`] implementation of the [`MockService`].
150///
151/// The [`MockService`] is always ready, and it intercepts the requests wrapping them in a
152/// [`ResponseSender`] which can be used to send a response.
153impl<Request, Response, Assertion, Error> Service<Request>
154 for MockService<Request, Response, Assertion, Error>
155where
156 Request: Send + 'static,
157 Response: Send + 'static,
158 Error: Send + 'static,
159{
160 type Response = Response;
161 type Error = Error;
162 type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
163
164 fn poll_ready(&mut self, _context: &mut Context) -> Poll<Result<(), Self::Error>> {
165 self.poll_count.fetch_add(1, Ordering::SeqCst);
166 Poll::Ready(Ok(()))
167 }
168
169 fn call(&mut self, request: Request) -> Self::Future {
170 let (response_sender, response_receiver) = ResponseSender::new(request);
171 let proxy_item = Arc::new(Mutex::new(Some(response_sender)));
172
173 let _ = self.sender.send(proxy_item);
174
175 response_receiver
176 .map(|response| {
177 response.expect("A response was not sent by the `MockService` for a request")
178 })
179 .boxed()
180 }
181}
182
183/// An entry point for starting the [`MockServiceBuilder`].
184///
185/// This `impl` block exists for ergonomic reasons. The generic type parameters don't matter,
186/// because they are actually set by [`MockServiceBuilder::finish`].
187impl MockService<(), (), ()> {
188 /// Create a [`MockServiceBuilder`] to help with the creation of a [`MockService`].
189 pub fn build() -> MockServiceBuilder {
190 MockServiceBuilder::default()
191 }
192}
193
194impl MockServiceBuilder {
195 /// Configure the size of the proxy channel used for sending intercepted requests.
196 ///
197 /// This determines the maximum amount of requests that are kept in queue before the oldest
198 /// request is dropped. Reading from a lagged receiver panics, so tests must configure enough
199 /// capacity for all requests sent between expectations.
200 ///
201 /// The default value of 100 should be enough for most cases.
202 ///
203 /// # Example
204 ///
205 /// ```
206 /// # use zebra_test::mock_service::MockService;
207 /// #
208 /// let mock_service = MockService::build()
209 /// .with_proxy_channel_size(100)
210 /// .for_prop_tests();
211 /// #
212 /// # // Add types to satisfy the compiler's type inference.
213 /// # let typed_mock_service: MockService<(), (), _> = mock_service;
214 /// ```
215 pub fn with_proxy_channel_size(mut self, size: usize) -> Self {
216 self.proxy_channel_size = Some(size);
217 self
218 }
219
220 /// Configure the maximum wait for both positive expectations and absence checks.
221 ///
222 /// Without an override, positive expectations (`expect_request` and `expect_request_that`)
223 /// wait up to 10 seconds, while absence checks (`expect_no_requests`) and optional reads
224 /// (`try_next_request`) wait up to 300 ms. Setting this value overrides both deadlines,
225 /// including on clones.
226 ///
227 /// # Example
228 ///
229 /// ```
230 /// # use std::time::Duration;
231 /// #
232 /// # use zebra_test::mock_service::MockService;
233 /// #
234 /// let mock_service = MockService::build()
235 /// .with_max_request_delay(Duration::from_millis(25))
236 /// .for_unit_tests();
237 /// #
238 /// # // Add types to satisfy the compiler's type inference.
239 /// # let typed_mock_service: MockService<(), (), _> = mock_service;
240 /// ```
241 pub fn with_max_request_delay(mut self, max_request_delay: Duration) -> Self {
242 self.max_request_delay = Some(max_request_delay);
243 self
244 }
245
246 /// Create a [`MockService`] to be used in [`mod@proptest`]s.
247 ///
248 /// The assertions performed by [`MockService`] use the macros provided by [`mod@proptest`], like
249 /// [`prop_assert`].
250 pub fn for_prop_tests<Request, Response, Error>(
251 self,
252 ) -> MockService<Request, Response, PropTestAssertion, Error> {
253 self.finish()
254 }
255
256 /// Create a [`MockService`] to be used in Rust unit tests.
257 ///
258 /// The assertions performed by [`MockService`] use the macros provided by default in Rust,
259 /// like [`assert`].
260 pub fn for_unit_tests<Request, Response, Error>(
261 self,
262 ) -> MockService<Request, Response, PanicAssertion, Error> {
263 self.finish()
264 }
265
266 /// An internal helper method to create the actual [`MockService`].
267 ///
268 /// Note that this is used by both [`Self::for_prop_tests`] and [`Self::for_unit_tests`], the
269 /// only difference being the `Assertion` generic type parameter, which Rust infers
270 /// automatically.
271 pub fn finish<Request, Response, Assertion, Error>(
272 self,
273 ) -> MockService<Request, Response, Assertion, Error> {
274 let proxy_channel_size = self
275 .proxy_channel_size
276 .unwrap_or(DEFAULT_PROXY_CHANNEL_SIZE);
277 let (sender, receiver) = broadcast::channel(proxy_channel_size);
278
279 MockService {
280 receiver,
281 sender,
282 poll_count: Arc::new(AtomicUsize::new(0)),
283 request_observation_timeout: self
284 .max_request_delay
285 .unwrap_or(DEFAULT_REQUEST_OBSERVATION_TIMEOUT),
286 expected_request_timeout: self
287 .max_request_delay
288 .unwrap_or(DEFAULT_EXPECTED_REQUEST_TIMEOUT),
289 _assertion_type: PhantomData,
290 }
291 }
292}
293
294/// Implementation of [`MockService`] methods that use standard Rust panicking assertions.
295impl<Request, Response, Error> MockService<Request, Response, PanicAssertion, Error> {
296 /// Expect a specific request to be received.
297 ///
298 /// The expected request should be the next one in the internal queue, or if the queue is
299 /// empty, it should be received in at most the max delay time configured by
300 /// [`MockServiceBuilder::with_max_request_delay`].
301 ///
302 /// If the received request matches the expected request, a [`ResponseSender`] is returned
303 /// which can be used to inspect the request and respond to it. If dropped without responding,
304 /// the caller's response future panics when polled.
305 ///
306 /// # Panics
307 ///
308 /// If no request is received or if a request is received that's not equal to the expected
309 /// request, this method panics.
310 ///
311 /// # Example
312 ///
313 /// ```
314 /// # use zebra_test::mock_service::MockService;
315 /// # use tower::ServiceExt;
316 /// #
317 /// # let reactor = tokio::runtime::Builder::new_current_thread()
318 /// # .enable_all()
319 /// # .build()
320 /// # .expect("Failed to build Tokio runtime");
321 /// #
322 /// # reactor.block_on(async {
323 /// # let mut mock_service: MockService<_, _, _> = MockService::build().for_unit_tests();
324 /// # let mut service = mock_service.clone();
325 /// #
326 /// let call = tokio::spawn(mock_service.clone().oneshot("request"));
327 ///
328 /// mock_service.expect_request("request").await.respond("response");
329 ///
330 /// assert!(matches!(call.await, Ok(Ok("response"))));
331 /// # });
332 /// ```
333 pub async fn expect_request(
334 &mut self,
335 expected: Request,
336 ) -> ResponseSender<Request, Response, Error>
337 where
338 Request: PartialEq + Debug,
339 {
340 let response_sender = self.next_request().await;
341
342 assert_eq!(
343 response_sender.request,
344 expected,
345 "received an unexpected request\n \
346 in {}",
347 std::any::type_name::<Self>(),
348 );
349
350 response_sender
351 }
352
353 /// Expect a request to be received that matches a specified condition.
354 ///
355 /// There should be a request already in the internal queue, or a request should be received in
356 /// at most the max delay time configured by [`MockServiceBuilder::with_max_request_delay`].
357 ///
358 /// The received request is passed to the `condition` function, which should return `true` if
359 /// it matches the expected condition or `false` otherwise. If `true` is returned, a
360 /// [`ResponseSender`] is returned which can be used to inspect the request again and respond
361 /// to it. If dropped without responding, the caller's response future panics when polled.
362 ///
363 /// # Panics
364 ///
365 /// If the `condition` function returns `false`, this method panics.
366 ///
367 /// # Example
368 ///
369 /// ```
370 /// # use zebra_test::mock_service::MockService;
371 /// # use tower::ServiceExt;
372 /// #
373 /// # let reactor = tokio::runtime::Builder::new_current_thread()
374 /// # .enable_all()
375 /// # .build()
376 /// # .expect("Failed to build Tokio runtime");
377 /// #
378 /// # reactor.block_on(async {
379 /// # let mut mock_service: MockService<_, _, _> = MockService::build().for_unit_tests();
380 /// # let mut service = mock_service.clone();
381 /// #
382 /// let call = tokio::spawn(mock_service.clone().oneshot(1));
383 ///
384 /// mock_service.expect_request_that(|request| *request > 0).await.respond("response");
385 ///
386 /// assert!(matches!(call.await, Ok(Ok("response"))));
387 /// # });
388 /// ```
389 pub async fn expect_request_that(
390 &mut self,
391 condition: impl FnOnce(&Request) -> bool,
392 ) -> ResponseSender<Request, Response, Error>
393 where
394 Request: Debug,
395 {
396 let response_sender = self.next_request().await;
397
398 assert!(
399 condition(&response_sender.request),
400 "condition was false for request: {:?},\n \
401 in {}",
402 response_sender.request,
403 std::any::type_name::<Self>(),
404 );
405
406 response_sender
407 }
408
409 /// Expect no requests to be received.
410 ///
411 /// The internal queue of received requests should be empty, and no new requests should arrive
412 /// for the max delay time configured by [`MockServiceBuilder::with_max_request_delay`].
413 ///
414 /// # Panics
415 ///
416 /// If the queue is not empty or if a request is received before the max request delay timeout
417 /// expires.
418 ///
419 /// # Example
420 ///
421 /// ```
422 /// # use zebra_test::mock_service::MockService;
423 /// # use tower::ServiceExt;
424 /// #
425 /// # let reactor = tokio::runtime::Builder::new_current_thread()
426 /// # .enable_all()
427 /// # .build()
428 /// # .expect("Failed to build Tokio runtime");
429 /// #
430 /// # reactor.block_on(async {
431 /// # let mut mock_service: MockService<(), (), _> = MockService::build().for_unit_tests();
432 /// #
433 /// mock_service.expect_no_requests().await;
434 /// # });
435 /// ```
436 pub async fn expect_no_requests(&mut self)
437 where
438 Request: Debug,
439 {
440 if let Some(response_sender) = self.try_next_request().await {
441 panic!(
442 "received an unexpected request: {:?},\n \
443 in {}",
444 response_sender.request,
445 std::any::type_name::<Self>(),
446 );
447 }
448 }
449
450 /// Returns the next request from the queue,
451 /// or panics if there are no requests before the positive expectation deadline.
452 ///
453 /// Returns the next request in the internal queue or waits at most the max delay time
454 /// configured by [`MockServiceBuilder::with_max_request_delay`] for a new request to be
455 /// received, and then returns that.
456 ///
457 /// # Panics
458 ///
459 /// If the queue is empty and a request is not received before the max request delay timeout
460 /// expires.
461 async fn next_request(&mut self) -> ResponseSender<Request, Response, Error> {
462 match self
463 .try_next_request_with_timeout(self.expected_request_timeout)
464 .await
465 {
466 Some(request) => request,
467 None => panic!(
468 "timeout while waiting for a request\n \
469 in {}",
470 std::any::type_name::<Self>(),
471 ),
472 }
473 }
474
475 /// Returns a count of the number of times this service has been polled.
476 ///
477 /// Note: The poll count wraps around on overflow.
478 pub fn poll_count(&self) -> usize {
479 self.poll_count.load(Ordering::SeqCst)
480 }
481}
482
483/// Implementation of [`MockService`] methods that use [`mod@proptest`] assertions.
484impl<Request, Response, Error> MockService<Request, Response, PropTestAssertion, Error> {
485 /// Expect a specific request to be received.
486 ///
487 /// The expected request should be the next one in the internal queue, or if the queue is
488 /// empty, it should be received in at most the max delay time configured by
489 /// [`MockServiceBuilder::with_max_request_delay`].
490 ///
491 /// If the received request matches the expected request, a [`ResponseSender`] is returned
492 /// which can be used to inspect the request and respond to it. If dropped without responding,
493 /// the caller's response future panics when polled.
494 ///
495 /// If no request is received or if a request is received that's not equal to the expected
496 /// request, this method returns an error generated by a [`mod@proptest`] assertion.
497 ///
498 /// # Example
499 ///
500 /// ```
501 /// # use proptest::prelude::*;
502 /// # use tower::ServiceExt;
503 /// #
504 /// # use zebra_test::mock_service::MockService;
505 /// #
506 /// # let reactor = tokio::runtime::Builder::new_current_thread()
507 /// # .enable_all()
508 /// # .build()
509 /// # .expect("Failed to build Tokio runtime");
510 /// #
511 /// # reactor.block_on(async {
512 /// # let test_code = || async {
513 /// # let mut mock_service: MockService<_, _, _> =
514 /// # MockService::build().for_prop_tests();
515 /// # let mut service = mock_service.clone();
516 /// #
517 /// let call = tokio::spawn(mock_service.clone().oneshot("request"));
518 ///
519 /// // NOTE: The try operator `?` is required for errors to be handled by proptest.
520 /// mock_service
521 /// .expect_request("request").await?
522 /// .respond("response");
523 ///
524 /// prop_assert!(matches!(call.await, Ok(Ok("response"))));
525 /// #
526 /// # Ok::<(), TestCaseError>(())
527 /// # };
528 /// # test_code().await
529 /// # }).unwrap();
530 /// ```
531 pub async fn expect_request(
532 &mut self,
533 expected: Request,
534 ) -> Result<ResponseSender<Request, Response, Error>, TestCaseError>
535 where
536 Request: PartialEq + Debug,
537 {
538 let response_sender = self.next_request().await?;
539
540 prop_assert_eq!(
541 &response_sender.request,
542 &expected,
543 "received an unexpected request\n \
544 in {}",
545 std::any::type_name::<Self>(),
546 );
547
548 Ok(response_sender)
549 }
550
551 /// Expect a request to be received that matches a specified condition.
552 ///
553 /// There should be a request already in the internal queue, or a request should be received in
554 /// at most the max delay time configured by [`MockServiceBuilder::with_max_request_delay`].
555 ///
556 /// The received request is passed to the `condition` function, which should return `true` if
557 /// it matches the expected condition or `false` otherwise. If `true` is returned, a
558 /// [`ResponseSender`] is returned which can be used to inspect the request again and respond
559 /// to it. If dropped without responding, the caller's response future panics when polled.
560 ///
561 /// If the `condition` function returns `false`, this method returns an error generated by a
562 /// [`mod@proptest`] assertion.
563 ///
564 /// # Example
565 ///
566 /// ```
567 /// # use proptest::prelude::*;
568 /// # use tower::ServiceExt;
569 /// #
570 /// # use zebra_test::mock_service::MockService;
571 /// #
572 /// # let reactor = tokio::runtime::Builder::new_current_thread()
573 /// # .enable_all()
574 /// # .build()
575 /// # .expect("Failed to build Tokio runtime");
576 /// #
577 /// # reactor.block_on(async {
578 /// # let test_code = || async {
579 /// # let mut mock_service: MockService<_, _, _> =
580 /// # MockService::build().for_prop_tests();
581 /// # let mut service = mock_service.clone();
582 /// #
583 /// let call = tokio::spawn(mock_service.clone().oneshot(1));
584 ///
585 /// // NOTE: The try operator `?` is required for errors to be handled by proptest.
586 /// mock_service
587 /// .expect_request_that(|request| *request > 0).await?
588 /// .respond("OK");
589 ///
590 /// prop_assert!(matches!(call.await, Ok(Ok("OK"))));
591 /// #
592 /// # Ok::<(), TestCaseError>(())
593 /// # };
594 /// # test_code().await
595 /// # }).unwrap();
596 /// ```
597 pub async fn expect_request_that(
598 &mut self,
599 condition: impl FnOnce(&Request) -> bool,
600 ) -> Result<ResponseSender<Request, Response, Error>, TestCaseError>
601 where
602 Request: Debug,
603 {
604 let response_sender = self.next_request().await?;
605
606 prop_assert!(
607 condition(&response_sender.request),
608 "condition was false for request: {:?},\n \
609 in {}",
610 &response_sender.request,
611 std::any::type_name::<Self>(),
612 );
613
614 Ok(response_sender)
615 }
616
617 /// Expect no requests to be received.
618 ///
619 /// The internal queue of received requests should be empty, and no new requests should arrive
620 /// for the max delay time configured by [`MockServiceBuilder::with_max_request_delay`].
621 ///
622 /// If the queue is not empty or if a request is received before the max request delay timeout
623 /// expires, an error generated by a [`mod@proptest`] assertion is returned.
624 ///
625 /// # Example
626 ///
627 /// ```
628 /// # use proptest::prelude::TestCaseError;
629 /// # use tower::ServiceExt;
630 /// #
631 /// # use zebra_test::mock_service::MockService;
632 /// #
633 /// # let reactor = tokio::runtime::Builder::new_current_thread()
634 /// # .enable_all()
635 /// # .build()
636 /// # .expect("Failed to build Tokio runtime");
637 /// #
638 /// # reactor.block_on(async {
639 /// # let test_code = || async {
640 /// # let mut mock_service: MockService<(), (), _> =
641 /// # MockService::build().for_prop_tests();
642 /// #
643 /// // NOTE: The try operator `?` is required for errors to be handled by proptest.
644 /// mock_service.expect_no_requests().await?;
645 /// #
646 /// # Ok::<(), TestCaseError>(())
647 /// # };
648 /// # test_code().await
649 /// # }).unwrap();
650 /// ```
651 pub async fn expect_no_requests(&mut self) -> Result<(), TestCaseError>
652 where
653 Request: Debug,
654 {
655 match self.try_next_request().await {
656 Some(response_sender) => {
657 prop_assert!(
658 false,
659 "received an unexpected request: {:?},\n \
660 in {}",
661 response_sender.request,
662 std::any::type_name::<Self>(),
663 );
664 unreachable!("prop_assert!(false) returns an early error");
665 }
666 None => Ok(()),
667 }
668 }
669
670 /// A helper method to get the next request from the queue.
671 ///
672 /// Returns the next request in the internal queue or waits at most the max delay time
673 /// configured by [`MockServiceBuilder::with_max_request_delay`] for a new request to be
674 /// received, and then returns that.
675 ///
676 /// If the queue is empty and a request is not received before the max request delay timeout
677 /// expires, an error generated by a [`mod@proptest`] assertion is returned.
678 async fn next_request(
679 &mut self,
680 ) -> Result<ResponseSender<Request, Response, Error>, TestCaseError> {
681 match self
682 .try_next_request_with_timeout(self.expected_request_timeout)
683 .await
684 {
685 Some(request) => Ok(request),
686 None => {
687 prop_assert!(
688 false,
689 "timeout while waiting for a request\n \
690 in {}",
691 std::any::type_name::<Self>(),
692 );
693 unreachable!("prop_assert!(false) returns an early error");
694 }
695 }
696 }
697
698 /// Returns a count of the number of times this service has been polled.
699 ///
700 /// Note: The poll count wraps around on overflow.
701 pub fn poll_count(&self) -> usize {
702 self.poll_count.load(Ordering::SeqCst)
703 }
704}
705
706/// Code that is independent of the assertions used in [`MockService`].
707impl<Request, Response, Assertion, Error> MockService<Request, Response, Assertion, Error> {
708 /// Try to get the next request received.
709 ///
710 /// Returns the next element in the queue. If the queue is empty, waits at most the max request
711 /// delay configured by [`MockServiceBuilder::with_max_request_delay`] for a request, and
712 /// returns it.
713 ///
714 /// If no request is received, returns `None`. The default observation window is 300 ms.
715 ///
716 /// # Panics
717 ///
718 /// If the receiver has lagged and lost requests, this method panics. Increase
719 /// [`MockServiceBuilder::with_proxy_channel_size`] to hold the expected request burst.
720 pub async fn try_next_request(&mut self) -> Option<ResponseSender<Request, Response, Error>> {
721 self.try_next_request_with_timeout(self.request_observation_timeout)
722 .await
723 }
724
725 /// Receive an unclaimed request within one deadline, including any already-claimed items.
726 async fn try_next_request_with_timeout(
727 &mut self,
728 max_request_delay: Duration,
729 ) -> Option<ResponseSender<Request, Response, Error>> {
730 timeout(max_request_delay, async {
731 loop {
732 match self.receiver.recv().await {
733 Ok(item) => {
734 if let Some(proxy_item) = item.lock().await.take() {
735 return proxy_item;
736 }
737 }
738 Err(RecvError::Lagged(dropped)) => panic!(
739 "MockService dropped {dropped} requests: \
740 increase with_proxy_channel_size to hold all requests between expectations"
741 ),
742 Err(RecvError::Closed) => unreachable!("sender is never closed"),
743 }
744 }
745 })
746 .await
747 .ok()
748 }
749}
750
751impl<Request, Response, Assertion, Error> Clone
752 for MockService<Request, Response, Assertion, Error>
753{
754 /// Clones the [`MockService`].
755 ///
756 /// This is a cheap operation, because it simply clones the [`broadcast`] channel endpoints.
757 fn clone(&self) -> Self {
758 MockService {
759 receiver: self.sender.subscribe(),
760 sender: self.sender.clone(),
761 poll_count: self.poll_count.clone(),
762 request_observation_timeout: self.request_observation_timeout,
763 expected_request_timeout: self.expected_request_timeout,
764 _assertion_type: PhantomData,
765 }
766 }
767}
768
769impl<Request, Response, Error> ResponseSender<Request, Response, Error> {
770 /// Create a [`ResponseSender`] for a given `request`.
771 fn new(request: Request) -> (Self, oneshot::Receiver<Result<Response, Error>>) {
772 let (response_sender, response_receiver) = oneshot::channel();
773
774 (
775 ResponseSender {
776 request,
777 response_sender,
778 },
779 response_receiver,
780 )
781 }
782
783 /// Access the `request` that's awaiting a response.
784 pub fn request(&self) -> &Request {
785 &self.request
786 }
787
788 /// Respond to the request using a fixed response value.
789 ///
790 /// The `response` can be of the `Response` type or a [`Result`]. This allows sending an error
791 /// representing an error while processing the request.
792 ///
793 /// This method takes ownership of the [`ResponseSender`] so that only one response can be
794 /// sent.
795 ///
796 /// # Example
797 ///
798 /// ```
799 /// # use zebra_test::mock_service::MockService;
800 /// # use tower::{Service, ServiceExt};
801 /// #
802 /// # #[derive(Debug, PartialEq, Eq)]
803 /// # struct Request;
804 /// #
805 /// # let reactor = tokio::runtime::Builder::new_current_thread()
806 /// # .enable_all()
807 /// # .build()
808 /// # .expect("Failed to build Tokio runtime");
809 /// #
810 /// # reactor.block_on(async {
811 /// // Mock a service with a `String` as the service `Error` type.
812 /// let mut mock_service: MockService<_, _, _, String> =
813 /// MockService::build().for_unit_tests();
814 ///
815 /// # let mut service = mock_service.clone();
816 /// # let task = tokio::spawn(async move {
817 /// # let first_call_result = (&mut service).oneshot(Request).await;
818 /// # let second_call_result = service.oneshot(Request).await;
819 /// #
820 /// # (first_call_result, second_call_result)
821 /// # });
822 /// #
823 /// mock_service
824 /// .expect_request(Request)
825 /// .await
826 /// .respond("Received Request".to_owned());
827 ///
828 /// mock_service
829 /// .expect_request(Request)
830 /// .await
831 /// .respond(Err("Duplicate request"));
832 /// # });
833 /// ```
834 pub fn respond(self, response: impl ResponseResult<Response, Error>) {
835 let _ = self.response_sender.send(response.into_result());
836 }
837
838 /// Respond to the request by calculating a value from the request.
839 ///
840 /// The response can be of the `Response` type or a [`Result`]. This allows sending an error
841 /// representing an error while processing the request.
842 ///
843 /// This method takes ownership of the [`ResponseSender`] so that only one response can be
844 /// sent.
845 ///
846 /// # Example
847 ///
848 /// ```
849 /// # use zebra_test::mock_service::MockService;
850 /// # use tower::{Service, ServiceExt};
851 /// #
852 /// # #[derive(Debug, PartialEq, Eq)]
853 /// # struct Request;
854 /// #
855 /// # let reactor = tokio::runtime::Builder::new_current_thread()
856 /// # .enable_all()
857 /// # .build()
858 /// # .expect("Failed to build Tokio runtime");
859 /// #
860 /// # reactor.block_on(async {
861 /// // Mock a service with a `String` as the service `Error` type.
862 /// let mut mock_service: MockService<_, _, _, String> =
863 /// MockService::build().for_unit_tests();
864 ///
865 /// # let mut service = mock_service.clone();
866 /// # let task = tokio::spawn(async move {
867 /// # let first_call_result = (&mut service).oneshot(Request).await;
868 /// # let second_call_result = service.oneshot(Request).await;
869 /// #
870 /// # (first_call_result, second_call_result)
871 /// # });
872 /// #
873 /// mock_service
874 /// .expect_request(Request)
875 /// .await
876 /// .respond_with(|req| format!("Received: {req:?}"));
877 ///
878 /// mock_service
879 /// .expect_request(Request)
880 /// .await
881 /// .respond_with(|req| Err(format!("Duplicate request: {req:?}")));
882 /// # });
883 /// ```
884 pub fn respond_with<F, R>(self, response_fn: F)
885 where
886 F: FnOnce(&Request) -> R,
887 R: ResponseResult<Response, Error>,
888 {
889 let response_result = response_fn(self.request()).into_result();
890 let _ = self.response_sender.send(response_result);
891 }
892
893 /// Respond to the request using a fixed error value.
894 ///
895 /// The `error` must be the `Error` type. This helps avoid type resolution issues in the
896 /// compiler.
897 ///
898 /// This method takes ownership of the [`ResponseSender`] so that only one response can be
899 /// sent.
900 ///
901 /// # Example
902 ///
903 /// ```
904 /// # use zebra_test::mock_service::MockService;
905 /// # use tower::{Service, ServiceExt};
906 /// #
907 /// # #[derive(Debug, PartialEq, Eq)]
908 /// # struct Request;
909 /// # struct Response;
910 /// #
911 /// # let reactor = tokio::runtime::Builder::new_current_thread()
912 /// # .enable_all()
913 /// # .build()
914 /// # .expect("Failed to build Tokio runtime");
915 /// #
916 /// # reactor.block_on(async {
917 /// // Mock a service with a `String` as the service `Error` type.
918 /// let mut mock_service: MockService<Request, Response, _, String> =
919 /// MockService::build().for_unit_tests();
920 ///
921 /// # let mut service = mock_service.clone();
922 /// # let task = tokio::spawn(async move {
923 /// # let first_call_result = (&mut service).oneshot(Request).await;
924 /// # let second_call_result = service.oneshot(Request).await;
925 /// #
926 /// # (first_call_result, second_call_result)
927 /// # });
928 /// #
929 /// mock_service
930 /// .expect_request(Request)
931 /// .await
932 /// .respond_error("Duplicate request".to_string());
933 /// # });
934 /// ```
935 pub fn respond_error(self, error: Error) {
936 // TODO: impl ResponseResult for BoxError/Error trait when overlapping impls are
937 // better supported by the compiler
938 let _ = self.response_sender.send(Err(error));
939 }
940
941 /// Respond to the request by calculating an error from the request.
942 ///
943 /// The `error` must be the `Error` type. This helps avoid type resolution issues in the
944 /// compiler.
945 ///
946 /// This method takes ownership of the [`ResponseSender`] so that only one response can be
947 /// sent.
948 ///
949 /// # Example
950 ///
951 /// ```
952 /// # use zebra_test::mock_service::MockService;
953 /// # use tower::{Service, ServiceExt};
954 /// #
955 /// # #[derive(Debug, PartialEq, Eq)]
956 /// # struct Request;
957 /// # struct Response;
958 /// #
959 /// # let reactor = tokio::runtime::Builder::new_current_thread()
960 /// # .enable_all()
961 /// # .build()
962 /// # .expect("Failed to build Tokio runtime");
963 /// #
964 /// # reactor.block_on(async {
965 /// // Mock a service with a `String` as the service `Error` type.
966 /// let mut mock_service: MockService<Request, Response, _, String> =
967 /// MockService::build().for_unit_tests();
968 ///
969 /// # let mut service = mock_service.clone();
970 /// # let task = tokio::spawn(async move {
971 /// # let first_call_result = (&mut service).oneshot(Request).await;
972 /// # let second_call_result = service.oneshot(Request).await;
973 /// #
974 /// # (first_call_result, second_call_result)
975 /// # });
976 /// #
977 /// mock_service
978 /// .expect_request(Request)
979 /// .await
980 /// .respond_with_error(|req| format!("Duplicate request: {req:?}"));
981 /// # });
982 /// ```
983 pub fn respond_with_error<F>(self, response_fn: F)
984 where
985 F: FnOnce(&Request) -> Error,
986 {
987 // TODO: impl ResponseResult for BoxError/Error trait when overlapping impls are
988 // better supported by the compiler
989 let response_result = Err(response_fn(self.request()));
990 let _ = self.response_sender.send(response_result);
991 }
992}
993
994/// A representation of an assertion type.
995///
996/// This trait is used to group the types of assertions that the [`MockService`] can do. There are
997/// currently two types that are used as type-system tags on the [`MockService`]:
998///
999/// - [`PanicAssertion`]
1000/// - [`PropTestAssertion`]
1001#[allow(dead_code)]
1002trait AssertionType {}
1003
1004/// Represents normal Rust assertions that panic, like [`assert_eq`].
1005pub enum PanicAssertion {}
1006
1007/// Represents [`mod@proptest`] assertions that return errors, like [`prop_assert_eq`].
1008pub enum PropTestAssertion {}
1009
1010impl AssertionType for PanicAssertion {}
1011
1012impl AssertionType for PropTestAssertion {}
1013
1014/// A helper trait to improve ergonomics when sending a response.
1015///
1016/// This allows the [`ResponseSender::respond`] method to receive either a [`Result`] or just the
1017/// response type, which it automatically wraps in an `Ok` variant.
1018pub trait ResponseResult<Response, Error> {
1019 /// Converts the type into a [`Result`] that can be sent as a response.
1020 fn into_result(self) -> Result<Response, Error>;
1021}
1022
1023impl<Response, Error> ResponseResult<Response, Error> for Response {
1024 fn into_result(self) -> Result<Response, Error> {
1025 Ok(self)
1026 }
1027}
1028
1029impl<Response, SourceError, TargetError> ResponseResult<Response, TargetError>
1030 for Result<Response, SourceError>
1031where
1032 SourceError: Into<TargetError>,
1033{
1034 fn into_result(self) -> Result<Response, TargetError> {
1035 self.map_err(|source_error| source_error.into())
1036 }
1037}