tideway 0.7.17

A batteries-included Rust web framework built on Axum for building SaaS applications quickly
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# Testing Guide

Tideway provides comprehensive testing utilities inspired by .NET's Alba framework, making it easy to test HTTP endpoints without running a full server.

## Overview

Tideway's testing utilities provide:

- **Alba-style Testing**: Fluent API for HTTP endpoint testing
- **Reusable Test Hosts**: Shared router setup with before/after hooks
- **Test Fixtures**: Factory pattern for creating test data
- **Database Testing**: Isolated database testing with transactions
- **Fake Data**: Helpers for generating test data

## Basic Testing

### Simple GET Request

```rust
use tideway::testing::{get, post};
use axum::{routing::get as axum_get, Router, Json};
use serde_json::json;

async fn hello_handler() -> Json<serde_json::Value> {
    Json(json!({"message": "Hello, World!"}))
}

#[tokio::test]
async fn test_hello() {
    let app = Router::new().route("/hello", axum_get(hello_handler));

    get(app, "/hello")
        .execute()
        .await
        .assert_ok()
        .assert_json_path("message", json!("Hello, World!"))
        .await;
}
```

### POST Request with JSON

```rust
use tideway::testing::post;

#[tokio::test]
async fn test_create_user() {
    let app = create_app();

    post(app, "/api/users")
        .with_json(&json!({
            "email": "test@example.com",
            "name": "Test User",
        }))
        .execute()
        .await
        .assert_created()
        .assert_json_path("data.email", json!("test@example.com"))
        .await;
}
```

### Alba-Style TestHost

```rust
use tideway::testing::TestHost;
use serde_json::json;

#[tokio::test]
async fn test_with_host_hooks() {
    let host = TestHost::new(create_tideway_app()).before_each(|request| {
        request
            .headers_mut()
            .insert("x-trace", "spec-123".parse().unwrap());
    });

    host.scenario(|scenario| {
        scenario.get("/api/health");
        scenario.header_should_exist("x-request-id");
        scenario.json_should_contain(json!({ "ok": true }));
    }).await;
}
```

### Host Setup Overrides

Use `TestHost::builder(...)` when a spec needs to alter the app before the
shared host is materialized:

```rust,ignore
use std::sync::Arc;
use tideway::testing::TestHost;

let host = TestHost::builder(app)
    .configure_app(|app| {
        app.merge_router(extra_router())
    })
    .configure_context(|context| {
        context.with_auth_provider(Arc::new(test_provider()))
    })
    .without_middleware()
    .before_each(|request| {
        request
            .headers_mut()
            .insert("x-trace", "spec-123".parse().unwrap());
    })
    .build();
```

This is the closest Tideway equivalent to Alba host bootstrapping: you can swap
dependencies, register extra routes, or drop Tideway middleware for a focused
integration spec without rebuilding the whole app by hand.

### Config And Environment Overrides

When the spec needs to vary runtime settings before the app exists, start from
`TestHost::bootstrap()` instead of a prebuilt `App`:

```rust,ignore
use tideway::testing::TestHost;

let host = TestHost::bootstrap()
    .from_env()
    .with_env_var("TIDEWAY_MAX_BODY_SIZE", "1024")
    .configure_config(|mut config| {
        config.dev.enabled = true;
        config
    })
    .configure_app(|app| app.register_module(ApiModule))
    .build();
```

Use `from_config(...)` or `from_config_builder(...)` when you want an explicit
starting point instead of the default config.

## Assertions

### Status Code Assertions

```rust
response.assert_ok();        // 200 OK
response.assert_created();   // 201 Created
response.assert_not_found(); // 404 Not Found
response.assert_bad_request(); // 400 Bad Request
```

### JSON Assertions

```rust
response.assert_json(); // Validates JSON response

// Assert specific JSON path
response.assert_json_path("data.id", json!(123)).await;

// Assert response contains text
response.assert_contains("success").await;
```

### Header Assertions

```rust
response.assert_header("content-type", "application/json");
response.assert_header_exists("x-request-id");
```

## Request Modifiers

### Query Parameters

```rust
get(app, "/api/users")
    .with_query(&[("page", "1"), ("limit", "20")])
    .execute()
    .await
    .assert_ok();
```

### Authentication

```rust
get(app, "/api/protected")
    .with_auth("token-123")
    .execute()
    .await
    .assert_ok();
```

With `test-auth-bypass`, you can also inject a synthetic authenticated identity:

```rust,ignore
host.scenario(|scenario| {
    scenario.get("/api/me");
    scenario.with_test_user("user-123");
}).await;

host.scenario(|scenario| {
    scenario.get("/api/admin");
    scenario.with_test_claims(&MyClaims {
        sub: "admin-1".into(),
        role: "admin".into(),
    });
}).await;
```

### Custom Headers

```rust
get(app, "/api/data")
    .with_header("X-Custom-Header", "value")
    .execute()
    .await
    .assert_ok();
```

### Request Body

```rust
post(app, "/api/users")
    .with_json(&user_data)
    .execute()
    .await
    .assert_created();

put(app, "/api/users/123")
    .with_json(&update_data)
    .execute()
    .await
    .assert_ok();
```

### Form Posts

```rust
post(app, "/login")
    .with_form(&[
        ("email", "test@example.com"),
        ("password", "secret"),
    ])
    .execute()
    .await
    .assert_ok();
```

## Test Fixtures

### TestFactory Trait

Create reusable test data factories:

