Skip to content

Commit

Permalink
aiohttp reuses SSLContext instances created at import-time (#259)
Browse files Browse the repository at this point in the history
* `aiohttp` reuses SSLContext instances created at import-time.
  • Loading branch information
mindflayer authored Oct 20, 2024
1 parent d0b43a1 commit 8eae0c7
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
11 changes: 9 additions & 2 deletions mocket/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
from .async_mocket import async_mocketize
from .mocket import Mocket, MocketEntry, Mocketizer, mocketize
from .mocket import FakeSSLContext, Mocket, MocketEntry, Mocketizer, mocketize

__all__ = ("async_mocketize", "mocketize", "Mocket", "MocketEntry", "Mocketizer")
__all__ = (
"async_mocketize",
"mocketize",
"Mocket",
"MocketEntry",
"Mocketizer",
"FakeSSLContext",
)

__version__ = "3.13.1"
18 changes: 18 additions & 0 deletions mocket/plugins/aiohttp_connector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import contextlib

from mocket import FakeSSLContext

with contextlib.suppress(ModuleNotFoundError):
from aiohttp import ClientRequest
from aiohttp.connector import TCPConnector

class MocketTCPConnector(TCPConnector):
"""
`aiohttp` reuses SSLContext instances created at import-time,
making it more difficult for Mocket to do its job.
This is an attempt to make things smoother, at the cost of
slightly patching the `ClientSession` while testing.
"""

def _get_ssl_context(self, req: ClientRequest) -> FakeSSLContext:
return FakeSSLContext()
9 changes: 7 additions & 2 deletions tests/test_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
import socket
import tempfile

import aiohttp
import pytest

from mocket import Mocketizer, async_mocketize
from mocket.mockhttp import Entry
from mocket.plugins.aiohttp_connector import MocketTCPConnector


def test_asyncio_record_replay(event_loop):
Expand Down Expand Up @@ -45,7 +47,10 @@ async def test_asyncio_connection():
@pytest.mark.asyncio
@async_mocketize
async def test_aiohttp():
import aiohttp
"""
The alternative to using the custom `connector` would be importing
`aiohttp` when Mocket is already in control (inside the decorated test).
"""

url = "https://bar.foo/"
data = {"message": "Hello"}
Expand All @@ -58,7 +63,7 @@ async def test_aiohttp():
)

async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=3)
timeout=aiohttp.ClientTimeout(total=3), connector=MocketTCPConnector()
) as session, session.get(url) as response:
response = await response.json()
assert response == data

0 comments on commit 8eae0c7

Please sign in to comment.