22import zlib
33from base64 import b64decode , b64encode
44from datetime import date
5- from urllib .parse import urlparse , urljoin
5+ from urllib .parse import urljoin , urlparse
66
77from 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 """
0 commit comments