Skip to content

Commit 9f9744d

Browse files
Merge pull request #6 from devanshshukla99/status_code
Added status code in the dump
2 parents e53f136 + 584190f commit 9f9744d

File tree

8 files changed

+53
-35
lines changed

8 files changed

+53
-35
lines changed

pytest_response/app.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111

1212

1313
class BaseMockResponse:
14-
def __init__(self, data: bytes, headers: dict = {}) -> None:
15-
self.status = self.status_code = self.code = 200
14+
def __init__(self, status: int, data: bytes, headers: dict = {}) -> None:
15+
self.status = self.status_code = self.code = status
1616
self.msg = self.reason = "OK"
1717
self.headers = headers
1818
self.will_close = True
@@ -159,7 +159,7 @@ def register(self, mock: str) -> None:
159159

160160
# Register for future use.
161161
self._registered_mocks[mock.stem] = mock_lib
162-
log.info(f"{mock.name} registered")
162+
log.debug(f"{mock.name} registered")
163163
return
164164

165165
def registermany(self, mocks: List[str]) -> None:

pytest_response/database.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22
import zlib
33
from base64 import b64decode, b64encode
44
from datetime import date
5-
from urllib.parse import urlparse, urljoin
5+
from urllib.parse import urljoin, urlparse
66

77
from tinydb import TinyDB, where
88

9+
from pytest_response.exceptions import MalformedUrl
10+
911
# from collections.abc import MutableMapping
1012

1113

