getsentry / responses

A utility for mocking out the Python Requests library.
Apache License 2.0
4.08k stars 348 forks source link

Feature request: Allow regex-matching for header values #651

Closed spreeni closed 10 months ago

spreeni commented 1 year ago

I would like to match the expected format of a request-signature, without necessarily knowing the exact signature hash. To enable this or similar use cases, it would be nice to be able to supply compiled regex for the matchers.header_matcher similar as it is possible for the url.

In general, this could be a nice feature for all other matchers as well.

Example: If I want to for example test that an outgoing request to an external API is supplied with a valid signature and a Bearer token. Currently, I'd implement a custom matcher for this. But it would be nice to test header fields optionally with regex directly in the header_matcher.

responses.get(
    url,
    status=200,
    json=mock_data,
    match=[
        matchers.header_matcher(
            {
                "Message-Signature": re.compile(r'signature="\S+",created=\d+'),
                "Authorization": "Bearer API_TOKEN",
            },
            strict_match=False
        ),
        signature_matcher,
    ],
)

Ps: I love responses, thanks for the great work :)

beliaev-maksim commented 1 year ago

please provide an example of the expected syntax and use case

spreeni commented 1 year ago

I added an example, please see if it helps clarify what I meant.

beliaev-maksim commented 1 year ago

@spreeni have you considered creating a custom matcher?

spreeni commented 12 months ago

@beliaev-maksim Hey sorry, I missed the notification somehow. Yes, I found custom matchers and that is how I implemented it myself now. But maybe as a convenience feature it would be nice to have this functionality directly within the matchers. It could make a fairly common approach more readable.

beliaev-maksim commented 11 months ago

@spreeni can you fire a PR with implementation proposal based on your custom matcher?

geetptl commented 11 months ago

@beliaev-maksim can I take this?

beliaev-maksim commented 11 months ago

@geetptl your contribution will be warmly welcomed!

Please check Contribution section https://github.com/getsentry/responses#contributing

geetptl commented 11 months ago

Think I'll need to add one more test like test_request_matches_headers_regex_strict. Might need a little more work, I'll get back soon.