1

I want to test my upload route here. I have one tests that calls this route via the rocket test client but I always get Status { code: 422, reason: "Unprocessable Entity" } as response.

However, I cannot figure out what is wrong with my request body.

Also if there is another way to test multipart/data-form, it is really welcome.

The test fails but when running the application I can successfully call the upload route, my curl command is: curl -X POST -H "Accept: application/json" -F file=@/home/username/Downloads/example.jpg -F id="1588a509-3517-49f2-9dea-1791c2e99db9" -F allowed_file_types="image/jpeg" http://localhost:8000/upload

I also run curl with the additional params --trace-ascii - and comapred the requests but I could not find any difference which causes the 422 response during the tests but works when using curl.

main.rs

#[macro_use] extern crate rocket;

use rocket::data::TempFile;
use rocket::form::Form;
use rocket_contrib::json::{json, JsonValue};
use rocket_contrib::uuid::Uuid;

#[derive(FromForm)]
pub struct FileUploadForm<'f> {
    id: Uuid,
    #[field(validate = len(1..))]
    allowed_file_types: Vec<String>,
    file: TempFile<'f>,
}

#[post("/upload", data = "<form>")]
pub async fn upload(mut form: Form<FileUploadForm<'_>>) -> JsonValue {
    json!({"status": "ok"})
}

fn rocket() -> rocket::Rocket {
    let rocket = rocket::ignite();

    rocket
        .mount("/", routes![upload])
}

#[rocket::main]
async fn main() {
    rocket()
        .launch()
        .await;
}

#[cfg(test)]
mod tests {
    extern crate image;

    use super::*;

    use std::str;
    use rocket::local::blocking::Client;
    use rocket::http::{Status, Header};
    use std::{env, io};
    use std::fs::File;
    use std::io::{Write, Read};
    use std::path::PathBuf;
    use self::image::RgbImage;


    fn create_image(file_name: &str) -> PathBuf {
        let path_buf = env::temp_dir().join(file_name);

        let imgbuf: RgbImage= image::ImageBuffer::new(256, 256);
        imgbuf.save(path_buf.as_path()).unwrap();

        path_buf
    }

    fn image_data(boundary: &str) -> io::Result<Vec<u8>> {
        // https://stackoverflow.com/questions/51397872/how-to-post-an-image-using-multipart-form-data-with-hyper
        // https://golangbyexample.com/multipart-form-data-content-type-golang/
        let mut data = Vec::new();

        // start
        write!(data, "--{}\r\n", boundary)?;

        // image data
        write!(data, "Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n")?;
        write!(data, "Content-Type: image/jpeg\r\n")?;
        write!(data, "\r\n")?;

        let path_buf = create_image("image.jpg");
        let mut f = File::open(path_buf.as_path())?;
        f.read_to_end(&mut data)?;
        write!(data, "\r\n")?;
        
        // id
        write!(data, "--{}\r\n", boundary)?;
        write!(data, "Content-Disposition: form-data; name=\"id\"\r\n")?;
        write!(data, "\r\n")?;

        write!(data, "1588a509-3517-49f2-9dea-1791c2e99db9")?;

        // allowed_file_types
        write!(data, "--{}\r\n", boundary)?;
        write!(data, "Content-Disposition: form-data; name=\"allowed_file_types\"\r\n")?;
        write!(data, "\r\n")?;

        write!(data, "image/jpeg")?;
        write!(data, "--{}\r\n", boundary)?;

        // end
        write!(data, "--{}--\r\n", boundary)?;

        Ok(data)
    }

    #[test]
    fn upload_file() {
        const BOUNDARY: &str = "--------------------------------XYZ";

        let client = Client::tracked(rocket()).expect("valid rocket instance");
        let accept = Header::new("Accept", "application/json");
        let content_type = Header::new("Content-Type", format!("multipart/form-data; boundary={}", BOUNDARY));

        let response = client
            .post("/upload")
            .header(content_type)
            .header(accept)
            .body(image_data(BOUNDARY).unwrap())
            .dispatch();

        assert_eq!(response.status(), Status::Ok);
    }
}

Cargo.toml

