Skip to content

Commit 9695880

Browse files
committed
override replace() to prevent 'zyte_api_response' attribute from being lost
1 parent 109dbf0 commit 9695880

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

scrapy_zyte_api/responses.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,20 @@
66

77

88
class ZyteAPIMixin:
9-
def __init__(self, *args, zyte_api_response=None, **kwargs):
9+
def __init__(self, *args, zyte_api_response: Dict = None, **kwargs):
1010
super().__init__(*args, **kwargs)
1111
self._zyte_api_response = zyte_api_response
1212

13+
def replace(self, *args, **kwargs):
14+
"""Create a new response with the same attributes except for those given
15+
new values.
16+
17+
NOTE: This doesn't support replacing the ``zyte_api_response`` attribute.
18+
"""
19+
instance = super().replace(*args, **kwargs)
20+
instance._zyte_api_response = self.zyte_api_response
21+
return instance
22+
1323
@property
1424
def zyte_api_response(self) -> Dict:
1525
"""Contains the raw API response from Zyte API.

tests/test_responses.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,23 @@ def test_text_from_api_response(api_response, cls):
7979
assert response.certificate is None
8080
assert response.ip_address is None
8181
assert response.protocol is None
82+
83+
84+
@pytest.mark.parametrize(
85+
"api_response,cls",
86+
[
87+
(api_response_browser, ZyteAPITextResponse),
88+
(api_response_body, ZyteAPIResponse),
89+
],
90+
)
91+
def test_response_replace(api_response, cls):
92+
orig_response = cls.from_api_response(api_response())
93+
94+
# The ``zyte_api_response`` should not be replaced.
95+
new_response = orig_response.replace(zyte_api_response={"overridden": "value"})
96+
assert new_response.zyte_api_response == orig_response.zyte_api_response
97+
98+
# It should still work the same way
99+
new_response = orig_response.replace(status=404)
100+
assert new_response.status == 404
101+
assert new_response.zyte_api_response == orig_response.zyte_api_response

0 commit comments

Comments
 (0)