vyuh 0.2.2

Vyuh web framework for Axum and SQLx with handler-first APIs
Documentation
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use crate::db::{DbConf, Pool};
use crate::{Site, SiteConf};
use axum::Router;
use axum::body::{self, Body, Bytes};
use axum::http::{Method, Request, Response};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{self, Value, value::to_value};
use std::collections::BTreeMap;
use std::ops::Deref;
use tower::ServiceExt;

pub use sqlx::{test, test_block_on};

pub fn router(site: &Site) -> Router {
    site.router()
}

pub struct TestClient {
    app: Router,
    site: Site,
}

impl TestClient {
    pub fn new(site: Site) -> Self {
        let app = router(&site);
        Self { app, site }
    }

    pub fn request(&self, method: Method, path: &str) -> TestRequestBuilder {
        TestRequestBuilder::new(self.app.clone(), method, path)
    }

    pub fn get(&self, path: &str) -> TestRequestBuilder {
        self.request(Method::GET, path)
    }
    pub fn post(&self, path: &str) -> TestRequestBuilder {
        self.request(Method::POST, path)
    }
    pub fn put(&self, path: &str) -> TestRequestBuilder {
        self.request(Method::PUT, path)
    }
    pub fn delete(&self, path: &str) -> TestRequestBuilder {
        self.request(Method::DELETE, path)
    }
    pub fn patch(&self, path: &str) -> TestRequestBuilder {
        self.request(Method::PATCH, path)
    }
}

impl Drop for TestClient {
    fn drop(&mut self) {
        self.site.shutdown();
    }
}

pub struct TestRequestBuilder {
    app: Router,
    method: Method,
    path: String,
    headers: Vec<(String, String)>,
    body: Option<Body>,
}

impl TestRequestBuilder {
    pub fn new(app: Router, method: Method, path: &str) -> Self {
        Self {
            app,
            method,
            path: path.to_string(),
            headers: Vec::new(),
            body: None,
        }
    }

    pub fn header(mut self, key: &str, value: &str) -> Self {
        self.headers.push((key.to_string(), value.to_string()));
        self
    }

    pub fn body(mut self, body: Body) -> Self {
        self.body = Some(body);
        self
    }

    pub fn json<T: Serialize>(mut self, value: &T) -> Self {
        let json = serde_json::to_vec(value).expect("Failed to serialize JSON");
        self.body = Some(Body::from(json));
        self.headers
            .push(("content-type".to_string(), "application/json".to_string()));
        self
    }

    pub fn query<T: Serialize>(mut self, params: &[(&str, T)]) -> Self {
        let query = TestClient::build_query(params);
        if self.path.contains('?') {
            self.path = format!("{}&{}", self.path, query);
        } else {
            self.path = format!("{}?{}", self.path, query);
        }
        self
    }

    pub async fn send(self) -> TestResponse {
        let mut req = Request::builder().method(self.method).uri(self.path);
        for (k, v) in self.headers {
            req = req.header(&k, &v);
        }
        let req = req
            .body(self.body.unwrap_or_else(|| Body::empty()))
            .unwrap();
        let resp = self.app.clone().oneshot(req).await.unwrap();
        TestResponse { resp }
    }
}

#[derive(Debug)]
pub struct TestResponse {
    resp: Response<Body>,
}

