alexliesenfeld / httpmock

HTTP mocking library for Rust
https://httpmock.rs
MIT License
488 stars 45 forks source link

Accessing the request body in Then #103

Open nastynaz opened 7 months ago

nastynaz commented 7 months ago

Is it possible to access the passed-in request body in Then? I'd like for the mock server to return a response based on the input. e.g:

let mock = server.mock(|when, then| {
    when.method(POST)
    // below has extra fields such as 'client_order_id' which I don't want to validate
        .json_body_partial(r#"{
            "price":"23222.5",
            "size":"0.23",
        }"#);
    then.status(200).json_body(serde_json::json!({
        "data": {
             /* would be useful if this could come from the request */
            "client_order_id": "would_be_nice_to_access_this"
        }
    }));
});

Is this already possible? If not I'd be happy to attempt an implementation if it's not too difficult.

nastynaz commented 7 months ago

I made this PR which allows for the request to be accessed when writing a .then response.

It's for my own use so I haven't added comments or tests, but if people find it useful I'm happy to edit it: https://github.com/alexliesenfeld/httpmock/pull/104

alexliesenfeld commented 7 months ago

Thanks for reaching out! It is indeed an interesting idea.

There is something similar for the request already (see here). It allows to dynamically evaluate if a request matches certain criteria at runtime. A dynamic body generator would probably look very similar.

Note though that httpmock also allows you to run a standalone mock server to which tests can connect to. Since it's not possible to transfer functions over the network, such dynamically defined response body generator would not work in standalone mode. A body generator can - just like matches - be disabled per cargo feature.

Thanks for your PR. I think it's good to wait for this feature at least for the next release to avoid having different solutions for the same problem.

nastynaz commented 7 months ago

@alexliesenfeld that makes sense. I'm happy to wait as I've managed to get it running for my own use case.

I noticed that MockMatcherFunction is defined as an fn and not an Fn, was this by design? In my PR I changed it to be Fn so that I .matches() could accept closures which did other things like send the request data elsewhere.