astrea 0.3.1

A file-system based routing framework for Axum with automatic code generation
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! 全面测试 Error 模块的错误处理功能

use anyhow::anyhow;
use astrea::error::{Result, RouteError};
use axum::http::StatusCode;
use axum::response::IntoResponse;

// ============================================================================
// 错误创建测试
// ============================================================================

#[test]
fn test_bad_request_error() {
    let error = RouteError::bad_request("Invalid input");

    assert_eq!(error.status_code(), StatusCode::BAD_REQUEST);
    assert_eq!(error.message(), "Invalid input");
}

#[test]
fn test_not_found_error() {
    let error = RouteError::not_found("Resource not found");

    assert_eq!(error.status_code(), StatusCode::NOT_FOUND);
    assert_eq!(error.message(), "Resource not found");
}

#[test]
fn test_unauthorized_error() {
    let error = RouteError::unauthorized("Authentication required");

    assert_eq!(error.status_code(), StatusCode::UNAUTHORIZED);
    assert_eq!(error.message(), "Authentication required");
}

#[test]
fn test_forbidden_error() {
    let error = RouteError::forbidden("Access denied");

    assert_eq!(error.status_code(), StatusCode::FORBIDDEN);
    assert_eq!(error.message(), "Access denied");
}

#[test]
fn test_validation_error() {
    let error = RouteError::validation("Email format is invalid");

    assert_eq!(error.status_code(), StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(error.message(), "Email format is invalid");
}

#[test]
fn test_custom_error() {
    let error = RouteError::custom(StatusCode::IM_A_TEAPOT, "I'm a teapot");

    assert_eq!(error.status_code(), StatusCode::IM_A_TEAPOT);
    assert_eq!(error.message(), "I'm a teapot");
}

// ============================================================================
// 错误变体测试
// ============================================================================

#[test]
fn test_method_not_allowed_error() {
    let error = RouteError::MethodNotAllowed("Only GET is allowed".to_string());

    assert_eq!(error.status_code(), StatusCode::METHOD_NOT_ALLOWED);
    assert!(error.message().contains("Only GET is allowed"));
}

#[test]
fn test_conflict_error() {
    let error = RouteError::Conflict("Resource already exists".to_string());

    assert_eq!(error.status_code(), StatusCode::CONFLICT);
    assert_eq!(error.message(), "Resource already exists");
}

#[test]
fn test_rate_limit_error() {
    let error = RouteError::RateLimit("Too many requests, please try again later".to_string());

    assert_eq!(error.status_code(), StatusCode::TOO_MANY_REQUESTS);
    assert!(error.message().contains("Too many requests"));
}

#[test]
fn test_internal_error_from_anyhow() {
    let anyhow_error = anyhow!("Database connection failed");
    let error = RouteError::Internal(anyhow_error);

    assert_eq!(error.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
    assert!(error.message().contains("Database connection failed"));
}

// ============================================================================
// 错误转换测试
// ============================================================================

#[test]
fn test_error_from_anyhow() {
    let anyhow_error = anyhow!("Something went wrong");
    let route_error: RouteError = anyhow_error.into();

    assert_eq!(route_error.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
}

#[test]
fn test_question_mark_operator_with_anyhow() {
    fn may_fail() -> anyhow::Result<String> {
        Err(anyhow!("Failed operation"))
    }

    fn handler() -> Result<String> {
        let result = may_fail()?; // anyhow::Error 自动转换为 RouteError
        Ok(result)
    }

    let result = handler();
    assert!(result.is_err());

    match result {
        Err(RouteError::Internal(_)) => {
            // 预期的错误类型
        }
        _ => panic!("Expected Internal error"),
    }
}

// ============================================================================
// 错误消息格式化测试
// ============================================================================

#[test]
fn test_error_display_bad_request() {
    let error = RouteError::BadRequest("Test message".to_string());
    let display = format!("{error}");

    assert!(display.contains("Bad request"));
    assert!(display.contains("Test message"));
}

#[test]
fn test_error_display_not_found() {
    let error = RouteError::NotFound("User not found".to_string());
    let display = format!("{error}");

    assert!(display.contains("Not found"));
    assert!(display.contains("User not found"));
}

#[test]
fn test_error_display_custom() {
    let error = RouteError::Custom {
        status: StatusCode::SERVICE_UNAVAILABLE,
        message: "Service temporarily unavailable".to_string(),
    };
    let display = format!("{error}");

    assert!(display.contains("503"));
    assert!(display.contains("Service temporarily unavailable"));
}

// ============================================================================
// IntoResponse 转换测试
// ============================================================================

#[test]
fn test_error_into_response_bad_request() {
    let error = RouteError::bad_request("Invalid data");
    let response = error.into_response();

    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}

#[test]
fn test_error_into_response_not_found() {
    let error = RouteError::not_found("Page not found");
    let response = error.into_response();

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[test]
fn test_error_into_response_unauthorized() {
    let error = RouteError::unauthorized("Login required");
    let response = error.into_response();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[test]
fn test_error_into_response_forbidden() {
    let error = RouteError::forbidden("Insufficient permissions");
    let response = error.into_response();

    assert_eq!(response.status(), StatusCode::FORBIDDEN);
}

#[test]
fn test_error_into_response_validation() {
    let error = RouteError::validation("Field is required");
    let response = error.into_response();

    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[test]
fn test_error_into_response_internal() {
    let error = RouteError::Internal(anyhow!("Internal server error"));
    let response = error.into_response();

    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

#[test]
fn test_error_into_response_custom() {
    let error = RouteError::custom(StatusCode::NOT_IMPLEMENTED, "Feature not implemented");
    let response = error.into_response();

    assert_eq!(response.status(), StatusCode::NOT_IMPLEMENTED);
}

// ============================================================================
// 状态码映射测试
// ============================================================================

#[test]
fn test_status_code_mapping() {
    let test_cases = vec![
        (RouteError::bad_request(""), StatusCode::BAD_REQUEST),
        (RouteError::not_found(""), StatusCode::NOT_FOUND),
        (RouteError::unauthorized(""), StatusCode::UNAUTHORIZED),
        (RouteError::forbidden(""), StatusCode::FORBIDDEN),
        (RouteError::validation(""), StatusCode::UNPROCESSABLE_ENTITY),
        (
            RouteError::MethodNotAllowed(String::new()),
            StatusCode::METHOD_NOT_ALLOWED,
        ),
        (RouteError::Conflict(String::new()), StatusCode::CONFLICT),
        (
            RouteError::RateLimit(String::new()),
            StatusCode::TOO_MANY_REQUESTS,
        ),
        (
            RouteError::Internal(anyhow!("")),
            StatusCode::INTERNAL_SERVER_ERROR,
        ),
    ];

    for (error, expected_status) in test_cases {
        assert_eq!(error.status_code(), expected_status);
    }
}

// ============================================================================
// 错误消息提取测试
// ============================================================================

#[test]
fn test_message_extraction() {
    let errors = vec![
        (
            RouteError::bad_request("Bad request message"),
            "Bad request message",
        ),
        (
            RouteError::not_found("Not found message"),
            "Not found message",
        ),
        (
            RouteError::unauthorized("Unauthorized message"),
            "Unauthorized message",
        ),
        (
            RouteError::forbidden("Forbidden message"),
            "Forbidden message",
        ),
        (
            RouteError::validation("Validation message"),
            "Validation message",
        ),
    ];

    for (error, expected_msg) in errors {
        assert_eq!(error.message(), expected_msg);
    }
}

#[test]
fn test_message_extraction_custom() {
    let error = RouteError::Custom {
        status: StatusCode::PAYMENT_REQUIRED,
        message: "Payment required message".to_string(),
    };

    assert_eq!(error.message(), "Payment required message");
}

// ============================================================================
// Result 类型别名测试
// ============================================================================

#[test]
fn test_result_ok() {
    fn returns_ok() -> Result<i32> {
        Ok(42)
    }

    let result = returns_ok();
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), 42);
}

#[test]
fn test_result_err() {
    fn returns_err() -> Result<i32> {
        Err(RouteError::not_found("Value not found"))
    }

    let result = returns_err();
    assert!(result.is_err());
}

// ============================================================================
// 复杂场景测试
// ============================================================================

#[test]
fn test_error_chain_with_context() {
    fn inner_function() -> anyhow::Result<()> {
        Err(anyhow!("Database query failed"))
    }

    fn outer_function() -> Result<()> {
        inner_function().map_err(|e| RouteError::Internal(anyhow!("Failed to fetch user: {e}")))?;
        Ok(())
    }

    let result = outer_function();
    assert!(result.is_err());

    match result {
        Err(RouteError::Internal(e)) => {
            let msg = e.to_string();
            assert!(msg.contains("Failed to fetch user"));
        }
        _ => panic!("Expected Internal error"),
    }
}

#[test]
fn test_multiple_error_types_in_function() {
    fn complex_handler(valid: bool) -> Result<String> {
        if !valid {
            return Err(RouteError::bad_request("Invalid input"));
        }

        // 模拟可能失败的数据库操作
        let db_result: anyhow::Result<String> = Err(anyhow!("DB error"));
        let data = db_result?;

        Ok(data)
    }

    // 测试验证错误
    let result1 = complex_handler(false);
    assert!(matches!(result1, Err(RouteError::BadRequest(_))));

    // 测试数据库错误
    let result2 = complex_handler(true);
    assert!(matches!(result2, Err(RouteError::Internal(_))));
}

#[test]
fn test_error_with_dynamic_message() {
    let user_id = 12345;
    let error = RouteError::not_found(format!("User with ID {user_id} not found"));

    assert!(error.message().contains("12345"));
    assert!(error.message().contains("User with ID"));
}

#[test]
fn test_error_with_multiline_message() {
    let error = RouteError::validation(
        "Multiple validation errors:\n\
         - Email is required\n\
         - Password must be at least 8 characters\n\
         - Username is already taken",
    );

    let msg = error.message();
    assert!(msg.contains("Email is required"));
    assert!(msg.contains("Password must be at least 8 characters"));
    assert!(msg.contains("Username is already taken"));
}

// ============================================================================
// 错误构造器模式测试
// ============================================================================

#[test]
fn test_error_builder_pattern_bad_request() {
    let error = RouteError::bad_request("Test");
    assert_eq!(error.status_code(), StatusCode::BAD_REQUEST);
}

#[test]
fn test_error_builder_pattern_all_variants() {
    let errors = vec![
        RouteError::bad_request("msg"),
        RouteError::not_found("msg"),
        RouteError::unauthorized("msg"),
        RouteError::forbidden("msg"),
        RouteError::validation("msg"),
        RouteError::custom(StatusCode::OK, "msg"),
    ];

    for error in errors {
        // 确保所有构造器都正常工作
        assert!(!error.message().is_empty());
    }
}

// ============================================================================
// 特殊字符和编码测试
// ============================================================================

#[test]
fn test_error_with_unicode_message() {
    let error = RouteError::bad_request("错误:用户名包含非法字符 🚫");

    assert!(error.message().contains("错误"));
    assert!(error.message().contains("🚫"));
}

#[test]
fn test_error_with_quotes_in_message() {
    let error = RouteError::bad_request(r#"Invalid JSON: expected "name" field"#);

    assert!(error.message().contains("expected"));
    assert!(error.message().contains("name"));
}

#[test]
fn test_error_empty_message() {
    let error = RouteError::bad_request("");

    assert_eq!(error.message(), "");
    assert_eq!(error.status_code(), StatusCode::BAD_REQUEST);
}

// ============================================================================
// 错误调试表示测试
// ============================================================================

#[test]
fn test_error_debug_format() {
    let error = RouteError::bad_request("Debug test");
    let debug_str = format!("{error:?}");

    assert!(debug_str.contains("BadRequest"));
    assert!(debug_str.contains("Debug test"));
}

#[test]
fn test_error_debug_format_internal() {
    let error = RouteError::Internal(anyhow!("Internal debug test"));
    let debug_str = format!("{error:?}");

    assert!(debug_str.contains("Internal"));
}

// ============================================================================
// 真实使用场景模拟
// ============================================================================

#[test]
fn test_authentication_scenario() {
    fn check_auth(token: Option<&str>) -> Result<String> {
        let token = token.ok_or_else(|| RouteError::unauthorized("Missing token"))?;

        if token != "valid_token" {
            return Err(RouteError::unauthorized("Invalid token"));
        }

        Ok("user123".to_string())
    }

    // 无 token
    assert!(matches!(check_auth(None), Err(RouteError::Unauthorized(_))));

    // 无效 token
    assert!(matches!(
        check_auth(Some("bad_token")),
        Err(RouteError::Unauthorized(_))
    ));

    // 有效 token
    assert!(check_auth(Some("valid_token")).is_ok());
}

#[test]
fn test_permission_check_scenario() {
    fn check_permission(user_role: &str, required_role: &str) -> Result<()> {
        if user_role != required_role {
            return Err(RouteError::forbidden(format!(
                "Requires {required_role} role, but user has {user_role} role"
            )));
        }
        Ok(())
    }

    // 权限不足
    let result = check_permission("user", "admin");
    assert!(result.is_err());
    match result {
        Err(RouteError::Forbidden(msg)) => {
            assert!(msg.contains("admin"));
            assert!(msg.contains("user"));
        }
        _ => panic!("Expected Forbidden error"),
    }

    // 权限匹配
    assert!(check_permission("admin", "admin").is_ok());
}

#[test]
fn test_resource_conflict_scenario() {
    fn create_user(username: &str, existing_users: &[&str]) -> Result<()> {
        if existing_users.contains(&username) {
            return Err(RouteError::Conflict(format!(
                "Username '{username}' is already taken"
            )));
        }
        Ok(())
    }

    let users = vec!["alice", "bob"];

    // 用户名冲突
    let result = create_user("alice", &users);
    assert!(matches!(result, Err(RouteError::Conflict(_))));

    // 用户名可用
    assert!(create_user("charlie", &users).is_ok());
}