impl TestResponse {
    pub fn status(&self) -> axum::http::StatusCode {
        self.resp.status()
    }
    pub async fn text(self) -> String {
        let bytes = body::to_bytes(self.resp.into_body(), usize::MAX)
            .await
            .expect("Failed to read body");
        String::from_utf8(bytes.to_vec()).expect("Response was not valid UTF-8")
    }
    pub async fn bytes(self) -> Bytes {
        body::to_bytes(self.resp.into_body(), usize::MAX)
            .await
            .expect("Failed to read body")
    }
    pub async fn json<T: DeserializeOwned>(self) -> T {
        let bytes = body::to_bytes(self.resp.into_body(), usize::MAX)
            .await
            .expect("Failed to read body");
        serde_json::from_slice(&bytes).expect("Response was not valid JSON")
    }
    pub async fn assert_text(self, expected_status: axum::http::StatusCode, expected_body: &str) {
        assert_eq!(self.status(), expected_status);
        let body = self.text().await;
        assert_eq!(body, expected_body);
    }
    pub async fn assert_json<T: DeserializeOwned + PartialEq + std::fmt::Debug>(
        self,
        expected_status: axum::http::StatusCode,
        expected_json: &T,
    ) {
        assert_eq!(self.status(), expected_status);
        let body: T = self.json().await;
        assert_eq!(&body, expected_json);
    }

    pub fn assert_status(self, expected_status: axum::http::StatusCode) -> Self {
        assert_eq!(
            self.status(),
            expected_status,
            "Expected status {}, got {}",
            expected_status,
            self.status()
        );
        self
    }

    pub fn assert_ok(self) -> Self {
        self.assert_status(axum::http::StatusCode::OK)
    }

    pub fn assert_created(self) -> Self {
        self.assert_status(axum::http::StatusCode::CREATED)
    }

    pub fn assert_not_found(self) -> Self {
        self.assert_status(axum::http::StatusCode::NOT_FOUND)
    }

    pub fn assert_bad_request(self) -> Self {
        self.assert_status(axum::http::StatusCode::BAD_REQUEST)
    }
}

impl TestClient {
    pub fn build_query<T: Serialize>(params: &[(&str, T)]) -> String {
        let mut map = BTreeMap::new();
        for (k, v) in params {
            let value: Value = to_value(v).expect("Failed to serialize param");
            let s = match value {
                Value::String(s) => s,
                Value::Number(n) => n.to_string(),
                Value::Bool(b) => b.to_string(),
                _ => value.to_string(),
            };
            map.insert(*k, s);
        }
        serde_urlencoded::to_string(&map).unwrap()
    }
}

/// Creates a minimal mock Site for testing purposes
/// Uses lazy DB (no actual connection) and safe defaults
pub async fn mock_site() -> SiteConf {
    use uuid::Uuid;

    let _test_db_name = format!("vyuh_test_{}", Uuid::now_v7().simple());
    let conf = SiteConf {
        host: "localhost".to_string(),
        port: 8080,
        project_dir: "/tmp/vyuh_test".to_string(),
        database: DbConf::default(),
        secret_key: "test_secret_key_minimum_32_chars!".to_string(),
        static_dirs: vec![],
        media_dir: None,
        templates: crate::templates::TemplateConf::default(),
        touch_reload: None,
        log_init: false,
        tz: Some("UTC".to_string()),
        auth: crate::auth::AuthConf::default(),
        ..Default::default()
    };

    conf
}

/// RAII guard for a test database
/// Automatically drops the database when the guard is dropped
pub struct MockDb {
    pool: Pool,
    pub db_name: String,
    pub base_url: String,
}

impl MockDb {
    pub fn pool(&self) -> &Pool {
        &self.pool
    }
}

impl Deref for MockDb {
    type Target = Pool;

    fn deref(&self) -> &Self::Target {
        &self.pool
    }
}

