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
#![forbid(unsafe_code)]
#![deny(
    clippy::dbg_macro,
    missing_copy_implementations,
    rustdoc::missing_crate_level_docs,
    missing_debug_implementations,
    missing_docs,
    nonstandard_style,
    unused_qualifications
)]

/*!
testing utilities for trillium applications.

this crate is intended to be used as a development dependency.

```
use trillium_testing::prelude::*;
use trillium::{Conn, conn_try};
async fn handler(mut conn: Conn) -> Conn {
    let request_body = conn_try!(conn.request_body_string().await, conn);
    conn.with_body(format!("request body was: {}", request_body))
        .with_status(418)
        .with_header("request-id", "special-request")
}

assert_response!(
    post("/").with_request_body("hello trillium!").on(&handler),
    Status::ImATeapot,
    "request body was: hello trillium!",
    "request-id" => "special-request",
    "content-length" => "33"
);

```

## Features

**You must enable a runtime feature for trillium testing**

### Tokio:
```toml
[dev-dependencies]
# ...
trillium-testing = { version = "0.2", features = ["tokio"] }
```

### Async-std:
```toml
[dev-dependencies]
# ...
trillium-testing = { version = "0.2", features = ["async-std"] }
```

### Smol:
```toml
[dev-dependencies]
# ...
trillium-testing = { version = "0.2", features = ["smol"] }
```


*/

mod assertions;

mod test_transport;
use std::future::{Future, IntoFuture};

pub use test_transport::TestTransport;

mod test_conn;
pub use test_conn::TestConn;

pub mod methods;
pub mod prelude {
    /*!
    useful stuff for testing trillium apps
    */
    pub use crate::{
        assert_body, assert_body_contains, assert_headers, assert_not_handled, assert_ok,
        assert_response, assert_status, block_on, connector, init, methods::*,
    };

    pub use trillium::{Conn, Method, Status};
}

pub use trillium::{Method, Status};

pub use url::Url;

/// initialize a handler
pub fn init(handler: &mut impl trillium::Handler) {
    let mut info = "testing".into();
    block_on(handler.init(&mut info))
}

// these exports are used by macros
pub use futures_lite;
pub use futures_lite::{AsyncRead, AsyncReadExt, AsyncWrite};

mod server_connector;
pub use server_connector::{connector, ServerConnector};

use trillium_server_common::{Config, Connector, Server};

#[derive(Debug)]
/// A droppable future
///
/// This only exists because of the #[must_use] on futures. The task will run to completion whether
/// or not this future is awaited.
pub struct SpawnHandle<F>(F);
impl<F> IntoFuture for SpawnHandle<F>
where
    F: Future,
{
    type IntoFuture = F;
    type Output = F::Output;
    fn into_future(self) -> Self::IntoFuture {
        self.0
    }
}

cfg_if::cfg_if! {
    if #[cfg(feature = "smol")] {
        /// runtime server config
        pub fn config() -> Config<impl Server, ()> {
            trillium_smol::config()
        }

        /// smol-based spawn variant that finishes whether or not the returned future is dropped
        pub fn spawn<Fut, Out>(future: Fut) -> SpawnHandle<impl Future<Output = Option<Out>>>
        where
            Fut: Future<Output = Out> + Send + 'static,
            Out: Send + 'static
        {
            let (tx, rx) = async_channel::bounded::<Out>(1);
            trillium_smol::async_global_executor::spawn(async move { let _ = tx.send(future.await).await; }).detach();
            SpawnHandle(async move {
                let rx = rx;
                rx.recv().await.ok()
            })
        }

        /// runtime client config
        pub fn client_config() -> impl Connector {
            trillium_smol::ClientConfig::default()
        }
        pub use trillium_smol::async_global_executor::block_on;
        pub use trillium_smol::ClientConfig;

    } else if #[cfg(feature = "async-std")] {
        /// runtime server config
        pub fn config() -> Config<impl Server, ()> {
            trillium_async_std::config()
        }
        pub use trillium_async_std::async_std::task::block_on;
        pub use trillium_async_std::ClientConfig;

        /// async-std-based spawn variant that finishes whether or not the returned future is dropped
        pub fn spawn<Fut, Out>(future: Fut) -> SpawnHandle<impl Future<Output = Option<Out>>>
        where
            Fut: Future<Output = Out> + Send + 'static,
            Out: Send + 'static
        {
            let (tx, rx) = async_channel::bounded::<Out>(1);
            trillium_async_std::async_std::task::spawn(async move { let _ = tx.send(future.await).await; });
            SpawnHandle(async move {
                let rx = rx;
                rx.recv().await.ok()
            })
        }
        /// runtime client config
        pub fn client_config() -> impl Connector {
            trillium_async_std::ClientConfig::default()
        }
    } else if #[cfg(feature = "tokio")] {
        /// runtime server config
        pub fn config() -> Config<impl Server, ()> {
            trillium_tokio::config()
        }
        pub use trillium_tokio::ClientConfig;
        pub use trillium_tokio::block_on;
        /// tokio-based spawn variant that finishes whether or not the returned future is dropped
        pub fn spawn<Fut, Out>(future: Fut) -> SpawnHandle<impl Future<Output = Option<Out>>>
        where
            Fut: Future<Output = Out> + Send + 'static,
            Out: Send + 'static
        {
            let (tx, rx) = async_channel::bounded::<Out>(1);
            trillium_tokio::tokio::task::spawn(async move { let _ = tx.send(future.await).await; });
            SpawnHandle(async move {
                let rx = rx;
                rx.recv().await.ok()
            })
        }
        /// runtime client config
        pub fn client_config() -> impl Connector {
            trillium_tokio::ClientConfig::default()
        }
   } else {
        /// runtime server config
        pub fn config() -> Config<impl Server, ()> {
            Config::<RuntimelessServer, ()>::new()
        }

        pub use RuntimelessClientConfig as ClientConfig;

        /// generic client config
        pub fn client_config() -> impl Connector {
            RuntimelessClientConfig
        }

        pub use futures_lite::future::block_on;

        /// fake runtimeless spawn that finishes whether or not the future is dropped
        pub fn spawn<Fut, Out>(future: Fut) -> SpawnHandle<impl Future<Output = Option<Out>>>
        where
            Fut: Future<Output = Out> + Send + 'static,
            Out: Send + 'static
        {
            let (tx, rx) = async_channel::bounded::<Out>(1);
            std::thread::spawn(move || { let _ = tx.send_blocking(block_on(future)); });
            SpawnHandle(async move {
                let rx = rx;
                rx.recv().await.ok()
            })
        }
    }
}

mod with_server;
pub use with_server::{with_server, with_transport};

mod runtimeless;
pub use runtimeless::{RuntimelessClientConfig, RuntimelessServer};

/// a sponge Result
pub type TestResult = Result<(), Box<dyn std::error::Error>>;

/// a test harness for use with [`test_harness`]
#[track_caller]
pub fn harness<F, Fut>(test: F)
where
    F: FnOnce() -> Fut,
    Fut: Future<Output = TestResult>,
{
    block_on(test()).unwrap();
}