getsentry / responses

A utility for mocking out the Python Requests library.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature request: Allow regex-matching for header values

spreeni opened this issue · comments

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 :)

please provide an example of the expected syntax and use case

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

@spreeni have you considered creating a custom matcher?

@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.

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

@beliaev-maksim can I take this?

@geetptl your contribution will be warmly welcomed!

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

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.