1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
|
import json
from typing import Annotated
import attrs
import pytest
from web_poet import (
AnyResponse,
BrowserHtml,
BrowserResponse,
HttpClient,
HttpResponse,
HttpResponseBody,
Injectable,
ItemPage,
PageParams,
RequestUrl,
ResponseUrl,
Stats,
WebPage,
)
from web_poet.annotated import AnnotatedInstance, annotation_decode, annotation_encode
from web_poet.page_inputs.url import _Url
from web_poet.serialization import (
SerializedDataFileStorage,
SerializedLeafData,
deserialize,
deserialize_leaf,
register_serialization,
serialize,
serialize_leaf,
)
def _assert_pages_equal(p1, p2) -> None:
assert type(p1) == type(p2) # noqa: E721
assert type(p1.response) == type(p2.response) # noqa: E721
assert type(p1.response.body) == type(p2.response.body) # noqa: E721
assert type(p1.response.headers) == type(p2.response.headers) # noqa: E721
assert p1.response.body == p2.response.body
assert p1.response.status == p2.response.status
assert p1.response.headers == p2.response.headers
assert p1.response._encoding == p2.response._encoding
_assert_urls_equal(p1.response.url, p2.response.url)
def _assert_urls_equal(u1: _Url, u2: _Url) -> None:
assert type(u1) == type(u2) # noqa: E721
assert str(u1) == str(u2)
def test_serialization_leaf() -> None:
leaf = HttpResponseBody(b"foo")
serialized_data = serialize_leaf(leaf)
assert isinstance(serialized_data["html"], bytes)
assert HttpResponseBody(serialized_data["html"]) == leaf
deserialized_data = deserialize_leaf(HttpResponseBody, serialized_data)
assert leaf == deserialized_data
def test_serialization_browser_html() -> None:
html_str = "<html><body>Hello</body></html>"
browser_html = BrowserHtml(html_str)
serialized_data = serialize_leaf(browser_html)
assert serialized_data == {"body.html": html_str.encode("utf8")}
deserialized = deserialize_leaf(BrowserHtml, serialized_data)
assert isinstance(deserialized, BrowserHtml)
assert deserialized == browser_html
def test_serialization_browser_response() -> None:
html = BrowserHtml("<html><body>Hello</body></html>")
url = ResponseUrl("http://example.com")
response = BrowserResponse(url=url, html=html, status=200)
serialized_data = serialize_leaf(response)
assert serialized_data["body.html"] == html.encode("utf8")
info = json.loads(serialized_data["info.json"])
assert info == {"url": str(url), "status": 200, "type": "BrowserResponse"}
deserialized = deserialize_leaf(BrowserResponse, serialized_data)
assert isinstance(deserialized, BrowserResponse)
assert deserialized.html == response.html
assert deserialized.status == response.status
_assert_urls_equal(deserialized.url, response.url)
def test_serialization_anyresponse_http_response(book_list_html_response) -> None:
any_response = AnyResponse(response=book_list_html_response)
serialized_data = serialize_leaf(any_response)
info = json.loads(serialized_data["info.json"])
assert "_encoding" in info
assert info["_encoding"] == book_list_html_response._encoding
assert serialized_data["body.html"] == bytes(book_list_html_response.body)
deserialized = deserialize_leaf(AnyResponse, serialized_data)
assert isinstance(deserialized, AnyResponse)
assert isinstance(deserialized.response, HttpResponse)
assert deserialized.response.body == book_list_html_response.body
assert deserialized.response.status == book_list_html_response.status
assert deserialized.response.headers == book_list_html_response.headers
assert deserialized.response._encoding == book_list_html_response._encoding
_assert_urls_equal(deserialized.response.url, book_list_html_response.url)
def test_serialization_anyresponse_browser_response() -> None:
html = BrowserHtml("<html><body>Hello</body></html>")
url = ResponseUrl("http://example.com")
browser_response = BrowserResponse(url=url, html=html, status=200)
any_response = AnyResponse(response=browser_response)
serialized_data = serialize_leaf(any_response)
assert serialized_data["body.html"] == html.encode("utf8")
info = json.loads(serialized_data["info.json"])
assert info == {"url": str(url), "status": 200, "type": "BrowserResponse"}
assert "_encoding" not in info
deserialized = deserialize_leaf(AnyResponse, serialized_data)
assert isinstance(deserialized, AnyResponse)
assert isinstance(deserialized.response, BrowserResponse)
assert deserialized.response.html == browser_response.html
assert deserialized.response.status == browser_response.status
_assert_urls_equal(deserialized.response.url, browser_response.url)
def test_serialization_leaf_unsupported() -> None:
class A:
pass
with pytest.raises(
NotImplementedError, match=r"Serialization .+ is not implemented"
):
serialize_leaf(A())
with pytest.raises(
NotImplementedError, match=r"Deserialization .+ is not implemented"
):
deserialize_leaf(A, {})
def test_serialization(book_list_html_response) -> None:
@attrs.define
class ResponseData(Injectable):
response: HttpResponse
@attrs.define
class MyWebPage(ItemPage):
response: HttpResponse
url: ResponseUrl
request_url: RequestUrl
params: PageParams
data: ResponseData
stats: Stats
url_str = "http://books.toscrape.com/index.html"
url = ResponseUrl(url_str)
request_url = RequestUrl(url_str)
page_params = PageParams(foo="bar")
stats = Stats()
serialized_deps = serialize(
[book_list_html_response, url, request_url, page_params, stats]
)
info_json = f"""{{
"_encoding": "utf-8",
"headers": [],
"status": null,
"type": "HttpResponse",
"url": "{url_str}"
}}""".encode()
assert serialized_deps == {
"HttpResponse": {
"body.html": bytes(book_list_html_response.body),
"info.json": info_json,
},
"ResponseUrl": {
"txt": url_str.encode(),
},
"RequestUrl": {
"txt": url_str.encode(),
},
"PageParams": {
"json": b'{\n "foo": "bar"\n}',
},
"Stats": {},
}
po = MyWebPage(
book_list_html_response,
url,
request_url,
page_params,
ResponseData(book_list_html_response),
Stats(),
)
deserialized_po = deserialize(MyWebPage, serialized_deps)
_assert_pages_equal(po, deserialized_po)
assert deserialized_po.data is not None
def test_serialization_injectable(book_list_html_response) -> None:
with pytest.raises(ValueError, match=r"Injectable type .+ passed"):
serialize([WebPage(book_list_html_response)])
def test_serialization_httpresponse_encoding(book_list_html) -> None:
body = HttpResponseBody(bytes(book_list_html, "utf-8"))
resp_enc = HttpResponse(
url=ResponseUrl("http://books.toscrape.com/index.html"),
body=body,
encoding="utf-8",
)
assert resp_enc._encoding == "utf-8"
deserialized_resp_enc = deserialize_leaf(HttpResponse, serialize_leaf(resp_enc))
assert deserialized_resp_enc._encoding == "utf-8"
resp_noenc = HttpResponse(
url=ResponseUrl("http://books.toscrape.com/index.html"), body=body
)
assert resp_noenc._encoding is None
deserialized_resp_noenc = deserialize_leaf(HttpResponse, serialize_leaf(resp_noenc))
assert deserialized_resp_noenc._encoding is None
def test_custom_functions() -> None:
class C:
value: int
def __init__(self, value: int):
self.value = value
def _serialize(o: C) -> SerializedLeafData:
return {"bin": o.value.to_bytes((o.value.bit_length() + 7) // 8, "little")}
def _deserialize(t: type[C], data: SerializedLeafData) -> C:
return t(int.from_bytes(data["bin"], "little"))
register_serialization(_serialize, _deserialize)
obj = C(22222222222)
deserialized_obj = deserialize_leaf(C, serialize_leaf(obj))
assert obj.value == deserialized_obj.value
def test_write_data(book_list_html_response, tmp_path) -> None:
@attrs.define
class MyWebPage(ItemPage):
response: HttpResponse
url: ResponseUrl
url = ResponseUrl("http://example.com")
directory = tmp_path / "ser"
directory.mkdir()
storage = SerializedDataFileStorage(directory)
serialized_deps = serialize([book_list_html_response, url])
storage.write(serialized_deps)
assert (directory / "HttpResponse-body.html").exists()
assert (directory / "HttpResponse-body.html").read_bytes() == bytes(
book_list_html_response.body
)
assert (directory / "HttpResponse-info.json").exists()
assert (directory / "ResponseUrl.txt").exists()
assert (directory / "ResponseUrl.txt").read_text(
encoding="utf-8"
) == "http://example.com"
read_serialized_deps = storage.read()
po = MyWebPage(book_list_html_response, url)
deserialized_po = deserialize(MyWebPage, read_serialized_deps)
assert type(deserialized_po) == MyWebPage # noqa: E721
_assert_pages_equal(po, deserialized_po)
def test_extra_files(book_list_html_response, tmp_path) -> None:
directory = tmp_path / "ser"
directory.mkdir()
storage = SerializedDataFileStorage(directory)
serialized_deps = serialize([book_list_html_response])
storage.write(serialized_deps)
(directory / "foo.dir").mkdir()
(directory / "bar.txt").touch()
read_serialized_deps = storage.read()
assert "HttpResponse" in read_serialized_deps
def test_httpclient_empty(tmp_path) -> None:
directory = tmp_path / "ser"
directory.mkdir()
client = HttpClient()
storage = SerializedDataFileStorage(directory)
serialized_deps = serialize([client])
storage.write(serialized_deps)
assert (directory / "HttpClient.exists").exists()
read_serialized_deps = storage.read()
assert "HttpClient" in read_serialized_deps
def test_annotated(book_list_html_response) -> None:
@attrs.define
class MyWebPage(ItemPage):
response: Annotated[HttpResponse, "foo", 42]
url: ResponseUrl
url_str = "http://books.toscrape.com/index.html"
url = ResponseUrl(url_str)
serialized_deps = serialize(
[AnnotatedInstance(book_list_html_response, ("foo", 42)), url]
)
po = MyWebPage(
book_list_html_response,
url,
)
deserialized_po = deserialize(MyWebPage, serialized_deps)
_assert_pages_equal(po, deserialized_po)
def test_annotated_duplicate(book_list_html_response) -> None:
url_str = "http://books.toscrape.com/index.html"
url = ResponseUrl(url_str)
with pytest.raises(
ValueError, match="Several instances of AnnotatedInstance for HttpResponse were"
):
serialize(
[
AnnotatedInstance(book_list_html_response, ("foo", 42)),
AnnotatedInstance(book_list_html_response, ("bar",)),
url,
]
)
@pytest.mark.parametrize(
"raw_annotation",
[
{"foo": "bar"},
["foo", "bar"],
],
)
def test_annotation_codec(raw_annotation):
encoded_annotation = annotation_encode(raw_annotation)
assert annotation_decode(encoded_annotation) == raw_annotation
obj = ResponseUrl("http://example.com")
metadata = (encoded_annotation,)
serialized = serialize([AnnotatedInstance(obj, metadata)])
expected_key = "AnnotatedInstance ResponseUrl"
assert expected_key in serialized
deserialized_instance = deserialize_leaf(
AnnotatedInstance, serialized[expected_key]
)
assert isinstance(deserialized_instance, AnnotatedInstance)
assert str(deserialized_instance.result) == str(obj)
assert metadata == deserialized_instance.metadata
|