By Guest
Unnamed Paste
Auto Detect
2.21 KiB
19
one month ago
#[cfg(test)]
mod tests {
// Need this for derive generated code
use crate::{self as actix_multipart_extract, File, Multipart};
use actix_multipart_extract_derive::MultipartForm;
use actix_web::{
body::{self, BoxBody},
http::header::ContentType,
test, web, App, HttpRequest, HttpResponse,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
// In realistic scenarios you shouldn't make forms serializable but its convenient for testing.
#[derive(Deserialize, Serialize, MultipartForm)]
#[serde(rename_all = "camelCase")]
struct TestForm {
some_string: String,
some_bool: bool,
#[multipart(max_size = 5mb)]
some_file: File,
}
async fn get_body(body: BoxBody) -> String {
std::str::from_utf8(&body::to_bytes(body).await.unwrap())
.unwrap()
.to_string()
}
#[actix_web::test]
async fn test_no_data() {
let app = test::init_service(App::new().route(
"/",
web::get().to(|_: Multipart<TestForm>| async { HttpResponse::Ok() }),
))
.await;
let req = test::TestRequest::default()
.insert_header(ContentType::plaintext())
.to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_client_error());
assert!(
get_body(resp.into_body()).await
== "Error while parsing field: missing field `someString`"
);
}
#[actix_web::test]
async fn test_with_data() {
let app = test::init_service(
App::new().route(
"/",
web::get()
.to(|form: Multipart<TestForm>| async { HttpResponse::Ok().json(form.into()) }),
),
)
.await;
let req = test::TestRequest::default().set_form(data).to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_client_error());
assert!(
get_body(resp.into_body()).await
== "Error while parsing field: missing field `someString`"
);
}
}