Colin-b / httpx_auth

Authentication classes to be used with httpx
MIT License
114 stars 26 forks source link

Add an option to disable cache #95

Closed halbow closed 3 months ago

halbow commented 3 months ago

Hi 👋

I'm trying out httpx_auth for a project and I would like to see if it would be possible to add an option to disable cache entirely ? My usecase is that I'm using it in some tests, mocking the HTTP calls with VCR and I'd like to replay the full flow for each test (request for token + actual request). Currently with the cache, I'm only recording the auth request on the first test which makes it not very deterministic.

The solution I ended up is to subclass TokenMemoryCache and override expiry to 0 (epoch time):

class NoCache(TokenMemoryCache):
    def _add_token(self, key: str, token: str, expiry: float, refresh_token: str | None = None):
        epoch_time = 0
        return super()._add_token(
            key=key,
            token=token,
            expiry=epoch_time,
            refresh_token=refresh_token,
        )

But as subclassing private method of a library is a bit hacky, I was wondering if you would consider adding this as an option in the library ? I would be happy to open a PR for it 🙂

Thanks for the great library !

[EDIT] Actually this solution ends up requesting the token before each request which is not the behavior I wanted either (what I'm trying to do is having the cache linked to the httpx.Client I use in each test)

halbow commented 3 months ago

In the end I was able to have one cache per test with the following fixture:

@pytest.fixture(autouse=True)
def patch_oauth_cache():
    OAuth2.token_cache = TokenMemoryCache()