tower_test/mock/
spawn.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
//! Spawn mock services onto a mock task.

use std::task::Poll;
use tokio_test::task;
use tower_service::Service;

/// Service spawned on a mock task
#[derive(Debug)]
pub struct Spawn<T> {
    inner: T,
    task: task::Spawn<()>,
}

impl<T> Spawn<T> {
    /// Create a new spawn.
    pub fn new(inner: T) -> Self {
        Self {
            inner,
            task: task::spawn(()),
        }
    }

    /// Check if this service has been woken up.
    pub fn is_woken(&self) -> bool {
        self.task.is_woken()
    }

    /// Get how many futurs are holding onto the waker.
    pub fn waker_ref_count(&self) -> usize {
        self.task.waker_ref_count()
    }

    /// Poll this service ready.
    pub fn poll_ready<Request>(&mut self) -> Poll<Result<(), T::Error>>
    where
        T: Service<Request>,
    {
        let task = &mut self.task;
        let inner = &mut self.inner;

        task.enter(|cx, _| inner.poll_ready(cx))
    }

    /// Call the inner Service.
    pub fn call<Request>(&mut self, req: Request) -> T::Future
    where
        T: Service<Request>,
    {
        self.inner.call(req)
    }

    /// Get the inner service.
    pub fn into_inner(self) -> T {
        self.inner
    }

    /// Get a reference to the inner service.
    pub fn get_ref(&self) -> &T {
        &self.inner
    }

    /// Get a mutable reference to the inner service.
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.inner
    }
}

impl<T: Clone> Clone for Spawn<T> {
    fn clone(&self) -> Self {
        Spawn::new(self.inner.clone())
    }
}