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
use ::anyhow::Context;
use ::anyhow::Result;
use ::axum::body::Body;
use ::axum::http::Method;
use ::axum::http::Request;
use ::axum::routing::IntoMakeService;
use ::axum::Router;
use ::axum::Server;
use ::hyper::body::to_bytes;
use ::hyper::body::Bytes;
use ::hyper::header;
use ::hyper::Client;
use ::std::net::SocketAddr;
use ::std::net::TcpListener;
use ::tokio::spawn;
use ::tokio::task::JoinHandle;

use crate::util::new_random_socket_addr;
use crate::TestResponse;

/// A means to run Axum applications within a server that you can query.
/// This is for writing tests.
pub struct TestServer {
    server_thread: JoinHandle<()>,
    server_address: String,
}

impl TestServer {
    /// This will take the given app, and run it.
    /// It will be run on a randomly picked port.
    ///
    /// The webserver is then wrapped within a `TestServer`,
    /// and returned.
    ///
    /// This function is for quick use. It will panic if it cannot
    /// create the webserver.
    pub fn new(app: IntoMakeService<Router>) -> Self {
        let addr = new_random_socket_addr().expect("Cannot create socket address for use");
        let test_server = Self::new_with_address(app, addr).expect("Cannot create TestServer");

        test_server
    }

    /// Creates a `TestServer` running your app on the address given.
    pub fn new_with_address(
        app: IntoMakeService<Router>,
        socket_address: SocketAddr,
    ) -> Result<Self> {
        let listener = TcpListener::bind(socket_address)
            .with_context(|| "Failed to create TCPListener for TestServer")?;
        let server_address = socket_address.to_string();
        let server = Server::from_tcp(listener)
            .with_context(|| "Failed to create ::axum::Server for TestServer")?
            .serve(app);

        let server_thread = spawn(async move {
            server.await.expect("Expect server to start serving");
        });

        let test_server = Self {
            server_thread,
            server_address,
        };

        Ok(test_server)
    }

    /// Performs a GET request to the path.
    ///
    /// This will presume the response is successful (a 200 status code).
    /// If a different status code is returned, then this will panic.
    pub async fn get(&self, path: &str) -> TestResponse {
        self.send(Method::GET, path, &"")
            .await
            .with_context(|| format!("Error calling get on path {}", path))
            .unwrap()
            .assert_status_ok()
    }

    /// Performs a GET request to the path.
    ///
    /// This will panic if the response is successful.
    /// It presumes the response would have failed.
    pub async fn get_fail(&self, path: &str) -> TestResponse {
        self.send(Method::GET, path, &"")
            .await
            .with_context(|| format!("Error calling get_fail on path {}", path))
            .unwrap()
            .assert_status_not_ok()
    }

    /// Performs a POST request to the path.
    ///
    /// This will presume the response is successful (a 200 status code).
    /// If a different status code is returned, then this will panic.
    pub async fn post(&self, path: &str, body: &str) -> TestResponse {
        self.send(Method::POST, path, body)
            .await
            .with_context(|| format!("Error calling post on path {}", path))
            .unwrap()
            .assert_status_ok()
    }

    /// Performs a POST request to the path.
    ///
    /// This will panic if the response is successful.
    /// It presumes the response would have failed.
    pub async fn post_fail(&self, path: &str, body: &str) -> TestResponse {
        self.send(Method::POST, path, body)
            .await
            .with_context(|| format!("Error calling post_fail on path {}", path))
            .unwrap()
            .assert_status_not_ok()
    }

    /// Performs a PATCH request to the path.
    ///
    /// This will panic if the response is successful.
    /// It presumes the response would have failed.
    pub async fn patch(&self, path: &str, body: &str) -> TestResponse {
        self.send(Method::PATCH, path, body)
            .await
            .with_context(|| format!("Error calling patch on path {}", path))
            .unwrap()
            .assert_status_ok()
    }

    /// Performs a PATCH request to the path.
    ///
    /// This will panic if the response is successful.
    /// It presumes the response would have failed.
    pub async fn patch_fail(&self, path: &str, body: &str) -> TestResponse {
        self.send(Method::PATCH, path, body)
            .await
            .with_context(|| format!("Error calling patch_fail on path {}", path))
            .unwrap()
            .assert_status_not_ok()
    }

    /// Performs a PUT request to the path.
    ///
    /// This will presume the response is successful (a 200 status code).
    /// If a different status code is returned, then this will panic.
    pub async fn put(&self, path: &str, body: &str) -> TestResponse {
        self.send(Method::PUT, path, body)
            .await
            .with_context(|| format!("Error calling put on path {}", path))
            .unwrap()
            .assert_status_ok()
    }

    /// Performs a PUT request to the path.
    ///
    /// This will panic if the response is successful.
    /// It presumes the response would have failed.
    pub async fn put_fail(&self, path: &str, body: &str) -> TestResponse {
        self.send(Method::PUT, path, body)
            .await
            .with_context(|| format!("Error calling put_fail on path {}", path))
            .unwrap()
            .assert_status_not_ok()
    }

    /// Performs a DELETE request to the path.
    ///
    /// This will presume the response is successful (a 200 status code).
    /// If a different status code is returned, then this will panic.
    pub async fn delete(&self, path: &str) -> TestResponse {
        self.send(Method::DELETE, path, &"")
            .await
            .with_context(|| format!("Error calling delete_fail on path {}", path))
            .unwrap()
            .assert_status_ok()
    }

    /// Performs a DELETE request to the path.
    ///
    /// This will panic if the response is successful.
    /// It presumes the response would have failed.
    pub async fn delete_fail(&self, path: &str) -> TestResponse {
        self.send(Method::DELETE, path, &"")
            .await
            .with_context(|| format!("Error calling delete_fail on path {}", path))
            .unwrap()
            .assert_status_not_ok()
    }

    async fn send(&self, method: Method, path: &str, body_str: &str) -> Result<TestResponse> {
        let request_url = path.to_string();
        let request_path = build_request_path(&self.server_address, path);
        let client = Client::new();
        let body_bytes = Bytes::copy_from_slice(body_str.as_bytes());
        let body: Body = body_bytes.into();

        let hyper_response = client
            .request(
                Request::builder()
                    .uri(request_path)
                    .header(header::CONTENT_TYPE, "application/json")
                    .method(method)
                    .body(body)
                    .expect("expect Request built to be valid"),
            )
            .await
            .expect("Expect TestResponse to come back");

        let (parts, response_body) = hyper_response.into_parts();
        let response_bytes = to_bytes(response_body).await?;
        let contents = String::from_utf8_lossy(&response_bytes).to_string();
        let status_code = parts.status;
        let response = TestResponse::new(request_url, contents, status_code);

        Ok(response)
    }
}

impl Drop for TestServer {
    fn drop(&mut self) {
        self.server_thread.abort();
    }
}

fn build_request_path(root_path: &str, sub_path: &str) -> String {
    if sub_path == "" {
        return format!("http://{}", root_path.to_string());
    }

    if sub_path.starts_with("/") {
        return format!("http://{}{}", root_path, sub_path);
    }

    format!("http://{}/{}", root_path, sub_path)
}