lipanski / mockito

HTTP mocking for Rust!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

support read request info in `body_fn`

s97712 opened this issue · comments

commented

support read request info in body_fn, then we can create different responses based on request info

mock("GET", Matcher::Regex("/hello/.*".to_string()))
        .with_body_from_fn(|request_info, write| {
            let word = extract_word(request_info.path);
            write!(write, "hello {}", word)
        });

@s97712 as mentioned in #95, I'm a bit sceptical about exposing the request object at the moment or in the near future. I also think this would make the interface a bit too complex.

on the other hand, did you have a look at all the available matchers and ways to match the request parts? what exactly are you missing there? maybe there's some other way to solve your problem that doesn't involve exposing the request.

Maybe a first step could be to expose the URL (as String) of the request?

mock("GET", Matcher::Regex("/hello/.*".to_string()))
        .with_body_with_url_from_fn(|request_url, write| {
            let word = some_function_to_process_the_url(request_url);
            write!(write, "hello {}", word)
        });

My use-case is that my code has the timestamp in the request (URL contains "&time=13541321") and this timestamp needs to be in the json response as well. Obviously I can't make matchers for any possible timestamps. I can hack around this e.g. by fixing the timestamp in production code but it'd be cleaner if the mock could be a bit more realistic.

@s97712 @dorak88783 took a while but this was added in #162 and released in 0.32.4.

note that it exposes a dedicated method Mock::with_body_from_request rather than adding to Mock::with_body_from_fn, which still uses chunked transfer encoding.