Skip to content

Commit

Permalink
Improve aiohttp JSONMatcher support (#139)
Browse files Browse the repository at this point in the history
* Improve aiohttp JSONMatcher support.

* Lint

* Small simplification

---------

Co-authored-by: sarayourfriend <[email protected]>
  • Loading branch information
KyleJamesWalker and sarayourfriend authored Oct 5, 2024
1 parent d9e739f commit 2683231
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/pook/interceptors/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ async def _on_request(
str(url) + "?" + urlencode([(x, y) for x, y in kw["params"].items()])
)

# If a json payload is provided, serialize it for JSONMatcher support
if json_body := kw.get("json"):
req.json = json_body
if "Content-Type" not in req.headers:
req.headers["Content-Type"] = "application/json"

# Match the request against the registered mocks in pook
mock = self.engine.match(req)

Expand Down
19 changes: 19 additions & 0 deletions tests/unit/interceptors/aiohttp_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import pytest
import aiohttp
import json

import pook

Expand Down Expand Up @@ -55,3 +56,21 @@ async def test_binary_body(URL):
async with aiohttp.ClientSession() as session:
req = await session.get(URL)
assert await req.read() == BINARY_FILE


@pytest.mark.asyncio
async def test_json_matcher_data_payload(URL):
payload = {"foo": "bar"}
pook.post(URL).json(payload).reply(200).body(BINARY_FILE)
async with aiohttp.ClientSession() as session:
req = await session.post(URL, data=json.dumps(payload))
assert await req.read() == BINARY_FILE


@pytest.mark.asyncio
async def test_json_matcher_json_payload(URL):
payload = {"foo": "bar"}
pook.post(URL).json(payload).reply(200).body(BINARY_FILE)
async with aiohttp.ClientSession() as session:
req = await session.post(URL, json=payload)
assert await req.read() == BINARY_FILE

0 comments on commit 2683231

Please sign in to comment.