Skip to content

Commit 48f435e

Browse files
Replace requests mocking with pook (#3562)
* Replace `requests` mocking with `pook` * Use `pook.use` context manager instead of `pook.on` and `pook.off` --------- Co-authored-by: sarayourfriend <24264157+sarayourfriend@users.noreply.github.com>
1 parent 8ad81f6 commit 48f435e

File tree

3 files changed

+36
-89
lines changed

3 files changed

+36
-89
lines changed

api/test/unit/utils/test_watermark.py

Lines changed: 17 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
import json
2-
from collections.abc import Callable
3-
from dataclasses import dataclass
42
from pathlib import Path
53

4+
import pook
65
import pytest
7-
from requests import Request, Response
86

97
from api.utils.watermark import HEADERS, watermark
108

@@ -14,55 +12,32 @@
1412
_MOCK_IMAGE_INFO = json.loads((_MOCK_IMAGE_PATH / "sample-image-info.json").read_text())
1513

1614

17-
@dataclass
18-
class RequestsFixture:
19-
requests: list[Request]
20-
response_factory: Callable[[Request], Response] = ( # noqa: E731
21-
lambda x: RequestsFixture._default_response_factory(x)
22-
)
15+
@pytest.fixture
16+
def mock_request():
17+
with pook.use():
18+
mock = (
19+
pook.get("http://example.com/")
20+
.header("User-Agent", HEADERS["User-Agent"])
21+
.reply(200)
22+
.body(_MOCK_IMAGE_BYTES, binary=True)
23+
.mock
24+
)
25+
yield mock
2326

24-
@staticmethod
25-
def _default_response_factory(req: Request) -> Response:
26-
res = Response()
27-
res.url = req.url
28-
res.status_code = 200
29-
res._content = _MOCK_IMAGE_BYTES
30-
return res
3127

32-
33-
@pytest.fixture(autouse=True)
34-
def requests(monkeypatch) -> RequestsFixture:
35-
fixture = RequestsFixture([])
36-
37-
def requests_get(url, **kwargs):
38-
req = Request(method="GET", url=url, **kwargs)
39-
fixture.requests.append(req)
40-
response = fixture.response_factory(req)
41-
return response
42-
43-
monkeypatch.setattr("requests.get", requests_get)
44-
45-
return fixture
46-
47-
48-
def test_sends_UA_header(requests):
28+
def test_watermark_image_sends_ua_header(mock_request):
4929
watermark("http://example.com/", _MOCK_IMAGE_INFO)
50-
51-
assert len(requests.requests) > 0
52-
for r in requests.requests:
53-
assert r.headers == HEADERS
30+
# ``pook`` will only match if UA header is sent.
31+
assert mock_request.total_matches > 0
5432

5533

5634
# Previously, wrapped titles would throw a TypeError:
5735
# slice indices must be integers or None or have an __index__ method.
5836
# See: https://github.com/WordPress/openverse/issues/2466
59-
def test_long_title_wraps_correctly(requests):
37+
def test_long_title_wraps_correctly(mock_request):
6038
# Make the title 400 chars long
6139
_MOCK_IMAGE_INFO_LONG_TITLE = dict(_MOCK_IMAGE_INFO)
6240
_MOCK_IMAGE_INFO_LONG_TITLE["title"] = "a" * 400
6341

6442
watermark("http://example.com/", _MOCK_IMAGE_INFO_LONG_TITLE)
65-
66-
assert len(requests.requests) > 0
67-
for r in requests.requests:
68-
assert r.headers == HEADERS
43+
assert mock_request.total_matches > 0

api/test/unit/utils/test_waveform.py

Lines changed: 16 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
11
import json
2-
from collections.abc import Callable
3-
from dataclasses import dataclass
4-
from io import BytesIO
52
from pathlib import Path
63

4+
import pook
75
import pytest
8-
from requests import Request, Response
9-
from requests.structures import CaseInsensitiveDict
106

117
from api.utils.waveform import UA_STRING, download_audio
128

@@ -16,42 +12,21 @@
1612
_MOCK_AUDIO_INFO = json.loads((_MOCK_AUDIO_PATH / "sample-audio-info.json").read_text())
1713

1814

19-
@dataclass
20-
class RequestsFixture:
21-
requests: list[Request]
22-
response_factory: Callable[[Request], Response] = ( # noqa: E731
23-
lambda x: RequestsFixture._default_response_factory(x)
24-
)
15+
@pytest.fixture
16+
def mock_request():
17+
with pook.use():
18+
mock = (
19+
pook.get("http://example.org/")
20+
.header("User-Agent", UA_STRING)
21+
.reply(200)
22+
.headers({"Content-Type": _MOCK_AUDIO_INFO["headers"]["Content-Type"]})
23+
.body(_MOCK_AUDIO_BYTES, binary=True)
24+
.mock
25+
)
26+
yield mock
2527

26-
@staticmethod
27-
def _default_response_factory(req: Request) -> Response:
28-
res = Response()
29-
res.url = req.url
30-
res.status_code = 200
31-
res.raw = BytesIO(_MOCK_AUDIO_BYTES)
32-
res.headers = CaseInsensitiveDict(_MOCK_AUDIO_INFO["headers"])
33-
return res
3428

35-
36-
@pytest.fixture(autouse=True)
37-
def requests(monkeypatch) -> RequestsFixture:
38-
fixture = RequestsFixture([])
39-
40-
def requests_get(url, **kwargs):
41-
kwargs.pop("stream")
42-
req = Request(method="GET", url=url, **kwargs)
43-
fixture.requests.append(req)
44-
response = fixture.response_factory(req)
45-
return response
46-
47-
monkeypatch.setattr("requests.get", requests_get)
48-
49-
return fixture
50-
51-
52-
def test_download_audio_sends_ua_header(requests):
29+
def test_download_audio_sends_ua_header(mock_request):
5330
download_audio("http://example.org", "abcd-1234")
54-
55-
assert len(requests.requests) > 0
56-
for r in requests.requests:
57-
assert r.headers["User-Agent"] == UA_STRING
31+
# ``pook`` will only match if UA header is sent.
32+
assert mock_request.total_matches > 0

api/test/unit/views/test_image_views.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import pook
77
import pytest
88
from PIL import UnidentifiedImageError
9-
from requests import Response
109

1110
from api.views.image_views import ImageViewSet
1211

@@ -85,11 +84,9 @@ def test_watermark_raises_424_for_invalid_image(api_client):
8584
def test_watermark_raises_424_for_404_image(api_client):
8685
image = ImageFactory.create()
8786

88-
with patch("requests.get") as mock_get:
89-
mock_get.return_value = Response()
90-
mock_get.return_value.status_code = 404
91-
mock_get.return_value.url = image.url
92-
mock_get.return_value.reason = "Not Found"
87+
with pook.use():
88+
pook.get(image.url).reply(404)
89+
9390
res = api_client.get(f"/v1/images/{image.identifier}/watermark/")
9491
assert res.status_code == 424
9592
assert res.data["detail"] == f"404 Client Error: Not Found for url: {image.url}"

0 commit comments

Comments
 (0)