fmt
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
use actix_web::{test, web, App, HttpResponse};
|
||||
use actix_web::{App, HttpResponse, test, web};
|
||||
|
||||
/// Простой тест health check
|
||||
#[actix_web::test]
|
||||
@@ -329,25 +329,37 @@ async fn test_thumbnail_path_parsing() {
|
||||
if path.is_empty() {
|
||||
return ("".to_string(), 0, "".to_string());
|
||||
}
|
||||
|
||||
|
||||
// Ищем последний underscore перед расширением
|
||||
let dot_pos = path.rfind('.');
|
||||
let name_part = if let Some(pos) = dot_pos { &path[..pos] } else { path };
|
||||
|
||||
let name_part = if let Some(pos) = dot_pos {
|
||||
&path[..pos]
|
||||
} else {
|
||||
path
|
||||
};
|
||||
|
||||
// Ищем underscore для ширины
|
||||
if let Some(underscore_pos) = name_part.rfind('_') {
|
||||
let base = name_part[..underscore_pos].to_string();
|
||||
let width_part = &name_part[underscore_pos + 1..];
|
||||
|
||||
|
||||
if let Ok(width) = width_part.parse::<u32>() {
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
return (base, width, ext);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Если не нашли ширину, возвращаем как есть
|
||||
let base = name_part.to_string();
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
(base, 0, ext)
|
||||
}
|
||||
|
||||
@@ -356,7 +368,10 @@ async fn test_thumbnail_path_parsing() {
|
||||
("image_300.jpg", ("image", 300, "jpg")),
|
||||
("photo_800.png", ("photo", 800, "png")),
|
||||
("document.pdf", ("document", 0, "pdf")),
|
||||
("file_with_underscore_but_no_width.gif", ("file_with_underscore_but_no_width", 0, "gif")),
|
||||
(
|
||||
"file_with_underscore_but_no_width.gif",
|
||||
("file_with_underscore_but_no_width", 0, "gif"),
|
||||
),
|
||||
("unsafe_1920x.jpg", ("unsafe_1920x", 0, "jpg")),
|
||||
("unsafe_1920x.png", ("unsafe_1920x", 0, "png")),
|
||||
("unsafe_1920x", ("unsafe_1920x", 0, "")),
|
||||
@@ -386,7 +401,7 @@ async fn test_image_format_detection() {
|
||||
"gif" => Ok(image::ImageFormat::Gif),
|
||||
"webp" => Ok(image::ImageFormat::WebP),
|
||||
"heic" | "heif" | "tiff" | "tif" => Ok(image::ImageFormat::Jpeg),
|
||||
_ => Err(())
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
use image::ImageFormat;
|
||||
@@ -430,14 +445,14 @@ async fn test_find_closest_width() {
|
||||
// Мокаем функцию find_closest_width для тестов
|
||||
fn find_closest_width(requested: u32) -> u32 {
|
||||
let available_widths = vec![100, 150, 200, 300, 400, 500, 600, 800];
|
||||
|
||||
|
||||
if available_widths.contains(&requested) {
|
||||
return requested;
|
||||
}
|
||||
|
||||
|
||||
let mut closest = available_widths[0];
|
||||
let mut min_diff = (requested as i32 - closest as i32).abs();
|
||||
|
||||
|
||||
for &width in &available_widths[1..] {
|
||||
let diff = (requested as i32 - width as i32).abs();
|
||||
if diff < min_diff {
|
||||
@@ -445,28 +460,28 @@ async fn test_find_closest_width() {
|
||||
closest = width;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
closest
|
||||
}
|
||||
|
||||
let test_cases = vec![
|
||||
(100, 100), // Точное совпадение
|
||||
(150, 150), // Точное совпадение
|
||||
(200, 200), // Точное совпадение
|
||||
(300, 300), // Точное совпадение
|
||||
(400, 400), // Точное совпадение
|
||||
(500, 500), // Точное совпадение
|
||||
(600, 600), // Точное совпадение
|
||||
(800, 800), // Точное совпадение
|
||||
(120, 100), // Ближайшее к 100 (разница 20)
|
||||
(180, 200), // Ближайшее к 200 (разница 20)
|
||||
(250, 200), // Ближайшее к 200 (разница 50)
|
||||
(350, 300), // Ближайшее к 300 (разница 50)
|
||||
(450, 400), // Ближайшее к 400 (разница 50)
|
||||
(550, 500), // Ближайшее к 500 (разница 50)
|
||||
(700, 600), // Ближайшее к 600 (разница 100)
|
||||
(1000, 800), // Больше максимального - возвращаем максимальный
|
||||
(2000, 800), // Больше максимального - возвращаем максимальный
|
||||
(100, 100), // Точное совпадение
|
||||
(150, 150), // Точное совпадение
|
||||
(200, 200), // Точное совпадение
|
||||
(300, 300), // Точное совпадение
|
||||
(400, 400), // Точное совпадение
|
||||
(500, 500), // Точное совпадение
|
||||
(600, 600), // Точное совпадение
|
||||
(800, 800), // Точное совпадение
|
||||
(120, 100), // Ближайшее к 100 (разница 20)
|
||||
(180, 200), // Ближайшее к 200 (разница 20)
|
||||
(250, 200), // Ближайшее к 200 (разница 50)
|
||||
(350, 300), // Ближайшее к 300 (разница 50)
|
||||
(450, 400), // Ближайшее к 400 (разница 50)
|
||||
(550, 500), // Ближайшее к 500 (разница 50)
|
||||
(700, 600), // Ближайшее к 600 (разница 100)
|
||||
(1000, 800), // Больше максимального - возвращаем максимальный
|
||||
(2000, 800), // Больше максимального - возвращаем максимальный
|
||||
];
|
||||
|
||||
for (requested, expected) in test_cases {
|
||||
@@ -490,10 +505,10 @@ async fn test_lookup_functions() {
|
||||
"gif" => Some("image/gif"),
|
||||
"webp" => Some("image/webp"),
|
||||
"mp4" => Some("video/mp4"),
|
||||
_ => None
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn find_file_by_pattern(_pattern: &str) -> Option<String> {
|
||||
Some("test_file.jpg".to_string())
|
||||
}
|
||||
@@ -531,12 +546,18 @@ async fn test_s3_utils_functions() {
|
||||
async fn get_s3_filelist(_bucket: &str) -> Result<Vec<String>, Box<dyn std::error::Error>> {
|
||||
Ok(vec!["file1.jpg".to_string(), "file2.png".to_string()])
|
||||
}
|
||||
|
||||
async fn check_file_exists(_bucket: &str, _key: &str) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
|
||||
async fn check_file_exists(
|
||||
_bucket: &str,
|
||||
_key: &str,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn load_file_from_s3(_bucket: &str, _key: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
|
||||
|
||||
async fn load_file_from_s3(
|
||||
_bucket: &str,
|
||||
_key: &str,
|
||||
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
|
||||
Ok(b"fake file content".to_vec())
|
||||
}
|
||||
|
||||
@@ -549,15 +570,18 @@ async fn test_s3_utils_functions() {
|
||||
#[test]
|
||||
async fn test_overlay_functions() {
|
||||
// Мокаем функцию generate_overlay для тестов
|
||||
async fn generate_overlay(shout_id: &str, image_data: actix_web::web::Bytes) -> Result<actix_web::web::Bytes, Box<dyn std::error::Error>> {
|
||||
async fn generate_overlay(
|
||||
shout_id: &str,
|
||||
image_data: actix_web::web::Bytes,
|
||||
) -> Result<actix_web::web::Bytes, Box<dyn std::error::Error>> {
|
||||
if image_data.is_empty() {
|
||||
return Err("Empty image data".into());
|
||||
}
|
||||
|
||||
|
||||
if shout_id == "invalid_id" {
|
||||
return Ok(image_data);
|
||||
}
|
||||
|
||||
|
||||
Ok(image_data)
|
||||
}
|
||||
use actix_web::web::Bytes;
|
||||
@@ -565,16 +589,19 @@ async fn test_overlay_functions() {
|
||||
// Тестируем с пустыми данными
|
||||
let empty_bytes = Bytes::from(vec![]);
|
||||
let result = generate_overlay("123", empty_bytes).await;
|
||||
|
||||
|
||||
// Должен вернуть ошибку при попытке загрузить изображение из пустых данных
|
||||
assert!(result.is_err(), "Should fail with empty image data");
|
||||
|
||||
// Тестируем с некорректным shout_id
|
||||
let test_bytes = Bytes::from(b"fake image data".to_vec());
|
||||
let result = generate_overlay("invalid_id", test_bytes).await;
|
||||
|
||||
|
||||
// Должен вернуть оригинальные данные при ошибке получения shout
|
||||
assert!(result.is_ok(), "Should return original data when shout fetch fails");
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"Should return original data when shout fetch fails"
|
||||
);
|
||||
}
|
||||
|
||||
/// Тест для проверки функций core.rs
|
||||
@@ -607,8 +634,11 @@ async fn test_auth_functions() {
|
||||
}
|
||||
Ok(123)
|
||||
}
|
||||
|
||||
async fn user_added_file(_user_id: u32, _filename: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
async fn user_added_file(
|
||||
_user_id: u32,
|
||||
_filename: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -644,23 +674,23 @@ async fn test_handlers_functions() {
|
||||
async fn get_quota_handler() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().json(serde_json::json!({"quota": 1024}))
|
||||
}
|
||||
|
||||
|
||||
async fn increase_quota_handler() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().json(serde_json::json!({"status": "increased"}))
|
||||
}
|
||||
|
||||
|
||||
async fn set_quota_handler() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().json(serde_json::json!({"status": "set"}))
|
||||
}
|
||||
|
||||
|
||||
async fn proxy_handler() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().body("proxy response")
|
||||
}
|
||||
|
||||
|
||||
async fn serve_file() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().body("file content")
|
||||
}
|
||||
|
||||
|
||||
async fn upload_handler() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().json(serde_json::json!({"status": "uploaded"}))
|
||||
}
|
||||
@@ -679,35 +709,47 @@ async fn test_integration() {
|
||||
if path.is_empty() {
|
||||
return ("".to_string(), 0, "".to_string());
|
||||
}
|
||||
|
||||
|
||||
// Ищем последний underscore перед расширением
|
||||
let dot_pos = path.rfind('.');
|
||||
let name_part = if let Some(pos) = dot_pos { &path[..pos] } else { path };
|
||||
|
||||
let name_part = if let Some(pos) = dot_pos {
|
||||
&path[..pos]
|
||||
} else {
|
||||
path
|
||||
};
|
||||
|
||||
// Ищем underscore для ширины
|
||||
if let Some(underscore_pos) = name_part.rfind('_') {
|
||||
let base = name_part[..underscore_pos].to_string();
|
||||
let width_part = &name_part[underscore_pos + 1..];
|
||||
|
||||
|
||||
if let Ok(width) = width_part.parse::<u32>() {
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
return (base, width, ext);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Если не нашли ширину, возвращаем как есть
|
||||
let base = name_part.to_string();
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
(base, 0, ext)
|
||||
}
|
||||
|
||||
|
||||
fn get_mime_type(ext: &str) -> Option<&'static str> {
|
||||
match ext.to_lowercase().as_str() {
|
||||
"jpg" | "jpeg" => Some("image/jpeg"),
|
||||
"png" => Some("image/png"),
|
||||
"gif" => Some("image/gif"),
|
||||
"webp" => Some("image/webp"),
|
||||
_ => None
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -729,32 +771,44 @@ async fn test_edge_cases() {
|
||||
if path.is_empty() {
|
||||
return ("".to_string(), 0, "".to_string());
|
||||
}
|
||||
|
||||
|
||||
if path == "." || path == ".." {
|
||||
return (path.to_string(), 0, "".to_string());
|
||||
}
|
||||
|
||||
|
||||
// Ищем последний underscore перед расширением
|
||||
let dot_pos = path.rfind('.');
|
||||
let name_part = if let Some(pos) = dot_pos { &path[..pos] } else { path };
|
||||
|
||||
let name_part = if let Some(pos) = dot_pos {
|
||||
&path[..pos]
|
||||
} else {
|
||||
path
|
||||
};
|
||||
|
||||
// Ищем underscore для ширины
|
||||
if let Some(underscore_pos) = name_part.rfind('_') {
|
||||
let base = name_part[..underscore_pos].to_string();
|
||||
let width_part = &name_part[underscore_pos + 1..];
|
||||
|
||||
|
||||
if let Ok(width) = width_part.parse::<u32>() {
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
return (base, width, ext);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Если не нашли ширину, возвращаем как есть
|
||||
let base = name_part.to_string();
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
(base, 0, ext)
|
||||
}
|
||||
|
||||
|
||||
// Тестируем пустые строки
|
||||
assert_eq!(parse_file_path(""), ("".to_string(), 0, "".to_string()));
|
||||
assert_eq!(parse_file_path("."), (".".to_string(), 0, "".to_string()));
|
||||
@@ -779,31 +833,43 @@ async fn test_edge_cases() {
|
||||
#[test]
|
||||
async fn test_parsing_performance() {
|
||||
use std::time::Instant;
|
||||
|
||||
|
||||
// Мокаем функцию parse_file_path для теста производительности
|
||||
fn parse_file_path(path: &str) -> (String, u32, String) {
|
||||
if path.is_empty() {
|
||||
return ("".to_string(), 0, "".to_string());
|
||||
}
|
||||
|
||||
|
||||
// Ищем последний underscore перед расширением
|
||||
let dot_pos = path.rfind('.');
|
||||
let name_part = if let Some(pos) = dot_pos { &path[..pos] } else { path };
|
||||
|
||||
let name_part = if let Some(pos) = dot_pos {
|
||||
&path[..pos]
|
||||
} else {
|
||||
path
|
||||
};
|
||||
|
||||
// Ищем underscore для ширины
|
||||
if let Some(underscore_pos) = name_part.rfind('_') {
|
||||
let base = name_part[..underscore_pos].to_string();
|
||||
let width_part = &name_part[underscore_pos + 1..];
|
||||
|
||||
|
||||
if let Ok(width) = width_part.parse::<u32>() {
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
return (base, width, ext);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Если не нашли ширину, возвращаем как есть
|
||||
let base = name_part.to_string();
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
(base, 0, ext)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use actix_web::{test, web, App, HttpRequest, HttpResponse, Error as ActixError};
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::{App, Error as ActixError, HttpRequest, HttpResponse, test, web};
|
||||
use serde_json::json;
|
||||
|
||||
|
||||
// Мокаем необходимые структуры и функции для тестов
|
||||
|
||||
/// Мок для Redis соединения
|
||||
@@ -36,7 +35,11 @@ impl MockAppState {
|
||||
Ok(1024 * 1024) // 1MB
|
||||
}
|
||||
|
||||
async fn increase_user_quota(&self, _user_id: &str, _additional_bytes: u64) -> Result<u64, actix_web::Error> {
|
||||
async fn increase_user_quota(
|
||||
&self,
|
||||
_user_id: &str,
|
||||
_additional_bytes: u64,
|
||||
) -> Result<u64, actix_web::Error> {
|
||||
Ok(2 * 1024 * 1024) // 2MB
|
||||
}
|
||||
|
||||
@@ -64,12 +67,13 @@ async fn test_get_quota_handler() {
|
||||
async fn get_quota_handler() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().json(serde_json::json!({"quota": 1024}))
|
||||
}
|
||||
|
||||
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/quota", web::get().to(get_quota_handler))
|
||||
).await;
|
||||
.route("/quota", web::get().to(get_quota_handler)),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест без авторизации
|
||||
let req = test::TestRequest::get()
|
||||
@@ -98,12 +102,13 @@ async fn test_increase_quota_handler() {
|
||||
async fn increase_quota_handler() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().json(serde_json::json!({"status": "increased"}))
|
||||
}
|
||||
|
||||
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/quota/increase", web::post().to(increase_quota_handler))
|
||||
).await;
|
||||
.route("/quota/increase", web::post().to(increase_quota_handler)),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест без авторизации
|
||||
let req = test::TestRequest::post()
|
||||
@@ -132,17 +137,16 @@ async fn test_set_quota_handler() {
|
||||
async fn set_quota_handler() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().json(serde_json::json!({"status": "set"}))
|
||||
}
|
||||
|
||||
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/quota/set", web::post().to(set_quota_handler))
|
||||
).await;
|
||||
.route("/quota/set", web::post().to(set_quota_handler)),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест без авторизации
|
||||
let req = test::TestRequest::post()
|
||||
.uri("/quota/set")
|
||||
.to_request();
|
||||
let req = test::TestRequest::post().uri("/quota/set").to_request();
|
||||
|
||||
let resp = test::call_service(&app, req).await;
|
||||
// Мок возвращает успешный ответ даже без авторизации
|
||||
@@ -166,17 +170,16 @@ async fn test_upload_handler() {
|
||||
async fn upload_handler() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().json(serde_json::json!({"status": "uploaded"}))
|
||||
}
|
||||
|
||||
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/", web::post().to(upload_handler))
|
||||
).await;
|
||||
.route("/", web::post().to(upload_handler)),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест без авторизации
|
||||
let req = test::TestRequest::post()
|
||||
.uri("/")
|
||||
.to_request();
|
||||
let req = test::TestRequest::post().uri("/").to_request();
|
||||
|
||||
let resp = test::call_service(&app, req).await;
|
||||
// Мок возвращает успешный ответ даже без авторизации
|
||||
@@ -200,12 +203,13 @@ async fn test_proxy_handler() {
|
||||
async fn proxy_handler() -> actix_web::HttpResponse {
|
||||
actix_web::HttpResponse::Ok().body("proxy response")
|
||||
}
|
||||
|
||||
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/{path:.*}", web::get().to(proxy_handler))
|
||||
).await;
|
||||
.route("/{path:.*}", web::get().to(proxy_handler)),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест с несуществующим файлом
|
||||
let req = test::TestRequest::get()
|
||||
@@ -221,12 +225,16 @@ async fn test_proxy_handler() {
|
||||
#[actix_web::test]
|
||||
async fn test_serve_file() {
|
||||
// Мокаем функцию serve_file
|
||||
async fn serve_file(_path: &str, _app_state: &MockAppState, _user_id: &str) -> Result<actix_web::HttpResponse, actix_web::Error> {
|
||||
async fn serve_file(
|
||||
_path: &str,
|
||||
_app_state: &MockAppState,
|
||||
_user_id: &str,
|
||||
) -> Result<actix_web::HttpResponse, actix_web::Error> {
|
||||
Err(actix_web::error::ErrorNotFound("File not found"))
|
||||
}
|
||||
|
||||
|
||||
let app_state = MockAppState::new();
|
||||
|
||||
|
||||
// Тест с пустым путем
|
||||
let result = serve_file("", &app_state, "").await;
|
||||
assert!(result.is_err());
|
||||
@@ -243,12 +251,16 @@ async fn test_handler_error_handling() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/test", web::get().to(|_req: HttpRequest| async {
|
||||
Err::<HttpResponse, ActixError>(
|
||||
actix_web::error::ErrorInternalServerError("Test error")
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
.route(
|
||||
"/test",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Err::<HttpResponse, ActixError>(actix_web::error::ErrorInternalServerError(
|
||||
"Test error",
|
||||
))
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::get().uri("/test").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
@@ -261,19 +273,21 @@ async fn test_cors_headers() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/test", web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().body("test")
|
||||
)
|
||||
}))
|
||||
.wrap(actix_cors::Cors::default().allow_any_origin())
|
||||
).await;
|
||||
.route(
|
||||
"/test",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().body("test"))
|
||||
}),
|
||||
)
|
||||
.wrap(actix_cors::Cors::default().allow_any_origin()),
|
||||
)
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::get().uri("/test").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
|
||||
|
||||
assert!(resp.status().is_success());
|
||||
|
||||
|
||||
// Проверяем наличие CORS headers
|
||||
let headers = resp.headers();
|
||||
// В тестовой среде CORS headers могут не добавляться автоматически
|
||||
@@ -286,23 +300,26 @@ async fn test_cors_headers() {
|
||||
async fn test_http_methods() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.route("/test", web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().body("GET method")
|
||||
)
|
||||
}))
|
||||
.route("/test", web::post().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().body("POST method")
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
.route(
|
||||
"/test",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().body("GET method"))
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/test",
|
||||
web::post().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().body("POST method"))
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест GET метода
|
||||
let req = test::TestRequest::get().uri("/test").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
assert!(resp.status().is_success());
|
||||
|
||||
|
||||
let body = test::read_body(resp).await;
|
||||
assert_eq!(body, "GET method");
|
||||
|
||||
@@ -310,7 +327,7 @@ async fn test_http_methods() {
|
||||
let req = test::TestRequest::post().uri("/test").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
assert!(resp.status().is_success());
|
||||
|
||||
|
||||
let body = test::read_body(resp).await;
|
||||
assert_eq!(body, "POST method");
|
||||
}
|
||||
@@ -318,23 +335,22 @@ async fn test_http_methods() {
|
||||
/// Тест для проверки query параметров
|
||||
#[actix_web::test]
|
||||
async fn test_query_parameters() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.route("/test", web::get().to(|req: HttpRequest| async move {
|
||||
let query_string = req.query_string().to_string();
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().body(query_string)
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
let app = test::init_service(App::new().route(
|
||||
"/test",
|
||||
web::get().to(|req: HttpRequest| async move {
|
||||
let query_string = req.query_string().to_string();
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().body(query_string))
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::get()
|
||||
.uri("/test?param1=value1¶m2=value2")
|
||||
.to_request();
|
||||
|
||||
|
||||
let resp = test::call_service(&app, req).await;
|
||||
assert!(resp.status().is_success());
|
||||
|
||||
|
||||
let body = test::read_body(resp).await;
|
||||
assert_eq!(body, "param1=value1¶m2=value2");
|
||||
}
|
||||
@@ -342,29 +358,29 @@ async fn test_query_parameters() {
|
||||
/// Тест для проверки headers
|
||||
#[actix_web::test]
|
||||
async fn test_headers() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.route("/test", web::get().to(|req: HttpRequest| async move {
|
||||
let user_agent = req.headers()
|
||||
.get("user-agent")
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().body(user_agent)
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
let app = test::init_service(App::new().route(
|
||||
"/test",
|
||||
web::get().to(|req: HttpRequest| async move {
|
||||
let user_agent = req
|
||||
.headers()
|
||||
.get("user-agent")
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().body(user_agent))
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::get()
|
||||
.uri("/test")
|
||||
.insert_header(("user-agent", "test-agent"))
|
||||
.to_request();
|
||||
|
||||
|
||||
let resp = test::call_service(&app, req).await;
|
||||
assert!(resp.status().is_success());
|
||||
|
||||
|
||||
let body = test::read_body(resp).await;
|
||||
assert_eq!(body, "test-agent");
|
||||
}
|
||||
@@ -372,31 +388,30 @@ async fn test_headers() {
|
||||
/// Тест для проверки JSON responses
|
||||
#[actix_web::test]
|
||||
async fn test_json_responses() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.route("/test", web::get().to(|_req: HttpRequest| async {
|
||||
let data = json!({
|
||||
"status": "success",
|
||||
"message": "test message",
|
||||
"data": {
|
||||
"id": 123,
|
||||
"name": "test"
|
||||
}
|
||||
});
|
||||
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().json(data)
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
let app = test::init_service(App::new().route(
|
||||
"/test",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
let data = json!({
|
||||
"status": "success",
|
||||
"message": "test message",
|
||||
"data": {
|
||||
"id": 123,
|
||||
"name": "test"
|
||||
}
|
||||
});
|
||||
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().json(data))
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::get().uri("/test").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
assert!(resp.status().is_success());
|
||||
|
||||
|
||||
let body = test::read_body(resp).await;
|
||||
let response_data: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
|
||||
|
||||
assert_eq!(response_data["status"], "success");
|
||||
assert_eq!(response_data["message"], "test message");
|
||||
assert_eq!(response_data["data"]["id"], 123);
|
||||
@@ -408,41 +423,54 @@ async fn test_json_responses() {
|
||||
async fn test_content_types() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.route("/text", web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/plain")
|
||||
.body("plain text")
|
||||
)
|
||||
}))
|
||||
.route("/html", web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/html")
|
||||
.body("<html><body>test</body></html>")
|
||||
)
|
||||
}))
|
||||
.route("/json", web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.json(json!({"test": "data"}))
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
.route(
|
||||
"/text",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/plain")
|
||||
.body("plain text"),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/html",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/html")
|
||||
.body("<html><body>test</body></html>"),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/json",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.json(json!({"test": "data"})),
|
||||
)
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест text/plain
|
||||
let req = test::TestRequest::get().uri("/text").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
assert_eq!(resp.headers().get("content-type").unwrap(), "text/plain");
|
||||
|
||||
|
||||
// Тест text/html
|
||||
let req = test::TestRequest::get().uri("/html").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
assert_eq!(resp.headers().get("content-type").unwrap(), "text/html");
|
||||
|
||||
|
||||
// Тест application/json
|
||||
let req = test::TestRequest::get().uri("/json").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
assert_eq!(resp.headers().get("content-type").unwrap(), "application/json");
|
||||
assert_eq!(
|
||||
resp.headers().get("content-type").unwrap(),
|
||||
"application/json"
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user