lipanski / mockito

HTTP mocking for Rust!
MIT License
695 stars 59 forks source link

support read request info in `body_fn` #115

Closed s97712 closed 1 year ago

s97712 commented 4 years ago

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)
        });
lipanski commented 4 years ago

@s97712 as mentioned in https://github.com/lipanski/mockito/issues/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.

dorak88783 commented 3 years ago

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.

lipanski commented 1 year ago

@s97712 @dorak88783 took a while but this was added in https://github.com/lipanski/mockito/pull/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.