use axum::http::StatusCode;
use axum::response::IntoResponse;
use fbc_starter::error::{AppError, ErrorCategory};
#[test]
fn test_error_category_display() {
assert_eq!(ErrorCategory::Biz.to_string(), "业务错误");
assert_eq!(ErrorCategory::Common.to_string(), "通用错误");
assert_eq!(ErrorCategory::Custom.to_string(), "自定义错误");
}
#[test]
fn test_error_category_equality() {
assert_eq!(ErrorCategory::Biz, ErrorCategory::Biz);
assert_ne!(ErrorCategory::Biz, ErrorCategory::Common);
}
#[test]
fn test_biz_error_factory() {
let err = AppError::biz_error(1001, "用户不存在".to_string());
let msg = err.to_string();
assert!(msg.contains("1001"));
assert!(msg.contains("用户不存在"));
assert!(msg.contains("业务错误"));
}
#[test]
fn test_common_error_factory() {
let err = AppError::common_error(5000, "系统繁忙".to_string());
let msg = err.to_string();
assert!(msg.contains("5000"));
assert!(msg.contains("系统繁忙"));
assert!(msg.contains("通用错误"));
}
#[test]
fn test_customer_error_factory() {
let err = AppError::customer_error(9999, "自定义".to_string());
let msg = err.to_string();
assert!(msg.contains("9999"));
assert!(msg.contains("自定义"));
}
#[tokio::test]
async fn test_categorized_error_returns_ok_status() {
let err = AppError::biz_error(1001, "test".to_string());
let response = err.into_response();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_not_found_error() {
let err = AppError::NotFound;
let response = err.into_response();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn test_unauthorized_error() {
let err = AppError::Unauthorized;
let response = err.into_response();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_forbidden_error() {
let err = AppError::Forbidden;
let response = err.into_response();
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn test_bad_request_error() {
let err = AppError::BadRequest("参数错误".to_string());
let response = err.into_response();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn test_service_unavailable_error() {
let err = AppError::ServiceUnavailable("ms-user".to_string());
let response = err.into_response();
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn test_internal_error() {
let err = AppError::Internal(anyhow::anyhow!("内部错误"));
let response = err.into_response();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[tokio::test]
async fn test_io_error() {
let err = AppError::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "file not found"));
let response = err.into_response();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[tokio::test]
async fn test_addr_parse_error() {
let err: AppError = "not_a_valid_addr".parse::<std::net::SocketAddr>()
.unwrap_err()
.into();
let response = err.into_response();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}