lundberg / respx

Mock HTTPX with awesome request patterns and response side effects 🦋
https://lundberg.github.io/respx
BSD 3-Clause "New" or "Revised" License
602 stars 39 forks source link

Feature request: Add auth pattern #245

Open stinovlas opened 1 year ago

stinovlas commented 1 year ago

It would be nice to have an auth pattern. I'm writing an app using a Basic auth protected API and I want to test the calls. Right now, I need to do this:

respx.post(
    "https://example.com/",
    headers={"Authorization": "Basic " + b64encode(b"rimmer:Gazpacho!").decode()},
).mock(...)

This works, but is quite ugly and I'd prefer to have a direct auth pattern:

respx.post(
    "https://example.com/",
    auth=("rimmer", "Gazpacho!"),
).mock(...)

This would mimick the auth argument of httpx.request(), similarly to json and similar patterns.

Note: httpx also supports Digest authentication, so respx should probably also cover that usecase, if implemented.

lundberg commented 11 months ago

Thanks for the suggestion @stinovlas. This would definitely be a suited argument since httpx.post also has it.

Though, I'm not sure what the value/api should look like to be extensible enough, allowing all kind of auth methods.

I find myself quite often implementing custom httpx.Auth classes, and that would then require respx auth pattern matching to handle them as well some how 🤔.

If you have many tests and this becomes repetitive, an other solution would be to have one unit test that asserts that the authorization header is properly sent with your client, e.g. by using respx_mock.calls.last.request.headers. And then all the other tests could ignore mocking the auth header, and just match on url.

stinovlas commented 11 months ago

Of course, or I could write a wrapper to check the headers with each call.

To be honest, I don't have much experience with httpx or respx yet, so I'm not sure how complicated this actually is. I did use requests quite a lot, but now I needed some async alternative so I went down the rabbit hole. I stumbled onto this in one of my first httpx tests and since I didn't find an issue for that, I created one. Maybe it would be sufficient to support auth mechanisms included in httpx for starters? But that's up to you as an author of the library to decide :slightly_smiling_face:.

lundberg commented 6 months ago

I've looked into this now and the only reasonable and doable pattern would be to implement auth=<tuple>, i.e. basic auth.

This might be ok, but could also confuse users into believing all httpx auth types is usable as a pattern match, which they can't be.