Rocket icon indicating copy to clipboard operation
Rocket copied to clipboard

Add `LocalForm` to make testing with form data more ergonomic

Open ELD opened this issue 4 years ago • 2 comments

This adds the testing improvement described in #1591.

The transformation of the form fields into the resulting body data is a bit clumsy and could probably use some improvement/cleanup. I believe the multipart form translation is correct, but there's only one, narrow test case that confirms it works as expected.

Additionally, I was unable to get something like this to work without ugly ergonomics:

let client = Client::tracked(rocket).unwrap();
let response = client.post("/")
    .form(&[("field", "value"), ("is it", "a cat?")])
    .dispatch();

I might be missing something, but attempting to do something like this:

impl<'v, F: Into<ValueField<'v>>, I: Iterator<Item = F>> From<I> for LocalForm { /* .. */ }

requires the caller to call the method in a way similar to this:

client.post("/")
    .form(&[("field", "value"), ("is it", "a cat?")].iter().cloned());

due to a slice reference not being coerced into an iterator and when it is iterated over, it returns &(&str, &str). ValueField doesn't have a present From<..> impl for &(&str, &str), so this is not possible.

Also, docs are likely not complete/elaborate enough at this stage, but an attempt at documenting relevant methods/structs was made in this first cut.

Please pick it apart so I can make the implementation better! :)

ELD avatar Apr 11 '21 01:04 ELD

@SergioBenitez This should be ready for another pass.

I updated the style to better match Rocket's. I think it's mostly there, but there might be some minor style issues remaining.

I changed the writing of the body data to a single Vec<u8> with the write! macro. There's a couple places where I call format!. There's probably a better way than what I did, so any help there would be great!

Error handling is a little weird as it currently silently outputs an empty buffer if the writing failed for some reason. This probably isn't a good user experience because an error would result in empty body data for the form request. Any pointers on how to do better error handling would be great!

ELD avatar Jun 05 '21 17:06 ELD

Has anyone had a chance to look at this yet?

eadgbear avatar Aug 31 '21 08:08 eadgbear