loco_rs/testing/request.rs
1use std::net::SocketAddr;
2
3use axum_test::{TestServer, TestServerConfig};
4use tokio::net::TcpListener;
5
6#[cfg(feature = "with-db")]
7use crate::Error;
8
9use crate::{
10 app::{AppContext, Hooks},
11 boot::{self, BootResult},
12 config::Server,
13 environment::Environment,
14 Result,
15};
16#[cfg(feature = "with-db")]
17use std::ops::Deref;
18
19#[cfg(feature = "with-db")]
20pub struct BootResultWrapper {
21 inner: BootResult,
22 test_db: Box<dyn super::db::TestSupport>,
23}
24
25#[cfg(feature = "with-db")]
26impl BootResultWrapper {
27 #[must_use]
28 pub fn new(boot: BootResult, test_db: Box<dyn super::db::TestSupport>) -> Self {
29 Self {
30 inner: boot,
31 test_db,
32 }
33 }
34}
35
36#[cfg(feature = "with-db")]
37impl Deref for BootResultWrapper {
38 type Target = BootResult;
39
40 fn deref(&self) -> &Self::Target {
41 &self.inner
42 }
43}
44
45#[cfg(feature = "with-db")]
46impl Drop for BootResultWrapper {
47 fn drop(&mut self) {
48 self.test_db.cleanup_db();
49 }
50}
51
52/// Configuration for making requests in the test server.
53pub struct RequestConfig {
54 /// Determines whether cookies should be saved for future requests.
55 pub save_cookies: bool,
56 /// The default content type for all requests.
57 pub default_content_type: Option<String>,
58 /// The default scheme to use for requests (e.g., "http" or "https").
59 pub default_scheme: String,
60}
61
62impl Default for RequestConfig {
63 fn default() -> Self {
64 RequestConfigBuilder::new().build()
65 }
66}
67
68/// Builder pattern for constructing [`RequestConfig`] instances.
69pub struct RequestConfigBuilder {
70 save_cookies: bool,
71 default_content_type: Option<String>,
72 default_scheme: String,
73}
74
75impl RequestConfigBuilder {
76 /// Creates a new [`RequestConfigBuilder`] with default values.
77 #[must_use]
78 pub fn new() -> Self {
79 Self {
80 save_cookies: false,
81 default_content_type: Some("application/json".to_string()),
82 default_scheme: "http".to_string(),
83 }
84 }
85
86 /// Sets whether cookies should be saved for future requests.
87 #[must_use]
88 pub fn save_cookies(mut self, save: bool) -> Self {
89 self.save_cookies = save;
90 self
91 }
92
93 /// Sets the default content type for requests.
94 #[must_use]
95 pub fn default_content_type<S: Into<String>>(mut self, content_type: S) -> Self {
96 self.default_content_type = Some(content_type.into());
97 self
98 }
99
100 /// Sets the default scheme to use for requests.
101 #[must_use]
102 pub fn default_scheme<S: Into<String>>(mut self, scheme: S) -> Self {
103 self.default_scheme = scheme.into();
104 self
105 }
106
107 /// Builds and returns a `RequestConfig` instance.
108 #[must_use]
109 pub fn build(self) -> RequestConfig {
110 RequestConfig {
111 save_cookies: self.save_cookies,
112 default_content_type: self.default_content_type,
113 default_scheme: self.default_scheme,
114 }
115 }
116}
117
118impl Default for RequestConfigBuilder {
119 fn default() -> Self {
120 Self::new()
121 }
122}
123
124// Implement the From trait for automatic conversion
125impl From<RequestConfig> for TestServerConfig {
126 fn from(request_config: RequestConfig) -> Self {
127 Self {
128 default_content_type: request_config.default_content_type,
129 save_cookies: request_config.save_cookies,
130 default_scheme: Some(request_config.default_scheme),
131 ..Default::default()
132 }
133 }
134}
135
136/// The port on which the test server will run.
137pub const TEST_PORT_SERVER: i32 = 5555;
138
139/// The hostname to which the test server binds.
140pub const TEST_BINDING_SERVER: &str = "localhost";
141
142/// Constructs and returns the base URL used for the test server.
143#[must_use]
144pub fn get_base_url_port(port: i32) -> String {
145 format!("http://{TEST_BINDING_SERVER}:{port}/")
146}
147
148/// Returns a unique port number. Usually increments by 1 starting from 59126
149///
150/// # Panics
151///
152/// Will panic if binding to test server address fails or if getting the local address fails
153pub async fn get_available_port() -> i32 {
154 let addr = format!("{TEST_BINDING_SERVER}:0");
155 let listener = TcpListener::bind(addr)
156 .await
157 .expect("Failed to bind to address");
158
159 i32::from(
160 listener
161 .local_addr()
162 .expect("Failed to get local address")
163 .port(),
164 )
165}
166
167/// Bootstraps test application with test environment hard coded.
168///
169/// # Example
170///
171/// The provided example demonstrates how to boot the test case with the
172/// application context.
173///
174/// ```rust,ignore
175/// use myapp::app::App;
176/// use loco_rs::testing::prelude::*;
177///
178/// #[tokio::test]
179/// async fn test_create_user() {
180/// let boot = boot_test::<App>().await;
181/// }
182/// ```
183///
184/// # Errors
185/// when could not bootstrap the test environment
186pub async fn boot_test<H: Hooks>() -> Result<BootResult> {
187 let config = H::load_config(&Environment::Test).await?;
188 let boot = H::boot(boot::StartMode::ServerOnly, &Environment::Test, config).await?;
189 Ok(boot)
190}
191
192/// Bootstraps the test application with a test environment and creates a new database.
193///
194/// This function initializes the test environment and sets up a fresh database for testing.
195/// The test database will be used during the test, and it will be cleaned up once the test completes.
196///
197/// ```rust,ignore
198/// use myapp::app::App;
199/// use loco_rs::testing::prelude::*;
200///
201/// #[tokio::test]
202/// async fn test_create_user() {
203/// let boot = boot_test_with_create_db::<App>().await;
204/// }
205/// ```
206///
207/// # Errors
208/// when could not bootstrap the test environment
209#[cfg(feature = "with-db")]
210pub async fn boot_test_with_create_db<H: Hooks>() -> Result<BootResultWrapper> {
211 let mut config = H::load_config(&Environment::Test).await?;
212 let test_db = super::db::init_test_db_creation(&config.database.uri)?;
213 test_db.init_db().await;
214 config.database.uri = test_db.get_connection_str().to_string();
215 let boot = match H::boot(boot::StartMode::ServerOnly, &Environment::Test, config).await {
216 Ok(boot) => boot,
217 Err(err) => {
218 test_db.cleanup_db();
219 return Err(Error::string(&err.to_string()));
220 }
221 };
222
223 Ok(BootResultWrapper::new(boot, test_db))
224}
225
226/// Bootstraps test application with test environment hard coded,
227/// and with a unique port.
228///
229/// # Errors
230/// when could not bootstrap the test environment
231///
232/// # Example
233///
234/// The provided example demonstrates how to boot the test case with the
235/// application context, and a with a unique port.
236///
237/// ```rust,ignore
238/// use myapp::app::App;
239/// use loco_rs::testing::prelude::*;
240///
241/// #[tokio::test]
242/// async fn test_create_user() {
243/// let port = get_available_port().await;
244/// let boot = boot_test_unique_port::<App>(Some(port)).await;
245///
246/// // .....
247/// }
248/// ```
249pub async fn boot_test_unique_port<H: Hooks>(port: Option<i32>) -> Result<BootResult> {
250 let mut config = H::load_config(&Environment::Test).await?;
251 config.server = Server {
252 port: port.unwrap_or(TEST_PORT_SERVER),
253 binding: TEST_BINDING_SERVER.to_string(),
254 ..config.server
255 };
256 H::boot(boot::StartMode::ServerOnly, &Environment::Test, config).await
257}
258
259#[allow(clippy::future_not_send)]
260async fn request_internal<F, Fut>(callback: F, boot: &BootResult, test_server_config: RequestConfig)
261where
262 F: FnOnce(TestServer, AppContext) -> Fut,
263 Fut: std::future::Future<Output = ()>,
264{
265 let routes = boot.router.clone().unwrap();
266 let server = TestServer::new_with_config(
267 routes.into_make_service_with_connect_info::<SocketAddr>(),
268 test_server_config,
269 )
270 .unwrap();
271
272 callback(server, boot.app_context.clone()).await;
273}
274
275/// Executes a test server request using the provided callback and the default boot process.
276///
277/// This function will boot the test environment without creating a new database.
278/// It takes a `callback` function that is called with the test server and application context.
279///
280/// # Panics
281/// When could not initialize the test request.this errors can be when could not
282/// initialize the test app
283///
284/// # Example
285///
286/// The provided example demonstrates how to create a test that check
287/// application HTTP endpoints
288///
289/// ```rust,ignore
290/// use myapp::app::App;
291/// use loco_rs::testing::prelude::*;
292///
293/// #[tokio::test]
294/// #[serial]
295/// async fn can_register() {
296/// request::<App, _, _>(|request, ctx| async move {
297/// let response = request.post("/auth/register").json(&serde_json::json!({})).await;
298/// })
299/// .await;
300/// }
301/// ```
302#[allow(clippy::future_not_send)]
303pub async fn request<H: Hooks, F, Fut>(callback: F)
304where
305 F: FnOnce(TestServer, AppContext) -> Fut,
306 Fut: std::future::Future<Output = ()>,
307{
308 request_with_config::<H, F, Fut>(RequestConfig::default(), callback).await;
309}
310/// Executes a test server request with a created database using the provided callback.
311///
312/// This function will boot the test environment and create a new database for the test.
313/// It takes a `callback` function that is called with the test server and application context.
314///
315/// ```rust,ignore
316/// use myapp::app::App;
317///
318/// #[tokio::test]
319/// async fn can_register() {
320/// request_with_create_db::<App, _, _>(|request, ctx| async move {
321/// let response = request.post("/auth/register").json(&serde_json::json!({})).await;
322/// })
323/// .await;
324/// }
325/// ```
326///
327/// # Panics
328/// When could not initialize the test request.this errors can be when could not
329/// initialize the test app
330#[allow(clippy::future_not_send)]
331#[cfg(feature = "with-db")]
332pub async fn request_with_create_db<H: Hooks, F, Fut>(callback: F)
333where
334 F: FnOnce(TestServer, AppContext) -> Fut,
335 Fut: std::future::Future<Output = ()>,
336{
337 request_config_with_create_db::<H, F, Fut>(RequestConfig::default(), callback).await;
338}
339
340/// Executes a test server request using a custom [`RequestConfig`].
341///
342/// This function will boot the test environment without creating a new database.
343/// It takes a `config` parameter to customize request settings and a `callback`
344/// function that is called with the test server and application context.
345///
346/// # Panics
347/// When the test request cannot be initialized, such as when the test app fails to start.
348///
349/// # Example
350/// ```rust,ignore
351/// let config = RequestConfigBuilder::new().save_cookies(true).build();
352/// request_with_config::<App, _, _>(config, |request, ctx| async move {
353/// let response = request.get("/endpoint").await;
354/// });
355/// ```
356pub async fn request_with_config<H: Hooks, F, Fut>(config: RequestConfig, callback: F)
357where
358 F: FnOnce(TestServer, AppContext) -> Fut,
359 Fut: std::future::Future<Output = ()>,
360{
361 let boot: BootResult = boot_test::<H>().await.unwrap();
362 request_internal(callback, &boot, config).await;
363}
364
365/// Executes a test server request with a created database using a custom [`RequestConfig`].
366///
367/// This function initializes the test environment, sets up a fresh database, and then runs
368/// the provided callback function with the test server and application context.
369/// The test database will be cleaned up after the test completes.
370///
371/// # Panics
372/// When the test request cannot be initialized, such as when the test app fails to start.
373///
374/// # Example
375/// ```rust,ignore
376/// let config = RequestConfigBuilder::new().save_cookies(true).build();
377/// request_config_with_create_db::<App, _, _>(config, |request, ctx| async move {
378/// let response = request.get("/endpoint").await;
379/// });
380/// ```
381#[allow(clippy::future_not_send)]
382#[cfg(feature = "with-db")]
383pub async fn request_config_with_create_db<H: Hooks, F, Fut>(config: RequestConfig, callback: F)
384where
385 F: FnOnce(TestServer, AppContext) -> Fut,
386 Fut: std::future::Future<Output = ()>,
387{
388 let boot_wrapper: BootResultWrapper = boot_test_with_create_db::<H>().await.unwrap();
389 request_internal(callback, &boot_wrapper.inner, config).await;
390}