@@ -37,19 +39,23 @@ def _sanatize_url(self, url: str):
3739
Expecting:
3840
from `http://www.python.org:80` -> `http://www.python.org`
3941
"""
40-
_urlparsed = urlparse(url)
41-
_url = "://".join([_urlparsed.scheme, _urlparsed.hostname])
42-
return urljoin(_url, _urlparsed.path)
43-
44-
def insert(self, url: str, response: bytes, headers: dict, **kwargs):
42+
try:
43+
_urlparsed = urlparse(url)
44+
_url = "://".join([_urlparsed.scheme, _urlparsed.hostname])
45+
return urljoin(_url, _urlparsed.path)
46+
except Exception:
47+
raise MalformedUrl
48+
49+
def insert(self, url: str, response: bytes, headers: dict, status: int = 200, **kwargs):
4550
"""
4651
Method for dumping url, headers and responses to the database.
4752
All additonal kwargs are dumped as well.
4853
"""
4954
kwargs.update({"url": self._sanatize_url(url)})
5055
kwargs.update({"cache_date": self.today})
51-
kwargs.update({"response": b64encode(zlib.compress(response)).decode("utf-8")})
56+
kwargs.update({"status": str(status)})
5257
kwargs.update({"headers": b64encode(zlib.compress(str(headers).encode("utf-8"))).decode("utf-8")})
58+
kwargs.update({"response": b64encode(zlib.compress(response)).decode("utf-8")})
5359
self._database.upsert(kwargs, where("url") == url)
5460
return
5561

@@ -60,12 +66,15 @@ def get(self, url: str, **kwargs):
6066
"""
6167
query = where("url") == self._sanatize_url(url) # and where("request") == "req"
6268
if element := self._database.search(query):
63-
res = element[0].get("response")
69+
status = element[0].get("status", 200)
6470
headers = element[0].get("headers", "[]")
65-
return zlib.decompress(b64decode(res.encode("utf-8"))), ast.literal_eval(
66-
zlib.decompress(b64decode(headers)).decode("utf-8")
71+
res = element[0].get("response")
72+
return (
73+
int(status),
74+
zlib.decompress(b64decode(res.encode("utf-8"))),
75+
ast.literal_eval(zlib.decompress(b64decode(headers)).decode("utf-8")),
6776
)
68-
return b"", {}
77+
return 404, b"", {}
6978

7079
def all(self):
7180
"""

pytest_response/interceptors/requests_quick.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,26 @@ def inner_func(url, params=None, **kwargs):
1616
log.error(f"RemoteBlockedError remote:{response.remote}")
1717
raise RemoteBlockedError
1818
if response.response:
19-
data, headers = response.get(url=url)
19+
status, data, headers = response.get(url=url)
2020
if not data:
2121
log.error(f"Response not found url:{url}")
2222
raise ResponseNotFound
23-
return MockResponse(data, headers)
23+
return MockResponse(status, data, headers)
2424
_ = func(url, params, **kwargs)
2525
if not response.capture:
2626
return _
2727
data = _.content
28-
response.insert(url=url, response=data, headers=dict(_.headers))
28+
response.insert(url=url, response=data, headers=dict(_.headers), status=_.status_code)
2929
return _
3030

3131
return inner_func
3232

3333

3434
class MockResponse(BaseMockResponse):
35-
def __init__(self, data, headers={}):
35+
def __init__(self, status, data, headers={}):
3636
headers = urllib3.response.HTTPHeaderDict(headers)
3737
self.content = data
38-
super().__init__(data, headers)
38+
super().__init__(status, data, headers)
3939

4040
pass
4141

pytest_response/interceptors/urllib.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ def begin(self, *args, **kwargs):
196196
if response.response:
197197
global CONFIG
198198
self.fp = io.BytesIO()
199-
data, headers = response.get(url=CONFIG.get("url", ""))
199+
status, data, headers = response.get(url=CONFIG.get("url", ""))
200200
if not data:
201201
self.code = self.status = 404
202202
self.reason = "Response Not Found (pytest-response)"

pytest_response/interceptors/urllib3_quick.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,26 +22,26 @@ def inner_func(self, method, url, *args, **kwargs):
2222
if not response.remote:
2323
raise RemoteBlockedError
2424
if response.response:
25-
data, headers = response.get(url=_url)
25+
status, data, headers = response.get(url=_url)
2626
if not data:
2727
log.error(f"Response not found url:{_url}")
2828
raise ResponseNotFound
29-
return MockResponse(data, headers)
29+
return MockResponse(status, data, headers)
3030
_ = func(self, method, url, *args, **kwargs)
3131
if not response.capture:
3232
return _
3333
data = _._fp.read()
3434
_._fp = io.BytesIO(data)
35-
response.insert(url=_url, response=data, headers=dict(_.headers))
35+
response.insert(url=_url, response=data, headers=dict(_.headers), status=_.status)
3636
return _
3737

3838
return inner_func
3939

4040

4141
class MockResponse(BaseMockResponse):
42-
def __init__(self, data, headers={}):
42+
def __init__(self, status, data, headers={}):
4343
headers = urllib3.response.HTTPHeaderDict(headers)
44-
super().__init__(data, headers)
44+
super().__init__(status, data, headers)
4545

4646

4747
def install_opener():

pytest_response/interceptors/urllib_quick.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,27 +15,27 @@ def inner_func(url, *args, **kwargs):
1515
log.error(f"RemoteBlockedError remote:{response.remote}")
1616
raise RemoteBlockedError
1717
if response.response:
18-
data, headers = response.get(url=url)
18+
status, data, headers = response.get(url=url)
1919
if not data:
2020
log.error(f"Response not found url:{url}")
2121
raise ResponseNotFound
22-
return MockResponse(data, headers)
22+
return MockResponse(status, data, headers)
2323

2424
_ = func(url, *args, **kwargs)
2525
if not response.capture:
2626
return _
2727
data = _.fp.read()
2828
_.fp = io.BytesIO(data)
2929
headers = _.headers
30-
response.insert(url=url, response=data, headers=dict(headers))
30+
response.insert(url=url, response=data, headers=dict(headers), status=_.status)
3131
return _
3232

3333
return inner_func
3434

3535

3636
class MockResponse(BaseMockResponse):
37-
def __init__(self, data, headers={}):
38-
super().__init__(data, headers)
37+
def __init__(self, status, data, headers={}):
38+
super().__init__(status, data, headers)
3939

4040
pass
4141

tests/test_app.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def test_response_obj():
4545

4646

4747
def test_basemockresponse():
48-
res = BaseMockResponse(b"Hello", headers={"Mock": True})
48+
res = BaseMockResponse(200, b"Hello", headers={"Mock": True})
4949
assert res.code == res.status_code == res.status == res.getcode() == 200
5050
assert res.headers
5151
assert res.info()

tests/test_database.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
1+
import pytest
2+
13
from pytest_response.database import ResponseDB
4+
from pytest_response.exceptions import MalformedUrl
25

36

47
def test_response_db(tmp_path):
58
path = tmp_path / "temp_db.json"
69
db = ResponseDB(path)
710

8-
url = "testurl"
11+
url = "https://testurl"
912
data = b"Hello, this is a test."
1013
headers = {"Test": True}
14+
status = 200
1115

12-
assert db.insert(url=url, response=data, headers=headers) is None
13-
get_data, get_headers = db.get(url)
16+
assert db.insert(url=url, response=data, headers=headers, status=status) is None
17+
get_status, get_data, get_headers = db.get(url)
18+
assert get_status == 200
1419
assert get_data == data
1520
assert get_headers == headers
1621

@@ -20,8 +25,12 @@ def test_response_db(tmp_path):
2025
assert db.truncate() is None
2126
assert db.all() == []
2227

23-
noget_data, noget_headers = db.get("invalid_url")
28+
noget_status, noget_data, noget_headers = db.get("https://invalid_url")
29+
assert noget_status == 404
2430
assert noget_data == b""
2531
assert noget_headers == {}
2632

33+
with pytest.raises(MalformedUrl):
34+
db.get("invalid_url")
35+
2736
db.close()

0 commit comments

Comments
 (0)