alexliesenfeld / httpmock

HTTP mocking library for Rust.
MIT License
435 stars 40 forks source link

feat: Add semantic "and" methods to `When` and `Then` structs #74

Closed the-wondersmith closed 1 year ago

the-wondersmith commented 1 year ago

PR adds an "and" method to the When and Then structs. The purpose of the new methods is to preserve the intuitively legible semantics of the When and Then structs while allowing users to abstract / encapsulate common or repeated operations into discrete functions.

From the docstrings of the new When::and method:

// Assuming an encapsulating function like:

fn is_authorized_json_post_request(when: When) -> When {
    when.method(httpmock::Method::POST)
        .header("authorization", "SOME API KEY")
        .header("content-type", "application/json")
}

// It can be applied without breaking the usual `When`
// semantic style. Meaning instead of:
is_authorized_json_post_request(when.json_body_partial(r#"{"key": "value"}"#))

// the `and` method can be used to preserve the
// legibility of the method chain:
 when.query_param("some-param", "some-value")
     .and(is_authorized_json_post_request)
     .json_body_partial(r#"{"key": "value"}"#)

// is still intuitively legible as "when some query
// parameter equals "some-value", the request is an
// authorized POST request, and the request body
// is the literal JSON object `{"key": "value"}`.
the-wondersmith commented 1 year ago

@alexliesenfeld Shameless self bump 😅

alexliesenfeld commented 1 year ago

@the-wondersmith This looks very interesting, thanks! I'll have a deeper look into it and get back to you with some feedback!