Skip to content

Use aiohttp middleware for mocking#170

Merged
sarayourfriend merged 1 commit intomasterfrom
aiohttp-middlewares
Mar 1, 2026
Merged

Use aiohttp middleware for mocking#170
sarayourfriend merged 1 commit intomasterfrom
aiohttp-middlewares

Conversation

@sarayourfriend
Copy link
Collaborator

Description

Fixes #166
Replaces #167 cc @cjw296

This solves a host of issues, including #166, as well as that middlewares would not have previously worked.

This aiohttp feature is documented here: https://docs.aiohttp.org/en/stable/client_advanced.html#client-middleware

This PR changes the aiohttp implementation to be middleware based by refactoring the interceptor to implement aiohttp's ClientMiddlewareType (as the __call__ method). Rather than mocking all of aiohttp's _request method, now pook injects its interceptor as the final middleware, then defers to the real _request method.

aiohttp's _request method picks up the middleware. As it is last, it will be the "innermost" middleware, and can intercept the actual request mechanism.

Because this still prevents aiohttp's _connect_and_send_request from running when a mock matches, and thus prevents the Connector.connect method from running, this won't fully solve other issues like #152. Some traces will start to work now, though.

PR Checklist

Comment on lines -57 to -58
if not hasattr(headers, "__setitem__"):
raise TypeError("headers must be a dictionary")
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check isn't necessary, or even accurate. The underlying HTTPHeaderDict class's extend method handles a host of different types of inputs and should be the source of any relevant TypeErrors anyway.

This solves a host of issues, including #166, as well as that middlwares would not have previously worked. It might also solve #152 but I have not tested that yet.
@sarayourfriend sarayourfriend merged commit b431197 into master Mar 1, 2026
9 checks passed
@sarayourfriend sarayourfriend deleted the aiohttp-middlewares branch March 1, 2026 01:51
@cjw296
Copy link

cjw296 commented Mar 2, 2026

Awesome, thanks! I ran out of steam on this a while back, as you saw... Do you know when you'll be able to get this out into a release I'd be able to use?

@sarayourfriend
Copy link
Collaborator Author

Yep! Released here in v2.1.5: https://github.com/h2non/pook/releases/tag/v2.1.5

Already on PyPI as well 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

aiohttp mocking does not match on basic auth headers provided in ClientSession

2 participants