[package]
name = "example"
version = "0.1.0"
edition = "2018"

[dependencies]
rocket = { git = "https://github.com/SergioBenitez/Rocket", version = "0.5.0-dev" }
image = { version = "^0"}

[dependencies.rocket_contrib]
git = "https://github.com/SergioBenitez/Rocket"
version = "0.5.0-dev"
default-features = false
features = ["json", "uuid"]

Greeneco
  • 691
  • 2
  • 8
  • 23

1 Answers1

0

I was missing one new line after the id part, the correct code would be the following. I have commented the one line that caused the error and another line where I have add a boundary that was not necessary.

#[macro_use] extern crate rocket;

use rocket::data::TempFile;
use rocket::form::Form;
use rocket_contrib::json::{json, JsonValue};
use rocket_contrib::uuid::Uuid;

#[derive(FromForm)]
pub struct FileUploadForm<'f> {
    id: Uuid,
    #[field(validate = len(1..))]
    allowed_file_types: Vec<String>,
    file: TempFile<'f>,
}

#[post("/upload", data = "<form>")]
pub async fn upload(mut form: Form<FileUploadForm<'_>>) -> JsonValue {
    json!({"status": "ok"})
}

fn rocket() -> rocket::Rocket {
    let rocket = rocket::ignite();

    rocket
        .mount("/", routes![upload])
}

#[rocket::main]
async fn main() {
    rocket()
        .launch()
        .await;
}

#[cfg(test)]
mod tests {
    extern crate image;

    use super::*;

    use std::str;
    use rocket::local::blocking::Client;
    use rocket::http::{Status, Header};
    use std::{env, io};
    use std::fs::File;
    use std::io::{Write, Read};
    use std::path::PathBuf;
    use self::image::RgbImage;


    fn create_image(file_name: &str) -> PathBuf {
        let path_buf = env::temp_dir().join(file_name);

        let imgbuf: RgbImage= image::ImageBuffer::new(256, 256);
        imgbuf.save(path_buf.as_path()).unwrap();

        path_buf
    }

    fn image_data(boundary: &str) -> io::Result<Vec<u8>> {
        // https://stackoverflow.com/questions/51397872/how-to-post-an-image-using-multipart-form-data-with-hyper
        // https://golangbyexample.com/multipart-form-data-content-type-golang/
        let mut data = Vec::new();

        // start
        write!(data, "--{}\r\n", boundary)?;

        // image data
        write!(data, "Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n")?;
        write!(data, "Content-Type: image/jpeg\r\n")?;
        write!(data, "\r\n")?;

        let path_buf = create_image("image.jpg");
        let mut f = File::open(path_buf.as_path())?;
        f.read_to_end(&mut data)?;
        write!(data, "\r\n")?;

        write!(data, "--{}\r\n", boundary)?;
        
        // id
        write!(data, "Content-Disposition: form-data; name=\"id\"\r\n")?;
        write!(data, "\r\n")?;

        write!(data, "1588a509-3517-49f2-9dea-1791c2e99db9")?;
        write!(data, "\r\n")?;  // I was missing this

        // allowed_file_types
        write!(data, "--{}\r\n", boundary)?;
        write!(data, "Content-Disposition: form-data; name=\"allowed_file_types\"\r\n")?;
        write!(data, "\r\n")?;

        write!(data, "image/jpeg")?;
        write!(data, "\r\n")?;  // No boundary needed here, however did not cause an error

        // end
        write!(data, "--{}--\r\n", boundary)?;

        Ok(data)
    }

    #[test]
    fn upload_file() {
        const BOUNDARY: &str = "--------------------------------XYZ";

        let client = Client::tracked(rocket()).expect("valid rocket instance");
        let accept = Header::new("Accept", "application/json");
        let content_type = Header::new("Content-Type", format!("multipart/form-data; boundary={}", BOUNDARY));

        let response = client
            .post("/upload")
            .header(content_type)
            .header(accept)
            .body(image_data(BOUNDARY).unwrap())
            .dispatch();

        assert_eq!(response.status(), Status::Ok);
    }
}
Greeneco
  • 691
  • 2
  • 8
  • 23