impl Drop for MockDb {
    fn drop(&mut self) {
        #[cfg(any(feature = "postgres", feature = "mysql"))]
        let db_name = self.db_name.clone();
        #[cfg(any(feature = "postgres", feature = "mysql"))]
        let base_url = self.base_url.clone();

        #[cfg(feature = "postgres")]
        {
            if !db_name.is_empty() {
                let _ = std::thread::spawn(move || {
                    let rt = tokio::runtime::Runtime::new().ok()?;
                    rt.block_on(async {
                        if let Ok(root_pool) = sqlx::PgPool::connect(&base_url).await {
                            let _ = sqlx::query(&format!(
                                "DROP DATABASE IF EXISTS \"{}\" WITH (FORCE)",
                                db_name
                            ))
                            .execute(&root_pool)
                            .await;
                            root_pool.close().await;
                        }
                        Some(())
                    })
                })
                .join();
            }
        }

        #[cfg(feature = "mysql")]
        {
            if !db_name.is_empty() {
                let _ = std::thread::spawn(move || {
                    let rt = tokio::runtime::Runtime::new().ok()?;
                    rt.block_on(async {
                        if let Ok(root_pool) = sqlx::MySqlPool::connect(&base_url).await {
                            let _ = sqlx::query(&format!("DROP DATABASE IF EXISTS `{}`", db_name))
                                .execute(&root_pool)
                                .await;
                            root_pool.close().await;
                        }
                        Some(())
                    })
                })
                .join();
            }
        }

        #[cfg(feature = "sqlite")]
        {
            // SQLite uses :memory:, no cleanup needed
        }
    }
}

/// Creates a new isolated database for testing
/// Similar to sqlx test macros, creates a unique database that is cleaned up after use
/// Returns a MockDb guard that derefs to Pool and drops the database on drop
///
/// # Example
/// ```ignore
/// #[tokio::test]
/// async fn test_something() {
///     let db = mock_db().await;
///     // Use db like a Pool - it derefs automatically
///     sqlx::query("SELECT 1").execute(&*db).await.unwrap();
///     // Database is dropped when db goes out of scope
/// }
/// ```
pub async fn mock_db() -> MockDb {
    #[cfg(feature = "postgres")]
    {
        let base_url = std::env::var("TEST_DATABASE_URL")
            .unwrap_or_else(|_| "postgres://localhost".to_string());

        let db_name = format!("vyuh_test_{}", uuid::Uuid::now_v7().simple());

        let root_pool = sqlx::PgPool::connect(&base_url)
            .await
            .expect("Failed to connect to postgres");

        sqlx::query(&format!("CREATE DATABASE \"{}\"", db_name))
            .execute(&root_pool)
            .await
            .expect("Failed to create test database");

        root_pool.close().await;

        let test_url = if base_url.contains('/') {
            let parts: Vec<&str> = base_url.rsplitn(2, '/').collect();
            format!("{}/{}", parts[1], db_name)
        } else {
            format!("{}/{}", base_url, db_name)
        };

        let pool = sqlx::PgPool::connect(&test_url)
            .await
            .expect("Failed to connect to test database");

        MockDb {
            pool,
            db_name,
            base_url,
        }
    }

    #[cfg(feature = "mysql")]
    {
        let base_url =
            std::env::var("TEST_DATABASE_URL").unwrap_or_else(|_| "mysql://localhost".to_string());

        let db_name = format!("vyuh_test_{}", uuid::Uuid::now_v7().simple());

        let root_pool = sqlx::MySqlPool::connect(&base_url)
            .await
            .expect("Failed to connect to mysql");

        sqlx::query(&format!("CREATE DATABASE `{}`", db_name))
            .execute(&root_pool)
            .await
            .expect("Failed to create test database");

        root_pool.close().await;

        let test_url = if base_url.contains('/') {
            let parts: Vec<&str> = base_url.rsplitn(2, '/').collect();
            format!("{}/{}", parts[1], db_name)
        } else {
            format!("{}/{}", base_url, db_name)
        };

        let pool = sqlx::MySqlPool::connect(&test_url)
            .await
            .expect("Failed to connect to test database");

        MockDb {
            pool,
            db_name,
            base_url,
        }
    }

    #[cfg(feature = "sqlite")]
    {
        let pool = sqlx::SqlitePool::connect(":memory:")
            .await
            .expect("Failed to create in-memory sqlite database");

        MockDb {
            pool,
            db_name: String::new(),
            base_url: String::new(),
        }
    }
}