```rust
use tideway::testing::TestFactory;

struct UserFactory;

impl TestFactory<User> for UserFactory {
    fn build() -> User {
        User {
            id: 0,
            email: tideway::testing::fake::email(),
            name: tideway::testing::fake::name(),
        }
    }

    fn build_with<F>(f: F) -> User
    where
        F: FnOnce(&mut User),
    {
        let mut user = Self::build();
        f(&mut user);
        user
    }
}

#[tokio::test]
async fn test_create_user() {
    let user = UserFactory::build_with(|u| {
        u.email = "custom@example.com".to_string();
    });

    // Use user in test
}
```

### Fake Data Helpers

Generate realistic test data:

```rust
use tideway::testing::fake;

let email = fake::email();           // "user123@example.com"
let uuid = fake::uuid();             // UUID v4
let name = fake::name();             // "John Doe"
let username = fake::username();     // "johndoe123"
let phone = fake::phone();           // "+1234567890"
```

## Database Testing

### TestDb

Tideway supports two integration profiles:

- Default SQLite in-memory with `TestDb::new()` (fast, zero infra).
- PostgreSQL-backed tests via `TestDb::new_postgres()` (local Postgres required) or `TIDEWAY_TEST_DB_BACKEND=postgres_container` with the `test-containers` feature (starts a temporary Docker container).

Test database operations in isolation:

```rust
use tideway::testing::TestDb;

#[tokio::test]
async fn test_user_creation() {
    let db = TestDb::new().await.unwrap();

    // Seed database
    db.seed("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT)")
        .await
        .unwrap();

    // Run migrations if needed
    db.run_migrations(&migrator).await.unwrap();

    // Test in transaction (always rolled back)
    db.with_transaction_rollback(|tx| async move {
        // Your test code here
        // Transaction is automatically rolled back
    }).await.unwrap();

    // Reset database
    db.reset().await.unwrap();
}
```

### Transaction Rollback

Ensure test isolation:

```rust
#[tokio::test]
async fn test_multiple_operations() {
    let db = TestDb::new().await.unwrap();

    db.with_transaction_rollback(|tx| async move {
        // All operations in this block are rolled back
        // Database state is unchanged after test
        create_user(&tx).await;
        update_user(&tx).await;
        delete_user(&tx).await;
    }).await.unwrap();
}
```

## Advanced Testing

### Testing Error Cases

```rust
#[tokio::test]
async fn test_not_found() {
    let app = create_app();

    get(app, "/api/users/999")
        .execute()
        .await
        .assert_not_found()
        .assert_json_path("error", json!("Not found: User not found"))
        .await;
}
```

### Testing Redirects

```rust
get(app, "/legacy")
    .execute()
    .await
    .assert_redirect_to("/new-path");
```

### Testing Validation Errors

```rust
#[tokio::test]
async fn test_validation_error() {
    let app = create_app();

    post(app, "/api/users")
        .with_json(&json!({
            "email": "invalid-email", // Invalid email
            "password": "short",       // Too short
        }))
        .execute()
        .await
        .assert_bad_request()
        .assert_json_path("field_errors.email", json!(["must be a valid email"]))
        .await;
}
```

### Testing Authentication

```rust
#[tokio::test]
async fn test_unauthorized() {
    let app = create_app();

    get(app, "/api/protected")
        .execute()
        .await
        .assert_unauthorized();
}

#[tokio::test]
async fn test_authorized() {
    let app = create_app();
    let token = create_test_token();

    get(app, "/api/protected")
        .with_auth(&token)
        .execute()
        .await
        .assert_ok();
}
```

### Debugging Responses

```rust
#[tokio::test]
async fn test_debug_response() {
    let app = create_app();

    let response = get(app, "/api/users")
        .execute()
        .await
        .assert_ok();

    // Dump response for debugging
    response.dump().await;

    // Or get response body as string
    let body = response.body_string().await;
    println!("Response: {}", body);
}
```

## Best Practices

1. **Isolation**: Use `with_transaction_rollback` for database tests
2. **Fixtures**: Use `TestFactory` for reusable test data
3. **Fake Data**: Use `fake` helpers for realistic test data
4. **Clear Assertions**: Use descriptive assertion methods
5. **Error Testing**: Test both success and error cases
6. **Test Organization**: Group related tests in modules

## Example Test Suite

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use tideway::testing::{get, post, TestDb, TestFactory};
    use tideway::testing::fake;

    #[tokio::test]
    async fn test_list_users() {
        let app = create_app();
        let db = setup_test_db().await;

        get(app, "/api/users")
            .execute()
            .await
            .assert_ok()
            .assert_json_path("data", json!([]))
            .await;
    }

    #[tokio::test]
    async fn test_create_user() {
        let app = create_app();
        let db = setup_test_db().await;

        let user_data = json!({
            "email": fake::email(),
            "name": fake::name(),
        });

        post(app, "/api/users")
            .with_json(&user_data)
            .execute()
            .await
            .assert_created()
            .assert_json_path("data.email", user_data["email"].clone())
            .await;
    }

    #[tokio::test]
    async fn test_get_user() {
        let app = create_app();
        let db = setup_test_db().await;

        let user = create_test_user(&db).await;

        get(app, &format!("/api/users/{}", user.id))
            .execute()
            .await
            .assert_ok()
            .assert_json_path("data.id", json!(user.id))
            .await;
    }
}
```

## See Also

- [Testing Examples]../examples/testing_example.rs
- [Validation Guide]./validation.md
- [Error Handling Guide]./error_handling.md