Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Minimize to_bytes()/to_unicode() usage. (#8313)

Andrey Rakhmatullineba3e0572716
diff --git a/docs/topics/request-response.rst b/docs/topics/request-response.rst
index c606cc02b..ca4b71842 100644
--- a/docs/topics/request-response.rst
+++ b/docs/topics/request-response.rst
@@ -374,8 +374,6 @@ URL canonicalization or taking the request method or body into account:
from hashlib import sha1
from weakref import WeakKeyDictionary
- from scrapy.utils.python import to_bytes
-
class RequestFingerprinter:
cache = WeakKeyDictionary()
@@ -383,7 +381,7 @@ URL canonicalization or taking the request method or body into account:
def fingerprint(self, request):
if request not in self.cache:
fp = sha1()
- fp.update(to_bytes(request.url))
+ fp.update(request.url.encode())
self.cache[request] = fp.digest()
return self.cache[request]
@@ -412,7 +410,6 @@ the following request fingerprinter:
from hashlib import sha1
from weakref import WeakKeyDictionary
- from scrapy.utils.python import to_bytes
from w3lib.url import canonicalize_url
@@ -422,8 +419,8 @@ the following request fingerprinter:
def fingerprint(self, request):
if request not in self.cache:
fp = sha1()
- fp.update(to_bytes(request.method))
- fp.update(to_bytes(canonicalize_url(request.url)))
+ fp.update(request.method.encode())
+ fp.update(canonicalize_url(request.url).encode())
fp.update(request.body or b"")
self.cache[request] = fp.digest()
return self.cache[request]
diff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.py
index 81506f4aa..7146143f1 100644
--- a/scrapy/core/downloader/handlers/http11.py
+++ b/scrapy/core/downloader/handlers/http11.py
@@ -61,7 +61,6 @@ from scrapy.utils._ssl import _log_ssl_conn_debug_info
from scrapy.utils.defer import maybe_deferred_to_future
from scrapy.utils.deprecate import warn_on_deprecated_spider_attribute
from scrapy.utils.httpobj import urlparse_cached
-from scrapy.utils.python import to_bytes, to_unicode
from scrapy.utils.url import _add_http_if_no_scheme
from ._base_http import BaseHttpDownloadHandler
@@ -188,7 +187,7 @@ class _TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
def __init__(
self,
reactor: ReactorBase,
- host: str,
+ host: bytes,
port: int,
proxyConf: tuple[str, int, bytes | None],
contextFactory: IPolicyForHTTPS,
@@ -200,7 +199,7 @@ class _TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
self._tunnelReadyDeferred: Deferred[Protocol] = Deferred(self._cancelTunnel)
self._connectDeferred: Deferred[Protocol] | None = None
self._protocol: Protocol | None = None
- self._tunneledHost: str = host
+ self._tunneledHost: bytes = host
self._tunneledPort: int = port
self._contextFactory: IPolicyForHTTPS = contextFactory
self._connectBuffer: bytearray = bytearray()
@@ -286,20 +285,17 @@ class _TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
def _tunnel_request_data(
- host: str, port: int, proxy_auth_header: bytes | None = None
+ host: bytes, port: int, proxy_auth_header: bytes | None = None
) -> bytes:
r"""
Return binary content of a CONNECT request.
- >>> from scrapy.utils.python import to_unicode as s
- >>> s(_tunnel_request_data("example.com", 8080))
+ >>> _tunnel_request_data(b"example.com", 8080).decode()
'CONNECT example.com:8080 HTTP/1.1\r\nHost: example.com:8080\r\n\r\n'
- >>> s(_tunnel_request_data("example.com", 8080, b"123"))
+ >>> _tunnel_request_data(b"example.com", 8080, b"123").decode()
'CONNECT example.com:8080 HTTP/1.1\r\nHost: example.com:8080\r\nProxy-Authorization: 123\r\n\r\n'
- >>> s(_tunnel_request_data(b"example.com", "8090"))
- 'CONNECT example.com:8090 HTTP/1.1\r\nHost: example.com:8090\r\n\r\n'
"""
- host_value = to_bytes(host, encoding="ascii") + b":" + to_bytes(str(port))
+ host_value = host + b":" + str(port).encode()
tunnel_req = b"CONNECT " + host_value + b" HTTP/1.1\r\n"
tunnel_req += b"Host: " + host_value + b"\r\n"
if proxy_auth_header:
@@ -495,7 +491,7 @@ class _ScrapyAgent:
)
return _ScrapyProxyAgent(
reactor=reactor,
- proxyURI=to_bytes(proxy, encoding="ascii"),
+ proxyURI=proxy.encode("ascii"),
contextFactory=self._contextFactory,
connectTimeout=timeout,
bindAddress=bindaddress,
@@ -518,7 +514,7 @@ class _ScrapyAgent:
# request details
url = urldefrag(request.url)[0]
- method = to_bytes(request.method)
+ method = request.method.encode()
headers = TxHeaders(request.headers)
if isinstance(agent, _TunnelingAgent):
headers.removeHeader(b"Proxy-Authorization")
@@ -526,7 +522,7 @@ class _ScrapyAgent:
start_time = monotonic()
d: Deferred[IResponse] = agent.request(
method,
- to_bytes(url, encoding="ascii"),
+ url.encode("ascii"),
headers,
cast("IBodyProducer", bodyproducer),
)
@@ -642,7 +638,7 @@ class _ScrapyAgent:
def _cb_bodydone(self, result: _ResultT, url: str) -> Response:
headers = self._headers_from_twisted_response(result["txresponse"])
version = result["txresponse"].version
- protocol = f"{to_unicode(version[0])}/{version[1]}.{version[2]}"
+ protocol = f"{version[0].decode()}/{version[1]}.{version[2]}"
return make_response(
url=url,
status=int(result["txresponse"].code),
diff --git a/scrapy/downloadermiddlewares/cookies.py b/scrapy/downloadermiddlewares/cookies.py
index 1ab48a35e..40a4b96a1 100644
--- a/scrapy/downloadermiddlewares/cookies.py
+++ b/scrapy/downloadermiddlewares/cookies.py
@@ -11,7 +11,6 @@ from scrapy.http import Response
from scrapy.http.cookies import CookieJar
from scrapy.utils.decorators import _warn_spider_arg
from scrapy.utils.httpobj import urlparse_cached
-from scrapy.utils.python import to_unicode
from scrapy.utils.request import _decode_cookie, _to_verbose_cookies
if TYPE_CHECKING:
@@ -108,10 +107,7 @@ class CookiesMiddleware:
def _debug_cookie(self, request: Request) -> None:
if self.debug:
- cl = [
- to_unicode(c, errors="replace")
- for c in request.headers.getlist("Cookie")
- ]
+ cl = [c.decode(errors="replace") for c in request.headers.getlist("Cookie")]
if cl:
cookies = "\n".join(f"Cookie: {c}\n" for c in cl)
msg = f"Sending cookies to: {request}\n{cookies}"
@@ -120,7 +116,7 @@ class CookiesMiddleware:
def _debug_set_cookie(self, response: Response) -> None:
if self.debug:
cl = [
- to_unicode(c, errors="replace")
+ c.decode(errors="replace")
for c in response.headers.getlist("Set-Cookie")
]
if cl:
diff --git a/scrapy/downloadermiddlewares/httpproxy.py b/scrapy/downloadermiddlewares/httpproxy.py
index faae041a1..095e62e7d 100644
--- a/scrapy/downloadermiddlewares/httpproxy.py
+++ b/scrapy/downloadermiddlewares/httpproxy.py
@@ -12,7 +12,6 @@ from urllib.request import ( # type: ignore[attr-defined]
from scrapy.exceptions import NotConfigured
from scrapy.utils.decorators import _warn_spider_arg
from scrapy.utils.httpobj import urlparse_cached
-from scrapy.utils.python import to_bytes
if TYPE_CHECKING:
from scrapy import Request, Spider
@@ -40,8 +39,8 @@ class HttpProxyMiddleware:
return cls(auth_encoding)
def _basic_auth_header(self, username: str, password: str) -> bytes:
- user_pass = to_bytes(
- f"{unquote(username)}:{unquote(password)}", encoding=self.auth_encoding
+ user_pass = f"{unquote(username)}:{unquote(password)}".encode(
+ self.auth_encoding or "utf-8"
)
return base64.b64encode(user_pass)
diff --git a/scrapy/downloadermiddlewares/stats.py b/scrapy/downloadermiddlewares/stats.py
index 93a619a95..ba108be48 100644
--- a/scrapy/downloadermiddlewares/stats.py
+++ b/scrapy/downloadermiddlewares/stats.py
@@ -6,7 +6,7 @@ from twisted.web import http
from scrapy.exceptions import NotConfigured
from scrapy.utils.decorators import _warn_spider_arg
-from scrapy.utils.python import global_object_name, to_bytes
+from scrapy.utils.python import global_object_name
from scrapy.utils.request import request_httprepr
if TYPE_CHECKING:
@@ -28,7 +28,7 @@ def get_header_size(
def get_status_size(response_status: int) -> int:
- return len(to_bytes(http.RESPONSES.get(response_status, b""))) + 15
+ return len(http.RESPONSES.get(response_status, b"")) + 15
# resp.status + b"\r\n" + b"HTTP/1.1 <100-599> "
diff --git a/scrapy/exporters.py b/scrapy/exporters.py
index 787109313..2667cf4be 100644
--- a/scrapy/exporters.py
+++ b/scrapy/exporters.py
@@ -19,7 +19,7 @@ from xml.sax.xmlreader import AttributesImpl
from itemadapter import ItemAdapter, is_item
from scrapy.item import Field, Item
-from scrapy.utils.python import is_listlike, to_bytes, to_unicode
+from scrapy.utils.python import is_listlike, to_unicode
from scrapy.utils.serialize import ScrapyJSONEncoder
if TYPE_CHECKING:
@@ -170,7 +170,7 @@ class JsonLinesItemExporter(BaseItemExporter):
def export_item(self, item: Any) -> None:
itemdict = dict(self.get_serialized_fields(item))
data = self.encoder.encode(itemdict) + "\n"
- self.file.write(to_bytes(data, self.encoding))
+ self.file.write(data.encode(self.encoding or "utf-8"))
class JsonItemExporter(BaseItemExporter):
@@ -209,7 +209,7 @@ class JsonItemExporter(BaseItemExporter):
def export_item(self, item: Any) -> None:
itemdict = dict(self.get_serialized_fields(item))
- data = to_bytes(self.encoder.encode(itemdict), self.encoding)
+ data = self.encoder.encode(itemdict).encode(self.encoding or "utf-8")
self._add_comma_after_first()
self.file.write(data)
@@ -407,7 +407,7 @@ class PprintItemExporter(BaseItemExporter):
def export_item(self, item: Any) -> None:
itemdict = dict(self.get_serialized_fields(item))
- self.file.write(to_bytes(pprint.pformat(itemdict) + "\n"))
+ self.file.write(pprint.pformat(itemdict).encode() + b"\n")
class PythonItemExporter(BaseItemExporter):
diff --git a/scrapy/extensions/httpcache.py b/scrapy/extensions/httpcache.py
index bf93ff46b..171cea4b4 100644
--- a/scrapy/extensions/httpcache.py
+++ b/scrapy/extensions/httpcache.py
@@ -16,7 +16,7 @@ from w3lib.http import headers_dict_to_raw, headers_raw_to_dict
from scrapy.http import Response
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.project import data_path
-from scrapy.utils.python import to_bytes, to_unicode
+from scrapy.utils.python import to_unicode
from scrapy.utils.response import response_from_dict
if TYPE_CHECKING:
@@ -67,7 +67,7 @@ class RFC2616Policy:
Request | Response, dict[bytes, bytes | None]
] = WeakKeyDictionary()
self.ignore_response_cache_controls: list[bytes] = [
- to_bytes(cc)
+ cc.encode()
for cc in settings.getlist("HTTPCACHE_IGNORE_RESPONSE_CACHE_CONTROLS")
]
@@ -363,7 +363,7 @@ class FilesystemCacheStorage:
"timestamp": time(),
}
with self._open(rpath / "meta", "wb") as f:
- f.write(to_bytes(repr(metadata)))
+ f.write(repr(metadata).encode())
with self._open(rpath / "pickled_meta", "wb") as f:
pickle.dump(metadata, f, protocol=4)
with self._open(rpath / "response_headers", "wb") as f:
diff --git a/scrapy/extensions/remote_control.py b/scrapy/extensions/remote_control.py
index 417edc1bf..dd2b4b95a 100644
--- a/scrapy/extensions/remote_control.py
+++ b/scrapy/extensions/remote_control.py
@@ -320,11 +320,11 @@ class RemoteControl:
def _cap(s: str, limit: int) -> tuple[str, bool]:
"""Cap a string to ``limit`` bytes, appending an inline truncation marker."""
- b = s.encode("utf-8")
+ b = s.encode()
if len(b) <= limit:
return s, False
extra_kb = (len(b) - limit) // 1024 + 1
- head = b[:limit].decode("utf-8", "ignore")
+ head = b[:limit].decode(errors="ignore")
return f"{head}…[truncated, +{extra_kb}KB]", True
diff --git a/scrapy/extensions/telnet.py b/scrapy/extensions/telnet.py
index 0ffa10e8a..3085a4be5 100644
--- a/scrapy/extensions/telnet.py
+++ b/scrapy/extensions/telnet.py
@@ -112,8 +112,8 @@ class TelnetConsole(protocol.ServerFactory):
def login(self_, credentials, mind, *interfaces): # type: ignore[no-untyped-def] # pylint: disable=no-self-argument
if not (
- credentials.username == self.username.encode("utf8")
- and credentials.checkPassword(self.password.encode("utf8"))
+ credentials.username == self.username.encode()
+ and credentials.checkPassword(self.password.encode())
):
return fail(ValueError("Invalid credentials"))
diff --git a/scrapy/http/cookies.py b/scrapy/http/cookies.py
index e446b9d16..e1b5c6de7 100644
--- a/scrapy/http/cookies.py
+++ b/scrapy/http/cookies.py
@@ -7,7 +7,6 @@ from http.cookiejar import CookieJar as _CookieJar
from typing import TYPE_CHECKING, Self, cast
from scrapy.utils.httpobj import urlparse_cached
-from scrapy.utils.python import to_unicode
if TYPE_CHECKING:
from collections.abc import Iterator, Sequence
@@ -182,13 +181,13 @@ class WrappedRequest:
def get_header(self, name: str, default: str | None = None) -> str | None:
value = self.request.headers.get(name, default)
- return to_unicode(value, errors="replace") if value is not None else None
+ return value.decode(errors="replace") if value is not None else None
def header_items(self) -> list[tuple[str, list[str]]]:
return [
(
- to_unicode(k, errors="replace"),
- [to_unicode(x, errors="replace") for x in v],
+ k.decode(errors="replace"),
+ [x.decode(errors="replace") for x in v],
)
for k, v in self.request.headers.items()
]
@@ -205,6 +204,4 @@ class WrappedResponse:
return self
def get_all(self, name: str, default: object = None) -> list[str]:
- return [
- to_unicode(v, errors="replace") for v in self.response.headers.getlist(name)
- ]
+ return [v.decode(errors="replace") for v in self.response.headers.getlist(name)]
diff --git a/scrapy/http/headers.py b/scrapy/http/headers.py
index b02ae4859..d31054141 100644
--- a/scrapy/http/headers.py
+++ b/scrapy/http/headers.py
@@ -8,7 +8,6 @@ from w3lib.http import headers_dict_to_raw
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils._datatypes import CaseInsensitiveDict
-from scrapy.utils.python import to_unicode
if TYPE_CHECKING:
from collections.abc import Iterable
@@ -206,8 +205,8 @@ class Headers(dict): # type: ignore[type-arg]
)
return CaseInsensitiveDict(
(
- to_unicode(key, encoding=self.encoding, errors="replace"),
- to_unicode(b",".join(value), encoding=self.encoding, errors="replace"),
+ key.decode(self.encoding, errors="replace"),
+ b",".join(value).decode(self.encoding, errors="replace"),
)
for key, value in self.items()
)
diff --git a/scrapy/http/request/form.py b/scrapy/http/request/form.py
index dbb78f9cf..90723c51e 100644
--- a/scrapy/http/request/form.py
+++ b/scrapy/http/request/form.py
@@ -17,7 +17,7 @@ from w3lib.html import strip_html5_whitespace
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.http.request import Request
-from scrapy.utils.python import is_listlike, to_bytes
+from scrapy.utils.python import to_bytes
if TYPE_CHECKING:
from lxml.html import (
@@ -30,9 +30,14 @@ if TYPE_CHECKING:
from scrapy.http.response.text import TextResponse
-FormdataVType: TypeAlias = str | Iterable[str]
-FormdataKVType: TypeAlias = tuple[str, FormdataVType]
-FormdataType: TypeAlias = Mapping[str, FormdataVType] | Iterable[FormdataKVType] | None
+FormdataVType: TypeAlias = str | bytes | Iterable[str] | Iterable[bytes]
+FormdataKVType: TypeAlias = tuple[str | bytes, FormdataVType]
+FormdataType: TypeAlias = (
+ Mapping[str, FormdataVType]
+ | Mapping[bytes, FormdataVType]
+ | Iterable[FormdataKVType]
+ | None
+)
class FormRequest(Request):
@@ -163,7 +168,7 @@ def _urlencode(seq: Iterable[FormdataKVType], enc: str) -> str:
values = [
(to_bytes(k, enc), to_bytes(v, enc))
for k, vs in seq
- for v in (vs if is_listlike(vs) else [cast("str", vs)])
+ for v in ([vs] if isinstance(vs, (str, bytes)) else vs)
]
return urlencode(values, doseq=True)
diff --git a/scrapy/http/response/text.py b/scrapy/http/response/text.py
index 1a0b5c317..6ba03229a 100644
--- a/scrapy/http/response/text.py
+++ b/scrapy/http/response/text.py
@@ -25,7 +25,7 @@ from w3lib.encoding import (
from w3lib.html import strip_html5_whitespace
from scrapy.http.response import Response
-from scrapy.utils.python import memoizemethod_noargs, to_unicode
+from scrapy.utils.python import memoizemethod_noargs
from scrapy.utils.response import get_base_url
if TYPE_CHECKING:
@@ -129,16 +129,13 @@ class TextResponse(Response):
@memoizemethod_noargs
def _headers_encoding(self) -> str | None:
content_type = self.headers.get(b"Content-Type") or b""
- return http_content_type_encoding(to_unicode(content_type, encoding="latin-1"))
+ return http_content_type_encoding(content_type.decode("latin-1"))
def _body_inferred_encoding(self) -> str:
+ content_type = self.headers.get(b"Content-Type") or b""
if self._cached_benc is None:
- content_type = to_unicode(
- cast("bytes", self.headers.get(b"Content-Type", b"")),
- encoding="latin-1",
- )
benc, ubody = html_to_unicode(
- content_type,
+ content_type.decode("latin-1"),
self.body,
auto_detect_fun=self._auto_detect_fun,
default_encoding=self._DEFAULT_ENCODING,
diff --git a/scrapy/pipelines/files.py b/scrapy/pipelines/files.py
index df5833a60..86a6ef8a2 100644
--- a/scrapy/pipelines/files.py
+++ b/scrapy/pipelines/files.py
@@ -51,7 +51,6 @@ from scrapy.utils.boto import _get_max_pool_connections, is_botocore_available
from scrapy.utils.defer import deferred_from_coro, ensure_awaitable
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.log import failure_to_exc_info
-from scrapy.utils.python import to_bytes
from scrapy.utils.request import referer_str
if TYPE_CHECKING:
@@ -745,7 +744,7 @@ class FilesPipeline(MediaPipeline):
*,
item: Any = None,
) -> str:
- media_guid = hashlib.sha1(to_bytes(request.url)).hexdigest() # noqa: S324
+ media_guid = hashlib.sha1(request.url.encode()).hexdigest() # noqa: S324
# clean it up and look at the path first
parsed_url = urlparse_cached(request)
diff --git a/scrapy/pipelines/images.py b/scrapy/pipelines/images.py
index 51e10c671..19f6309cc 100644
--- a/scrapy/pipelines/images.py
+++ b/scrapy/pipelines/images.py
@@ -21,7 +21,6 @@ from scrapy.http.request import NO_CALLBACK
from scrapy.pipelines.files import FilesPipeline, GCSFilesStore, S3FilesStore
from scrapy.pipelines.media import FileException
from scrapy.utils.defer import ensure_awaitable
-from scrapy.utils.python import to_bytes
if TYPE_CHECKING:
from collections.abc import Iterator
@@ -268,7 +267,7 @@ class ImagesPipeline(FilesPipeline):
*,
item: Any = None,
) -> str:
- image_guid = hashlib.sha1(to_bytes(request.url)).hexdigest() # noqa: S324
+ image_guid = hashlib.sha1(request.url.encode()).hexdigest() # noqa: S324
ext = "" if self.preserve_format else ".jpg"
return f"full/{image_guid}{ext}"
@@ -281,6 +280,6 @@ class ImagesPipeline(FilesPipeline):
*,
item: Any = None,
) -> str:
- thumb_guid = hashlib.sha1(to_bytes(request.url)).hexdigest() # noqa: S324
+ thumb_guid = hashlib.sha1(request.url.encode()).hexdigest() # noqa: S324
ext = "" if self.preserve_format else ".jpg"
return f"thumbs/{thumb_id}/{thumb_guid}{ext}"
diff --git a/scrapy/pqueues.py b/scrapy/pqueues.py
index 7e7ceac89..fb3df069a 100644
--- a/scrapy/pqueues.py
+++ b/scrapy/pqueues.py
@@ -32,7 +32,7 @@ def _path_safe(text: str) -> str:
pathable_slot = "".join([c if c.isalnum() or c in "-._" else "_" for c in text])
# as we replace some letters we can get collision for different slots
# add we add unique part
- unique_slot = hashlib.md5(text.encode("utf8")).hexdigest() # noqa: S324
+ unique_slot = hashlib.md5(text.encode()).hexdigest() # noqa: S324
return f"{pathable_slot}-{unique_slot}"
diff --git a/scrapy/responsetypes.py b/scrapy/responsetypes.py
index 3d9dafda6..2e7174701 100644
--- a/scrapy/responsetypes.py
+++ b/scrapy/responsetypes.py
@@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, ClassVar
from scrapy.http import Response
from scrapy.utils.misc import load_object
-from scrapy.utils.python import binary_is_text, to_bytes, to_unicode
+from scrapy.utils.python import binary_is_text, to_unicode
if TYPE_CHECKING:
from collections.abc import Mapping
@@ -102,7 +102,6 @@ class ResponseTypes:
it's not meant to be used except for special cases where response types
cannot be guess using more straightforward methods."""
chunk = body[:5000]
- chunk = to_bytes(chunk)
if not binary_is_text(chunk):
return self.from_mimetype("application/octet-stream")
lowercase_chunk = chunk.lower()
diff --git a/scrapy/robotstxt.py b/scrapy/robotstxt.py
index d980f2004..04066d306 100644
--- a/scrapy/robotstxt.py
+++ b/scrapy/robotstxt.py
@@ -23,7 +23,7 @@ def decode_robotstxt(
) -> str:
try:
if to_native_str_type:
- body_decoded = to_unicode(robotstxt_body)
+ body_decoded = robotstxt_body.decode()
else:
body_decoded = robotstxt_body.decode("utf-8-sig", errors="ignore")
except UnicodeDecodeError:
diff --git a/scrapy/spidermiddlewares/referer.py b/scrapy/spidermiddlewares/referer.py
index 891de5bfe..f728aecdb 100644
--- a/scrapy/spidermiddlewares/referer.py
+++ b/scrapy/spidermiddlewares/referer.py
@@ -16,7 +16,7 @@ from scrapy.http import Request, Response
from scrapy.spidermiddlewares.base import BaseSpiderMiddleware
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.misc import load_object
-from scrapy.utils.python import _looks_like_import_path, to_unicode
+from scrapy.utils.python import _looks_like_import_path
from scrapy.utils.url import strip_url
if TYPE_CHECKING:
@@ -373,7 +373,7 @@ class RefererMiddleware(BaseSpiderMiddleware):
if policy_name is None and isinstance(response, Response):
policy_header = response.headers.get("Referrer-Policy")
if policy_header is not None:
- policy_name = to_unicode(policy_header.decode("latin1"))
+ policy_name = policy_header.decode("latin1")
allow_import_path = False
if policy_name is None:
return self.default_policy()
diff --git a/scrapy/utils/iterators.py b/scrapy/utils/iterators.py
index 540fe407c..36dde8aa0 100644
--- a/scrapy/utils/iterators.py
+++ b/scrapy/utils/iterators.py
@@ -92,7 +92,7 @@ class _StreamReader:
def _read_unicode(self, n: int = 65535) -> bytes:
s, e = self._ptr, self._ptr + n
self._ptr = e
- return cast("str", self._text)[s:e].encode("utf-8")
+ return cast("str", self._text)[s:e].encode()
def csviter(
@@ -179,7 +179,7 @@ def _body_or_str(obj: Response | str | bytes, unicode: bool = True) -> str | byt
return obj.body
if isinstance(obj, TextResponse):
return obj.text
- return obj.body.decode("utf-8")
+ return obj.body.decode()
if isinstance(obj, str):
- return obj if unicode else obj.encode("utf-8")
- return obj.decode("utf-8") if unicode else obj
+ return obj if unicode else obj.encode()
+ return obj.decode() if unicode else obj
diff --git a/scrapy/utils/python.py b/scrapy/utils/python.py
index a163e1021..216b5cd92 100644
--- a/scrapy/utils/python.py
+++ b/scrapy/utils/python.py
@@ -166,7 +166,7 @@ def memoizemethod_noargs(
_BINARYCHARS = {
- i for i in range(32) if to_bytes(chr(i)) not in {b"\0", b"\t", b"\n", b"\r"}
+ i for i in range(32) if chr(i).encode() not in {b"\0", b"\t", b"\n", b"\r"}
}
diff --git a/scrapy/utils/request.py b/scrapy/utils/request.py
index 248b4cd28..1e349cee6 100644
--- a/scrapy/utils/request.py
+++ b/scrapy/utils/request.py
@@ -17,7 +17,7 @@ from w3lib.url import canonicalize_url
from scrapy import Request, Spider
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.misc import load_object
-from scrapy.utils.python import to_bytes, to_unicode
+from scrapy.utils.python import to_bytes
if TYPE_CHECKING:
from collections.abc import Iterable
@@ -106,7 +106,7 @@ def fingerprint(
else:
url = canonicalize_url(request.url, keep_fragments=keep_fragments)
fingerprint_data = {
- "method": to_unicode(request.method),
+ "method": request.method,
"url": url,
"body": (request.body or b"").hex(),
"headers": headers,
@@ -159,8 +159,8 @@ def request_httprepr(request: Request) -> bytes:
"""
parsed = urlparse_cached(request)
path = urlunparse(("", "", parsed.path or "/", parsed.params, parsed.query, ""))
- s = to_bytes(request.method) + b" " + to_bytes(path) + b" HTTP/1.1\r\n"
- s += b"Host: " + to_bytes(parsed.hostname or b"") + b"\r\n"
+ s = f"{request.method} {path} HTTP/1.1\r\n".encode()
+ s += f"Host: {parsed.hostname or ''}\r\n".encode()
if headers := request.headers.to_string():
s += headers + b"\r\n"
s += b"\r\n"
@@ -173,7 +173,7 @@ def referer_str(request: Request) -> str | None:
referrer = request.headers.get("Referer")
if referrer is None:
return referrer
- return to_unicode(referrer, errors="replace")
+ return referrer.decode(errors="replace")
def request_from_dict(d: dict[str, Any], *, spider: Spider | None = None) -> Request:
@@ -235,7 +235,7 @@ def _decode_cookie(cookie: VerboseCookie, request: Request) -> dict[str, str] |
else:
assert isinstance(value, bytes)
try:
- decoded[key] = value.decode("utf8")
+ decoded[key] = value.decode()
except UnicodeDecodeError:
logger.warning(
f"Non UTF-8 encoded cookie found in request {request}: {cookie}",
@@ -253,18 +253,18 @@ def request_to_curl(request: Request) -> str:
"""
method = request.method
- data = f"--data-raw '{request.body.decode('utf-8')}'" if request.body else ""
+ data = f"--data-raw '{request.body.decode()}'" if request.body else ""
header_args: list[str] = []
for name, values in request.headers.items():
- str_name = to_unicode(name, errors="replace")
+ str_name = name.decode(errors="replace")
if not values:
# "Remove an internal header by giving a replacement without
# content on the right side of the colon, as in: -H "Host:"."
# (which is how Scrapy handles empty headers)
header_args.append(f"-H '{str_name}:'")
for value in values:
- str_value = to_unicode(value, errors="replace")
+ str_value = value.decode(errors="replace")
header_args.append(f"-H '{str_name}: {str_value}'")
headers = " ".join(header_args)
diff --git a/scrapy/utils/response.py b/scrapy/utils/response.py
index d06e389b8..984dc7064 100644
--- a/scrapy/utils/response.py
+++ b/scrapy/utils/response.py
@@ -18,7 +18,6 @@ from w3lib import html
from scrapy.http.headers import Headers
from scrapy.utils.misc import load_object
-from scrapy.utils.python import to_bytes, to_unicode
if TYPE_CHECKING:
from collections.abc import Callable, Iterable
@@ -83,8 +82,8 @@ def response_from_dict(d: dict[str, Any]) -> Response:
def response_status_message(status: bytes | float | str) -> str:
"""Return status code plus status text descriptive message"""
status_int = int(status)
- message = http.RESPONSES.get(status_int, "Unknown Status")
- return f"{status_int} {to_unicode(message)}"
+ message = http.RESPONSES.get(status_int, b"Unknown Status").decode()
+ return f"{status_int} {message}"
_DOCTYPE_RE = re.compile(rb"\s*<!doctype[^<>]*>", re.IGNORECASE)
@@ -126,15 +125,13 @@ def open_in_browser(
# any base tag of the response, and matches it when there is one.
doctype = _DOCTYPE_RE.match(body)
index = doctype.end() if doctype else 0
- base_tag = to_bytes(f'<base href="{get_base_url(response)}">')
+ base_tag = f'<base href="{get_base_url(response)}">'.encode()
body = body[:index] + base_tag + body[index:]
ext = ".html"
elif isinstance(response, TextResponse):
ext = ".txt"
else:
- content_type = to_unicode(
- response.headers.get(b"Content-Type") or b"", encoding="latin-1"
- )
+ content_type = (response.headers.get(b"Content-Type") or b"").decode("latin-1")
mimetype = content_type.split(";")[0].strip().lower()
ext = mimetypes.guess_extension(mimetype) or ""
if not ext:
diff --git a/scrapy/utils/ssl.py b/scrapy/utils/ssl.py
index fca4f75fa..e87afd484 100644
--- a/scrapy/utils/ssl.py
+++ b/scrapy/utils/ssl.py
@@ -2,13 +2,12 @@
from __future__ import annotations
import warnings
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, cast
import OpenSSL._util as pyOpenSSLutil
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils._versions import _get_openssl_version as get_openssl_version
-from scrapy.utils.python import to_unicode
if TYPE_CHECKING:
from OpenSSL.crypto import X509Name
@@ -21,7 +20,7 @@ def get_temp_key_info(ssl_object: Any) -> str | None:
def ffi_buf_to_string(buf: Any) -> str:
- return to_unicode(pyOpenSSLutil.ffi.string(buf))
+ return cast("str", pyOpenSSLutil.ffi.string(buf).decode())
def x509name_to_string(x509name: X509Name) -> str:
diff --git a/scrapy/utils/test.py b/scrapy/utils/test.py
index bb26928e5..d461056e5 100644
--- a/scrapy/utils/test.py
+++ b/scrapy/utils/test.py
@@ -119,4 +119,4 @@ def get_web_client_agent_req(url: str) -> Deferred[TxResponse]: # pragma: no co
from twisted.internet import reactor
agent = Agent(reactor)
- return cast("Deferred[TxResponse]", agent.request(b"GET", url.encode("utf-8")))
+ return cast("Deferred[TxResponse]", agent.request(b"GET", url.encode()))
diff --git a/tests/mockserver/http.py b/tests/mockserver/http.py
index 58764c886..9f37af048 100644
--- a/tests/mockserver/http.py
+++ b/tests/mockserver/http.py
@@ -86,7 +86,7 @@ class Root(BaseResource):
self, b"redirect-no-meta-refresh", NoMetaRefreshRedirect(b"/redirected")
)
put_child(self, b"redirected", Data(b"Redirected here", "text/plain"))
- numbers = [str(x).encode("utf8") for x in range(2**18)]
+ numbers = [str(x).encode() for x in range(2**18)]
put_child(self, b"numbers", Data(b"".join(numbers), "text/plain"))
put_child(self, b"wait", ForeverTakingResource())
put_child(self, b"hang-after-headers", ForeverTakingResource(write=True))
diff --git a/tests/mockserver/http_resources.py b/tests/mockserver/http_resources.py
index 4413eac54..d159a04af 100644
--- a/tests/mockserver/http_resources.py
+++ b/tests/mockserver/http_resources.py
@@ -11,7 +11,6 @@ from twisted.web import resource, server
from twisted.web.server import NOT_DONE_YET
from twisted.web.util import Redirect, redirectTo
-from scrapy.utils.python import to_bytes, to_unicode
from tests import get_testdata
if TYPE_CHECKING:
@@ -102,7 +101,7 @@ class ClientIPResource(BaseResource):
client_address = request.getClientAddress()
if client_address is None or client_address.host is None:
return b""
- return to_bytes(client_address.host)
+ return cast("bytes", client_address.host.encode())
class PayloadResource(BaseResource):
@@ -167,11 +166,11 @@ class Follow(LeafResource):
assert request.args is not None
args = request.args.copy()
for nl in nlist:
- args[b"n"] = [to_bytes(str(nl))]
+ args[b"n"] = [str(nl).encode()]
argstr = urlencode(args, doseq=True)
s += f"<a href='/follow?{argstr}'>follow {nl}</a><br>"
s += """</body>"""
- request.write(to_bytes(s))
+ request.write(s.encode())
request.finish()
@@ -207,7 +206,7 @@ class Delay(LeafResource):
return NOT_DONE_YET
def _delayedRender(self, request: Request, n: float) -> None:
- request.write(to_bytes(f"Response delayed for {n:.3f} seconds\n"))
+ request.write(f"Response delayed for {n:.3f} seconds\n".encode())
request.finish()
@@ -273,14 +272,14 @@ class Echo(LeafResource):
assert request.content
output = {
"headers": {
- to_unicode(k, errors="surrogateescape"): [
- to_unicode(v, errors="surrogateescape") for v in vs
+ k.decode(errors="surrogateescape"): [
+ v.decode(errors="surrogateescape") for v in vs
]
for k, vs in request.requestHeaders.getAllRawHeaders()
},
- "body": to_unicode(request.content.read()),
+ "body": request.content.read().decode(),
}
- return to_bytes(json.dumps(output))
+ return json.dumps(output).encode()
render_POST = render_GET
@@ -450,7 +449,7 @@ class ResponseHeadersResource(BaseResource):
request.responseHeaders.setRawHeaders(
header_name, [header_value.encode("utf-8", "surrogateescape")]
)
- return json.dumps(body).encode("utf-8")
+ return json.dumps(body).encode()
class Compress(BaseResource):
diff --git a/tests/mockserver/utils.py b/tests/mockserver/utils.py
index a04ce8c28..ae65ec091 100644
--- a/tests/mockserver/utils.py
+++ b/tests/mockserver/utils.py
@@ -11,7 +11,6 @@ from twisted.internet.ssl import CertificateOptions, ContextFactory
from scrapy.core.downloader.tls import _TWISTED_VERSION_MAP
from scrapy.utils._ssl import _get_cert_options_version_kwargs
-from scrapy.utils.python import to_bytes
if TYPE_CHECKING:
from twisted.internet.interfaces import IOpenSSLContextFactory
@@ -51,5 +50,5 @@ def ssl_context_factory(
ctx = factory.getContext()
# disabling TLS1.3 because it unconditionally enables some strong ciphers
ctx.set_options(SSL.OP_CIPHER_SERVER_PREFERENCE | SSL.OP_NO_TLSv1_3)
- ctx.set_cipher_list(to_bytes(cipher_string))
+ ctx.set_cipher_list(cipher_string.encode())
return cast("ContextFactory", factory)
diff --git a/tests/test_core_downloader.py b/tests/test_core_downloader.py
index 7b9d0dc93..b81f78086 100644
--- a/tests/test_core_downloader.py
+++ b/tests/test_core_downloader.py
@@ -47,7 +47,6 @@ from scrapy.utils.defer import (
maybe_deferred_to_future,
)
from scrapy.utils.misc import build_from_crawler
-from scrapy.utils.python import to_bytes
from scrapy.utils.spider import DefaultSpider
from scrapy.utils.test import get_crawler
from tests import IDNA_REJECTED_HOSTNAMES
@@ -266,7 +265,7 @@ class TestContextFactory(TestContextFactoryBase):
) -> None:
s = "0123456789" * 10
body = await self.get_page(server_url + "payload", factory, body=s)
- assert body == to_bytes(s)
+ assert body == s.encode()
def test_no_context_sharing(self, factory: _ScrapyClientContextFactory) -> None:
"""Every call to creatorForNetloc() should give a fresh context."""
@@ -387,7 +386,7 @@ class TestContextFactoryCiphers(TestContextFactoryBase):
body = await self.get_page(
server_url + "payload", client_context_factory, body=s
)
- assert body == to_bytes(s)
+ assert body == s.encode()
def test_default(self) -> None:
"""The default 'DEFAULT' value is passed to Twisted as is."""
@@ -430,7 +429,7 @@ class TestContextFactoryTLSMethod(TestContextFactoryBase):
body = await self.get_page(
server_url + "payload", client_context_factory, body=s
)
- assert body == to_bytes(s)
+ assert body == s.encode()
@coroutine_test
async def test_setting_default(self, server_url: str) -> None:
diff --git a/tests/test_crawl.py b/tests/test_crawl.py
index da0a08b7b..dc809df43 100644
--- a/tests/test_crawl.py
+++ b/tests/test_crawl.py
@@ -24,7 +24,6 @@ from scrapy.utils.engine import (
get_engine_status,
print_engine_status,
)
-from scrapy.utils.python import to_unicode
from scrapy.utils.test import get_crawler
from tests import NON_EXISTING_RESOLVABLE
from tests.spiders import (
@@ -361,16 +360,16 @@ with multiples lines
assert "responses" in crawler.spider.meta
assert "failures" not in crawler.spider.meta
# start() doesn't set Referer header
- echo0 = json.loads(to_unicode(crawler.spider.meta["responses"][0].body))
+ echo0 = json.loads(crawler.spider.meta["responses"][0].body.decode())
assert "Referer" not in echo0["headers"]
# following request sets Referer to the source request url
- echo1 = json.loads(to_unicode(crawler.spider.meta["responses"][1].body))
+ echo1 = json.loads(crawler.spider.meta["responses"][1].body.decode())
assert echo1["headers"].get("Referer") == [req0.url]
# next request avoids Referer header
- echo2 = json.loads(to_unicode(crawler.spider.meta["responses"][2].body))
+ echo2 = json.loads(crawler.spider.meta["responses"][2].body.decode())
assert "Referer" not in echo2["headers"]
# last request explicitly sets a Referer header
- echo3 = json.loads(to_unicode(crawler.spider.meta["responses"][3].body))
+ echo3 = json.loads(crawler.spider.meta["responses"][3].body.decode())
assert echo3["headers"].get("Referer") == ["http://example.com"]
@coroutine_test
diff --git a/tests/test_crawler_subprocess.py b/tests/test_crawler_subprocess.py
index 7456b48a0..7049bd489 100644
--- a/tests/test_crawler_subprocess.py
+++ b/tests/test_crawler_subprocess.py
@@ -48,7 +48,7 @@ class ScriptRunnerMixin(ABC):
stderr=subprocess.PIPE,
)
_, stderr = p.communicate()
- return stderr.decode("utf-8")
+ return stderr.decode()
class TestCrawlerProcessSubprocessBase(ScriptRunnerMixin):
diff --git a/tests/test_downloader_handler_twisted_ftp.py b/tests/test_downloader_handler_twisted_ftp.py
index bea4d44a5..1f00b9497 100644
--- a/tests/test_downloader_handler_twisted_ftp.py
+++ b/tests/test_downloader_handler_twisted_ftp.py
@@ -19,7 +19,6 @@ from scrapy.http import HtmlResponse, Request, Response
from scrapy.http.response.text import TextResponse
from scrapy.utils.defer import deferred_f_from_coro_f, maybe_deferred_to_future
from scrapy.utils.misc import build_from_crawler
-from scrapy.utils.python import to_bytes
from scrapy.utils.test import get_crawler
if TYPE_CHECKING:
@@ -132,7 +131,7 @@ class TestFTPBase(ABC):
self, server_url: str, dh: FTPDownloadHandler
) -> None:
f, local_fname = mkstemp()
- fname_bytes = to_bytes(local_fname)
+ fname_bytes = local_fname.encode()
local_path = Path(local_fname)
os.close(f)
meta = {"ftp_local_filename": fname_bytes}
diff --git a/tests/test_downloader_handler_twisted_http11.py b/tests/test_downloader_handler_twisted_http11.py
index eb286c916..2c08e6eb0 100644
--- a/tests/test_downloader_handler_twisted_http11.py
+++ b/tests/test_downloader_handler_twisted_http11.py
@@ -91,7 +91,7 @@ def test_tunneling_cancelled_before_connected() -> None:
reactor = MemoryReactorClock()
endpoint = _TunnelingTCP4ClientEndpoint(
reactor=cast("ReactorBase", reactor),
- host="example.com",
+ host=b"example.com",
port=443,
proxyConf=("127.0.0.1", 8080, None),
contextFactory=_load_context_factory_from_settings(get_crawler()),
diff --git a/tests/test_downloadermiddleware.py b/tests/test_downloadermiddleware.py
index 5aebd3160..1c5c5f275 100644
--- a/tests/test_downloadermiddleware.py
+++ b/tests/test_downloadermiddleware.py
@@ -22,7 +22,6 @@ from scrapy.http import Request, Response
from scrapy.spiders import Spider
from scrapy.utils.defer import maybe_deferred_to_future
from scrapy.utils.misc import build_from_crawler
-from scrapy.utils.python import to_bytes
from scrapy.utils.test import get_crawler, get_from_asyncio_queue
from tests.utils.decorators import coroutine_test
@@ -146,7 +145,7 @@ class TestDefaults(TestManagerBase):
async with self.get_mwman() as mwman:
ret = await self._download(mwman, req, resp)
assert isinstance(ret, Request), f"Not redirected: {ret!r}"
- assert to_bytes(ret.url) == resp.headers["Location"], (
+ assert ret.url.encode() == resp.headers["Location"], (
"Not redirected to location header"
)
diff --git a/tests/test_downloadermiddleware_cookies.py b/tests/test_downloadermiddleware_cookies.py
index 87bf71070..c093649e1 100644
--- a/tests/test_downloadermiddleware_cookies.py
+++ b/tests/test_downloadermiddleware_cookies.py
@@ -37,7 +37,7 @@ def _cookie_to_set_cookie_value(cookie: VerboseCookie) -> str | None:
else:
assert isinstance(value, bytes)
try:
- decoded[key] = value.decode("utf8")
+ decoded[key] = value.decode()
except UnicodeDecodeError:
decoded[key] = value.decode("latin1", errors="replace")
diff --git a/tests/test_downloadermiddleware_defaultheaders.py b/tests/test_downloadermiddleware_defaultheaders.py
index 507097df9..1f137de5c 100644
--- a/tests/test_downloadermiddleware_defaultheaders.py
+++ b/tests/test_downloadermiddleware_defaultheaders.py
@@ -4,14 +4,13 @@ from scrapy.downloadermiddlewares.defaultheaders import DefaultHeadersMiddleware
from scrapy.http import Request
from scrapy.spiders import Spider
from scrapy.utils.misc import build_from_crawler
-from scrapy.utils.python import to_bytes
from scrapy.utils.test import get_crawler
def get_defaults_mw() -> tuple[dict[bytes, list[bytes]], DefaultHeadersMiddleware]:
crawler = get_crawler(Spider)
defaults = {
- to_bytes(k): [to_bytes(v)]
+ k.encode(): [v.encode()]
for k, v in crawler.settings.get("DEFAULT_REQUEST_HEADERS").items()
}
return defaults, build_from_crawler(DefaultHeadersMiddleware, crawler)
diff --git a/tests/test_downloadermiddleware_redirect_metarefresh.py b/tests/test_downloadermiddleware_redirect_metarefresh.py
index bee79ba14..d118da005 100644
--- a/tests/test_downloadermiddleware_redirect_metarefresh.py
+++ b/tests/test_downloadermiddleware_redirect_metarefresh.py
@@ -23,7 +23,7 @@ from tests.utils.redirect import (
def meta_refresh_body(url: str, interval: int = 5) -> bytes:
html = f"""<html><head><meta http-equiv="refresh" content="{interval};url={url}"/></head></html>"""
- return html.encode("utf-8")
+ return html.encode()
class TestMetaRefreshMiddleware(TestRedirectBase):
diff --git a/tests/test_dupefilters.py b/tests/test_dupefilters.py
index 98dfa62cc..38ad4b689 100644
--- a/tests/test_dupefilters.py
+++ b/tests/test_dupefilters.py
@@ -14,7 +14,6 @@ from scrapy.dupefilters import BaseDupeFilter, DiskDupeFilter, RFPDupeFilter
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.http import Request
from scrapy.utils.misc import build_from_crawler
-from scrapy.utils.python import to_bytes
from scrapy.utils.test import get_crawler
from tests.spiders import SimpleSpider
@@ -100,7 +99,7 @@ class DupeFilterTestMixin:
class CaseInsensitiveRequestFingerprinter:
def fingerprint(self, request: Request) -> bytes:
- return hashlib.sha1(to_bytes(request.url.lower())).digest()
+ return hashlib.sha1(request.url.lower().encode()).digest()
case_insensitive_dupefilter = self._get_dupefilter(
REQUEST_FINGERPRINTER_CLASS=CaseInsensitiveRequestFingerprinter
@@ -242,7 +241,7 @@ class TestRFPDupeFilter(DupeFilterTestMixin):
def test_request_fingerprint_override_deprecation(self):
class LegacyDupeFilter(RFPDupeFilter):
def request_fingerprint(self, request):
- return hashlib.sha1(to_bytes(request.url.lower())).hexdigest()
+ return hashlib.sha1(request.url.lower().encode()).hexdigest()
with pytest.warns(
ScrapyDeprecationWarning,
diff --git a/tests/test_engine.py b/tests/test_engine.py
index 2a8e936a8..103ee79b8 100644
--- a/tests/test_engine.py
+++ b/tests/test_engine.py
@@ -281,7 +281,7 @@ class TestEngine(TestEngineBase):
p.communicate()
pytest.fail("Command took too much time to complete")
- stderr_str = stderr.decode("utf-8")
+ stderr_str = stderr.decode()
assert "AttributeError" not in stderr_str, stderr_str
assert "AssertionError" not in stderr_str, stderr_str
diff --git a/tests/test_engine_stop_download_bytes.py b/tests/test_engine_stop_download_bytes.py
index b20ffd8d2..c0386acec 100644
--- a/tests/test_engine_stop_download_bytes.py
+++ b/tests/test_engine_stop_download_bytes.py
@@ -61,5 +61,5 @@ class TestBytesReceivedEngine(TestEngineBase):
# Received bytes are not the complete response. The exact amount depends
# on the buffer size, which can vary, so we only check that the amount
# of received bytes is strictly less than the full response.
- numbers = [str(x).encode("utf8") for x in range(2**18)]
+ numbers = [str(x).encode() for x in range(2**18)]
assert len(joined_data) < len(b"".join(numbers))
diff --git a/tests/test_exporters.py b/tests/test_exporters.py
index 36c45ecc4..573d23752 100644
--- a/tests/test_exporters.py
+++ b/tests/test_exporters.py
@@ -76,8 +76,6 @@ class TestBaseItemExporter(ABC):
pass
def _assert_expected_item(self, exported_dict: dict[str, Any]) -> None:
- for k, v in exported_dict.items():
- exported_dict[k] = to_unicode(v)
assert self.i == self.item_class(**exported_dict)
@staticmethod
@@ -309,9 +307,7 @@ class TestCsvItemExporter(TestBaseItemExporter):
def _check_output(self) -> None:
self.output.seek(0)
- self.assertCsvEqual(
- to_unicode(self.output.read()), "age,name\r\n22,John\xa3\r\n"
- )
+ self.assertCsvEqual(self.output.read(), "age,name\r\n22,John\xa3\r\n")
def assertExportResult(
self, item: Any, expected: bytes | str = b"", **kwargs: Any
@@ -553,7 +549,7 @@ class TestJsonLinesItemExporter(TestBaseItemExporter):
return JsonLinesItemExporter(self.output, **kwargs)
def _check_output(self) -> None:
- exported = json.loads(to_unicode(self.output.getvalue().strip()))
+ exported = json.loads(self.output.getvalue().strip())
assert exported == ItemAdapter(self.i).asdict()
def test_nested_item(self):
@@ -564,7 +560,7 @@ class TestJsonLinesItemExporter(TestBaseItemExporter):
self.ie.export_item(i3)
self.ie.finish_exporting()
del self.ie # See the first “del self.ie” in this file for context.
- exported = json.loads(to_unicode(self.output.getvalue()))
+ exported = json.loads(self.output.getvalue())
assert exported == self._expected_nested
def test_extra_keywords(self):
@@ -580,7 +576,7 @@ class TestJsonLinesItemExporter(TestBaseItemExporter):
self.ie.export_item(item)
self.ie.finish_exporting()
del self.ie # See the first “del self.ie” in this file for context.
- exported = json.loads(to_unicode(self.output.getvalue()))
+ exported = json.loads(self.output.getvalue())
item["time"] = item["time"].isoformat()
assert exported == item
@@ -597,7 +593,7 @@ class TestJsonItemExporter(TestJsonLinesItemExporter):
return JsonItemExporter(self.output, **kwargs)
def _check_output(self) -> None:
- exported = json.loads(to_unicode(self.output.getvalue().strip()))
+ exported = json.loads(self.output.getvalue().strip())
assert exported == [ItemAdapter(self.i).asdict()]
def assertTwoItemsExported(self, item: Any) -> None:
@@ -606,7 +602,7 @@ class TestJsonItemExporter(TestJsonLinesItemExporter):
self.ie.export_item(item)
self.ie.finish_exporting()
del self.ie # See the first “del self.ie” in this file for context.
- exported = json.loads(to_unicode(self.output.getvalue()))
+ exported = json.loads(self.output.getvalue())
assert exported == [ItemAdapter(item).asdict(), ItemAdapter(item).asdict()]
def test_two_items(self):
@@ -627,7 +623,7 @@ class TestJsonItemExporter(TestJsonLinesItemExporter):
self.ie.export_item(i2)
self.ie.export_item(i3)
self.ie.finish_exporting()
- exported = json.loads(to_unicode(self.output.getvalue()))
+ exported = json.loads(self.output.getvalue())
assert exported == [dict(i1), dict(i3)]
def test_nested_item(self):
@@ -638,7 +634,7 @@ class TestJsonItemExporter(TestJsonLinesItemExporter):
self.ie.export_item(i3)
self.ie.finish_exporting()
del self.ie # See the first “del self.ie” in this file for context.
- exported = json.loads(to_unicode(self.output.getvalue()))
+ exported = json.loads(self.output.getvalue())
expected = {
"name": "Jesus",
"age": {"name": "Maria", "age": ItemAdapter(i1).asdict()},
@@ -653,7 +649,7 @@ class TestJsonItemExporter(TestJsonLinesItemExporter):
self.ie.export_item(i3)
self.ie.finish_exporting()
del self.ie # See the first “del self.ie” in this file for context.
- exported = json.loads(to_unicode(self.output.getvalue()))
+ exported = json.loads(self.output.getvalue())
expected = {"name": "Jesus", "age": {"name": "Maria", "age": i1}}
assert exported == [expected]
@@ -663,7 +659,7 @@ class TestJsonItemExporter(TestJsonLinesItemExporter):
self.ie.export_item(item)
self.ie.finish_exporting()
del self.ie # See the first “del self.ie” in this file for context.
- exported = json.loads(to_unicode(self.output.getvalue()))
+ exported = json.loads(self.output.getvalue())
item["time"] = item["time"].isoformat()
assert exported == [item]
@@ -683,7 +679,7 @@ class TestJsonItemExporterToBytes(TestBaseItemExporter):
self.ie.export_item(i2)
self.ie.export_item(i3)
self.ie.finish_exporting()
- exported = json.loads(to_unicode(self.output.getvalue(), encoding="latin"))
+ exported = json.loads(self.output.getvalue().decode(encoding="latin-1"))
assert exported == [dict(i1), dict(i3)]
diff --git a/tests/test_extension_telnet.py b/tests/test_extension_telnet.py
index 194b5b242..d470e3f03 100644
--- a/tests/test_extension_telnet.py
+++ b/tests/test_extension_telnet.py
@@ -73,7 +73,7 @@ async def test_bad_credentials() -> None:
async def test_good_credentials() -> None:
with _get_console_and_portal() as (console, portal):
creds = credentials.UsernamePassword(
- console.username.encode("utf8"), console.password.encode("utf8")
+ console.username.encode(), console.password.encode()
)
d = portal.login(creds, None, ITelnetProtocol)
await maybe_deferred_to_future(d)
diff --git a/tests/test_http_request.py b/tests/test_http_request.py
index b9cec93a1..cf4b4ae0a 100644
--- a/tests/test_http_request.py
+++ b/tests/test_http_request.py
@@ -5,7 +5,6 @@ import pytest
from scrapy import Request
from scrapy.http import XmlRpcRequest
-from scrapy.utils.python import to_bytes
from tests.utils.bases.http_request import TestRequestBase
@@ -21,8 +20,8 @@ class TestXmlRpcRequest(TestRequestBase):
def _test_request(self, **kwargs: Any) -> None:
r = self.request_class("http://scrapytest.org/rpc2", **kwargs)
assert r.headers[b"Content-Type"] == b"text/xml"
- assert r.body == to_bytes(
- xmlrpc.client.dumps(**kwargs), encoding=kwargs.get("encoding", "utf-8")
+ assert r.body == xmlrpc.client.dumps(**kwargs).encode(
+ encoding=kwargs.get("encoding", "utf-8")
)
assert r.method == "POST"
assert r.encoding == kwargs.get("encoding", "utf-8")
diff --git a/tests/test_http_request_form.py b/tests/test_http_request_form.py
index 8d82a4a49..8c6e74dc4 100644
--- a/tests/test_http_request_form.py
+++ b/tests/test_http_request_form.py
@@ -10,7 +10,6 @@ import pytest
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.http import FormRequest, HtmlResponse
from scrapy.utils.httpobj import urlparse_cached
-from scrapy.utils.python import to_unicode
from tests.utils.bases.http_request import TestRequestBase
if TYPE_CHECKING:
@@ -38,7 +37,7 @@ def _qs_unicode(req: Request, encoding: str = "utf-8") -> dict[str, list[str]]:
def _assert_query_equal(first: bytes, second: bytes) -> None:
- assert sorted(to_unicode(first).split("&")) == sorted(to_unicode(second).split("&"))
+ assert sorted(first.decode().split("&")) == sorted(second.decode().split("&"))
# FormRequest.from_response() is deprecated in favor of form2request, so the
diff --git a/tests/test_http_request_json.py b/tests/test_http_request_json.py
index 1bfbbbdf5..932ab1bb9 100644
--- a/tests/test_http_request_json.py
+++ b/tests/test_http_request_json.py
@@ -7,7 +7,6 @@ from unittest import mock
import pytest
from scrapy.http import JsonRequest
-from scrapy.utils.python import to_bytes
from tests.utils.bases.http_request import TestRequestBase
@@ -31,11 +30,11 @@ class TestJsonRequest(TestRequestBase):
"name": "value",
}
r3 = self.request_class(url="http://www.example.com/", data=data)
- assert r3.body == to_bytes(json.dumps(data))
+ assert r3.body == json.dumps(data).encode()
# empty data
r4 = self.request_class(url="http://www.example.com/", data=[])
- assert r4.body == to_bytes(json.dumps([]))
+ assert r4.body == json.dumps([]).encode()
def test_data_method(self):
# data is not passed
@@ -89,7 +88,7 @@ class TestJsonRequest(TestRequestBase):
"error", category=UserWarning, message="Both body and data passed"
)
r7 = self.request_class(url="http://www.example.com/", body=None, data=data)
- assert r7.body == to_bytes(json.dumps(data))
+ assert r7.body == json.dumps(data).encode()
assert r7.method == "POST"
def test_body_data_none(self):
@@ -136,7 +135,7 @@ class TestJsonRequest(TestRequestBase):
}
r1 = self.request_class(url="http://www.example.com/", data=data1)
r2 = r1.replace(data=data2)
- assert r2.body == to_bytes(json.dumps(data2))
+ assert r2.body == json.dumps(data2).encode()
def test_replace_sort_keys(self):
"""Test that replace provides sort_keys=True to json.dumps"""
diff --git a/tests/test_http_response_text.py b/tests/test_http_response_text.py
index 4f5845095..622fe9205 100644
--- a/tests/test_http_response_text.py
+++ b/tests/test_http_response_text.py
@@ -11,7 +11,6 @@ import pytest
from scrapy.http import HtmlResponse, TextResponse, XmlResponse
from scrapy.selector import Selector
-from scrapy.utils.python import to_unicode
from tests.utils.bases.http_response import TestResponseBase
@@ -57,7 +56,7 @@ class TestTextResponse(TestResponseBase):
resp = self.response_class(
url="http://www.example.com/price/\xa3", encoding="utf-8"
)
- assert resp.url == to_unicode(b"http://www.example.com/price/\xc2\xa3")
+ assert resp.url == b"http://www.example.com/price/\xc2\xa3".decode()
resp = self.response_class(
url="http://www.example.com/price/\xa3", encoding="latin-1"
)
@@ -66,7 +65,7 @@ class TestTextResponse(TestResponseBase):
"http://www.example.com/price/\xa3",
headers={"Content-type": ["text/html; charset=utf-8"]},
)
- assert resp.url == to_unicode(b"http://www.example.com/price/\xc2\xa3")
+ assert resp.url == b"http://www.example.com/price/\xc2\xa3".decode()
resp = self.response_class(
"http://www.example.com/price/\xa3",
headers={"Content-type": ["text/html; charset=iso-8859-1"]},
diff --git a/tests/test_mail.py b/tests/test_mail.py
index a43dca7bd..286c61bd3 100644
--- a/tests/test_mail.py
+++ b/tests/test_mail.py
@@ -113,7 +113,7 @@ class TestMailSender:
msg = self.catched_msg["msg"]
assert msg["subject"] == subject
- assert msg.get_payload(decode=True).decode("utf-8") == body
+ assert msg.get_payload(decode=True).decode() == body
assert msg.get_charset() == Charset("utf-8")
assert msg.get("Content-Type") == 'text/plain; charset="utf-8"'
@@ -121,7 +121,7 @@ class TestMailSender:
subject = "sübjèçt"
body = "bödÿ-àéïöñß"
attach = BytesIO()
- attach.write(body.encode("utf-8"))
+ attach.write(body.encode())
attach.seek(0)
attachs = [("attachment", "text/plain", attach)]
@@ -149,9 +149,9 @@ class TestMailSender:
assert len(payload) == 2
text, attach = payload
- assert text.get_payload(decode=True).decode("utf-8") == body
+ assert text.get_payload(decode=True).decode() == body
assert text.get_charset() == Charset("utf-8")
- assert attach.get_payload(decode=True).decode("utf-8") == body
+ assert attach.get_payload(decode=True).decode() == body
def test_create_sender_factory_with_host(self):
mailsender = MailSender(debug=False, smtphost="smtp.testhost.com")
diff --git a/tests/test_request_attribute_binding.py b/tests/test_request_attribute_binding.py
index dd4adbe7e..85e300e40 100644
--- a/tests/test_request_attribute_binding.py
+++ b/tests/test_request_attribute_binding.py
@@ -32,7 +32,7 @@ class CatchExceptionOverrideRequestMiddleware:
def process_exception(self, request, exception):
return Response(
url="http://localhost/",
- body=b"Caught " + exception.__class__.__name__.encode("utf-8"),
+ body=b"Caught " + exception.__class__.__name__.encode(),
request=Request(OVERRIDDEN_URL),
)
@@ -41,7 +41,7 @@ class CatchExceptionDoNotOverrideRequestMiddleware:
def process_exception(self, request, exception):
return Response(
url="http://localhost/",
- body=b"Caught " + exception.__class__.__name__.encode("utf-8"),
+ body=b"Caught " + exception.__class__.__name__.encode(),
)
diff --git a/tests/test_utils_iterators.py b/tests/test_utils_iterators.py
index 672ae0be6..eefb562bd 100644
--- a/tests/test_utils_iterators.py
+++ b/tests/test_utils_iterators.py
@@ -92,7 +92,7 @@ class TestXmliter:
for r in (
# with bytes
- XmlResponse(url="http://example.com", body=body.encode("utf-8")),
+ XmlResponse(url="http://example.com", body=body.encode()),
# Unicode body needs encoding information
XmlResponse(url="http://example.com", body=body, encoding="utf-8"),
):
@@ -423,7 +423,7 @@ class TestUtilsCsv:
headers, body = sample[0].split(b","), b"\n".join(sample[1:])
response = TextResponse(url="http://example.com/", body=body)
- csv = csviter(response, headers=[h.decode("utf-8") for h in headers])
+ csv = csviter(response, headers=[h.decode() for h in headers])
assert list(csv) == [
{"id": "1", "name": "alpha", "value": "foobar"},
@@ -488,7 +488,7 @@ class TestUtilsCsv:
class TestBodyOrStr:
bbody = b"utf8-body"
- ubody = bbody.decode("utf8")
+ ubody = bbody.decode()
@pytest.mark.parametrize(
"obj",
diff --git a/tests/test_utils_request.py b/tests/test_utils_request.py
index ce0ac8ff5..9d3ced599 100644
--- a/tests/test_utils_request.py
+++ b/tests/test_utils_request.py
@@ -8,7 +8,6 @@ from weakref import WeakKeyDictionary
import pytest
from scrapy.http import Request
-from scrapy.utils.python import to_bytes
from scrapy.utils.request import (
_fingerprint_cache,
fingerprint,
@@ -342,7 +341,7 @@ class TestCustomRequestFingerprinter:
def fingerprint(self, request: Request) -> bytes:
if request not in self.cache:
fp = sha1()
- fp.update(to_bytes(request.url))
+ fp.update(request.url.encode())
self.cache[request] = fp.digest()
return self.cache[request]
diff --git a/tests/test_utils_response.py b/tests/test_utils_response.py
index 0ad9bd7be..915a28802 100644
--- a/tests/test_utils_response.py
+++ b/tests/test_utils_response.py
@@ -7,7 +7,6 @@ from urllib.parse import urlparse
import pytest
from scrapy.http import HtmlResponse, Response, TextResponse
-from scrapy.utils.python import to_bytes
from scrapy.utils.response import (
get_base_url,
get_meta_refresh,
@@ -31,7 +30,7 @@ def test_open_in_browser():
def browser_open(burl: str) -> bool:
bbody = _read_browser_output(burl)
- assert b'<base href="' + to_bytes(url) + b'">' in bbody
+ assert b'<base href="' + url.encode() + b'">' in bbody
return True
response = HtmlResponse(url, body=body)
@@ -200,7 +199,7 @@ def test_inject_base_url(body: bytes) -> None:
def check_base_url(burl):
bbody = _read_browser_output(burl)
- base_tag = b'<base href="' + to_bytes(url) + b'">'
+ base_tag = b'<base href="' + url.encode() + b'">'
assert bbody.count(base_tag) == 1
index = bbody.index(base_tag)
# The base tag is not commented out.
@@ -302,7 +301,7 @@ def test_open_in_browser_injects_base_when_only_in_comment():
def check(burl):
bbody = _read_browser_output(burl)
- assert b'<base href="' + to_bytes(url) + b'">' in bbody
+ assert b'<base href="' + url.encode() + b'">' in bbody
return True
response = HtmlResponse(url, body=body)
@@ -321,8 +320,8 @@ def test_open_in_browser_injects_base_before_head_contents():
def check(burl):
bbody = _read_browser_output(burl)
- assert bbody.count(b'<base href="' + to_bytes(url) + b'">') == 1
- base_pos = bbody.find(b'<base href="' + to_bytes(url) + b'">')
+ assert bbody.count(b'<base href="' + url.encode() + b'">') == 1
+ base_pos = bbody.find(b'<base href="' + url.encode() + b'">')
title_pos = bbody.find(b"<title>Actual</title>")
assert base_pos < title_pos
return True
diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.py
index 4aff40527..6a3abd0ae 100644
--- a/tests/utils/bases/download_handlers_http.py
+++ b/tests/utils/bases/download_handlers_http.py
@@ -203,7 +203,7 @@ class TestHttpBase(ABC):
async with self.get_dh() as download_handler:
response = await download_handler.download_request(request)
assert response.status == HTTPStatus.OK
- body = json.loads(response.body.decode("utf-8"))
+ body = json.loads(response.body.decode())
assert "headers" in body
for header_name, header_value in request_headers.items():
assert header_name in body["headers"]
@@ -223,7 +223,7 @@ class TestHttpBase(ABC):
async with self.get_dh() as download_handler:
response = await download_handler.download_request(request)
assert response.status == HTTPStatus.OK
- body = json.loads(response.body.decode("utf-8"))
+ body = json.loads(response.body.decode())
assert "headers" in body
for header_name in request_headers:
assert header_name not in body["headers"]
@@ -247,7 +247,7 @@ class TestHttpBase(ABC):
async with self.get_dh() as download_handler:
response = await download_handler.download_request(request)
assert response.status == HTTPStatus.OK
- body = json.loads(response.body.decode("utf-8"))
+ body = json.loads(response.body.decode())
assert "headers" in body
assert body["headers"]["X-Custom-Header"] == ["foo", "bar"]
@@ -260,7 +260,7 @@ class TestHttpBase(ABC):
async with self.get_dh() as download_handler:
response = await download_handler.download_request(request)
assert response.status == HTTPStatus.OK
- body = json.loads(response.body.decode("utf-8"))
+ body = json.loads(response.body.decode())
assert body["headers"]["X-Custom-Header"] == ["café"]
@coroutine_test
@@ -274,7 +274,7 @@ class TestHttpBase(ABC):
async with self.get_dh() as download_handler:
response = await download_handler.download_request(request)
assert response.status == HTTPStatus.OK
- body = json.loads(response.body.decode("utf-8"))
+ body = json.loads(response.body.decode())
# the mockserver decodes invalid UTF-8 with surrogateescape
received = [
value.encode("utf-8", "surrogateescape")
@@ -293,7 +293,7 @@ class TestHttpBase(ABC):
async with self.get_dh() as download_handler:
response = await download_handler.download_request(request)
assert response.status == HTTPStatus.OK
- body = json.loads(response.body.decode("utf-8"))
+ body = json.loads(response.body.decode())
assert "headers" in body
received_headers = set(body["headers"].keys())
allowed_headers = {
@@ -318,7 +318,7 @@ class TestHttpBase(ABC):
async with self.get_dh() as download_handler:
response = await download_handler.download_request(request)
assert response.status == HTTPStatus.OK
- body = json.loads(response.body.decode("utf-8"))
+ body = json.loads(response.body.decode())
assert json.loads(body["body"]) == request_body
@coroutine_test
@@ -373,9 +373,7 @@ class TestHttpBase(ABC):
assert header_name in response.headers, (
f"Response was missing expected header {header_name}"
)
- assert response.headers.getlist(header_name) == [
- header_value.encode(encoding="utf-8")
- ]
+ assert response.headers.getlist(header_name) == [header_value.encode()]
@coroutine_test
async def test_download_no_extra_response_headers(
diff --git a/tests/utils/bases/engine.py b/tests/utils/bases/engine.py
index cd34d828d..f00e4675d 100644
--- a/tests/utils/bases/engine.py
+++ b/tests/utils/bases/engine.py
@@ -139,7 +139,7 @@ class TestEngineBase:
# signal was fired multiple times
assert len(data) > 1
# bytes were received in order
- numbers = [str(x).encode("utf8") for x in range(2**18)]
+ numbers = [str(x).encode() for x in range(2**18)]
assert joined_data == b"".join(numbers)
@staticmethod