Skip to content

Commit 4a7f552

Browse files
committed
fix(corekit,utilities): unquote a StringField's bytes on Python 3.8 through compat.unquote (#1693)
StringField(unquote=True) handed the raw field octets to urllib.parse.unquote, which accepts bytes only from Python 3.9; on 3.8 every unquoting read raised "TypeError: Expected str, got bytes". pcapkit.utilities.compat now exports unquote behind a sys.version_info gate: from 3.9 it is urllib.parse.unquote itself; below 3.9 it spells out what 3.9 does for bytes, unquote_to_bytes(value).decode(encoding, errors), and passes anything else to the interpreter's own unquote. StringField imports it for both call sites, including the UnicodeError fallback, and the docs' compatibility table lists it. Tests: test_compat checks the running interpreter's unquote and the pre-3.9 branch (under the faked (3, 5), once more with a bytes-rejecting unquote) against one table pinned to 3.9's results; WARM_BEFORE_FAKING gains urllib.parse. The StringField table stays, plus a check that the field unquotes through compat.
1 parent 375d37a commit 4a7f552

5 files changed

Lines changed: 179 additions & 9 deletions

File tree

‎docs/source/pcapkit/utilities/index.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ following objects and functions:
4848
- Python 3.9
4949
* - :class:`dict[KT, VT] <dict>`
5050
- Python 3.9
51+
* - :func:`urllib.parse.unquote` on :obj:`bytes`
52+
- Python 3.9
5153
* - :class:`enum.StrEnum`
5254
- Python 3.11
5355
* - :func:`typing.final`

‎pcapkit/corekit/fields/strings.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
from pcapkit.corekit.fields.field import NO_VALUE, Field
88
from pcapkit.utilities.chardet import detect
9-
from pcapkit.utilities.compat import Dict
9+
from pcapkit.utilities.compat import Dict, unquote
1010
from pcapkit.utilities.exceptions import FieldValueError
1111

1212
__all__ = [
@@ -138,7 +138,7 @@ class StringField(_TextField[str]):
138138
def __init__(self, length: 'int | Callable[[dict[str, Any]], int]',
139139
default: 'str | NoValueType' = NO_VALUE, encoding: 'Optional[str]' = None,
140140
errors: 'Literal["strict", "ignore", "replace"]' = 'strict',
141-
unquote: 'bool' = False,
141+
unquote: 'bool' = False, # pylint: disable=redefined-outer-name
142142
callback: 'Callable[[Self, dict[str, Any]], None]' = lambda *_: None) -> 'None':
143143
super().__init__(length, default, callback)
144144

@@ -198,9 +198,9 @@ def post_process(self, value: 'bytes', packet: 'dict[str, Any]') -> 'str': # py
198198
"""
199199
if self._unquote:
200200
try:
201-
ret = urllib_parse.unquote(value, encoding=self._encoding or 'utf-8', errors=self._errors)
201+
ret = unquote(value, encoding=self._encoding or 'utf-8', errors=self._errors)
202202
except UnicodeError:
203-
ret = urllib_parse.unquote(value.replace(b'%', rb'\x'), encoding='utf-8', errors='replace')
203+
ret = unquote(value.replace(b'%', rb'\x'), encoding='utf-8', errors='replace')
204204
else:
205205
charset = self._encoding or detect(value)
206206
try:

‎pcapkit/utilities/compat.py‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
__all__ = [
1010
# functions
11-
'final', 'localcontext', 'show_flag_values',
11+
'final', 'localcontext', 'show_flag_values', 'unquote',
1212

1313
# exceptions
1414
'ModuleNotFoundError',
@@ -131,6 +131,25 @@ def __get__(self, instance: 'Optional[_S]',
131131
List: 'TypeAlias' = list
132132
Dict: 'TypeAlias' = dict
133133

134+
# urllib.parse.unquote accepts bytes from 3.9; before it, it raises
135+
# ``TypeError: Expected str, got bytes`` on them (issue #1693)
136+
if sys.version_info < (3, 9):
137+
from urllib.parse import unquote as _unquote
138+
from urllib.parse import unquote_to_bytes as _unquote_to_bytes
139+
140+
def unquote(string: 'str | bytes', encoding: 'str' = 'utf-8', errors: 'str' = 'replace') -> 'str':
141+
"""Replace %xx escapes by their single-character equivalent. The optional
142+
encoding and errors parameters specify how to decode percent-encoded
143+
sequences into Unicode characters, as accepted by the bytes.decode()
144+
method. A bytes string is unquoted to octets first and then decoded,
145+
as from Python 3.9; anything else goes to this interpreter's own
146+
unquote unchanged."""
147+
if isinstance(string, bytes):
148+
return _unquote_to_bytes(string).decode(encoding, errors)
149+
return _unquote(string, encoding, errors)
150+
else:
151+
from urllib.parse import unquote
152+
134153
# The ``else`` branch of each ``sys.version_info`` guard below imports a name
135154
# that only exists on the newer interpreter, so it never executes on the older
136155
# one the guard is there to support. Vermin's analysis is static and cannot see

‎tests/corekit/test_stringfield_lossless_unit.py‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import pickle
2828
import tempfile
2929
import unittest
30+
import urllib.parse
3031

3132
from tests._support import reimport_once_per_class
3233

@@ -152,6 +153,90 @@ def test_decoded_string_compares_and_hashes_as_its_text(self) -> None:
152153
self.assertEqual({value: 1}['été'], 1)
153154

154155

156+
#: ``(octets, field keyword arguments, decoded text, whether it is a DecodedString)``
157+
#: for ``unquote=True``, each as Python 3.9+ decodes it. A text holding a literal
158+
#: ``\xE9`` is the ``UnicodeError`` fallback, which decodes with ``%`` turned into ``\x``.
159+
UNQUOTED = (
160+
(b'', {}, '', False),
161+
(b'a%2fb%2F', {}, 'a/b/', True),
162+
(b'%C3%A9', {}, 'é', False),
163+
(b'caf%E9', {'encoding': 'latin-1'}, 'café', False),
164+
(b'a+b%20c', {}, 'a+b c', True),
165+
(b'%zz%', {}, '%zz%', True),
166+
(b'%E9', {'errors': 'replace'}, '�', True),
167+
(b'%E9', {'errors': 'ignore'}, '', True),
168+
(b'%FF%FEa%00', {'encoding': 'utf-16'}, 'a', True),
169+
(b'%E9', {}, '\\xE9', True),
170+
(b'\xff%41', {}, '�\\x41', True),
171+
(b'%ED%A0%80', {}, '\\xED\\xA0\\x80', True),
172+
(b'%C3%A9', {'encoding': 'ascii'}, '\\xC3\\xA9', True),
173+
(b'%E9', {'encoding': 'idna'}, '\\xE9', True),
174+
)
175+
176+
177+
class TestStringFieldUnquote(unittest.TestCase):
178+
"""``unquote=True`` decodes alike on every Python (#1693).
179+
180+
:func:`urllib.parse.unquote` accepts :obj:`bytes` only from Python 3.9, and
181+
every value a field unpacks is :obj:`bytes`, so on 3.8 each of these raised
182+
``TypeError: Expected str, got bytes``.
183+
"""
184+
185+
def setUp(self) -> None:
186+
reimport_once_per_class(self)
187+
188+
def check_table(self) -> None:
189+
from pcapkit.corekit.fields.strings import DecodedString, StringField
190+
191+
for octets, kwargs, text, decoded in UNQUOTED:
192+
with self.subTest(octets=octets, kwargs=kwargs):
193+
field = StringField(length=len(octets), unquote=True, **kwargs) # type: ignore[arg-type]
194+
value = field.unpack(octets, {})
195+
self.assertEqual(str(value), text)
196+
self.assertIs(isinstance(value, DecodedString), decoded)
197+
self.assertEqual(field.pack(value, {}), octets)
198+
199+
def test_unquote_decodes_as_python_3_9_does(self) -> None:
200+
self.check_table()
201+
202+
def test_unquote_is_the_compat_one(self) -> None:
203+
"""The field unquotes through :func:`pcapkit.utilities.compat.unquote`.
204+
205+
That is where the version gate lives, and
206+
:mod:`tests.utilities.test_compat` runs both of its branches, the pre-3.9
207+
one included, on every Python.
208+
"""
209+
from pcapkit.corekit.fields import strings
210+
from pcapkit.utilities import compat
211+
212+
self.assertIs(strings.unquote, compat.unquote)
213+
214+
def test_a_value_that_is_not_bytes_still_goes_to_urllib(self) -> None:
215+
"""Only :obj:`bytes` take the 3.9 path; the fix leaves anything else as it was.
216+
217+
A field never unpacks one, but :meth:`post_process` is public: text is
218+
unquoted, while a :obj:`bytearray` or :obj:`memoryview` raises exactly what
219+
:func:`urllib.parse.unquote` raises on it.
220+
"""
221+
from pcapkit.corekit.fields.strings import DecodedString, StringField
222+
223+
field = StringField(length=5, unquote=True)
224+
value = field.post_process('a%20b', {}) # type: ignore[arg-type]
225+
self.assertIsInstance(value, DecodedString)
226+
self.assertEqual((str(value), value.raw), ('a b', 'a%20b'))
227+
latin = StringField(length=6, unquote=True, encoding='latin-1')
228+
self.assertEqual(latin.post_process('caf%E9', {}), 'café') # type: ignore[arg-type]
229+
230+
for octets, error in ((bytearray(b'a%20b'), TypeError),
231+
(memoryview(b'a%20b'), AttributeError)):
232+
with self.subTest(type=type(octets).__name__):
233+
with self.assertRaises(error) as expected:
234+
urllib.parse.unquote(octets, 'utf-8', 'strict') # type: ignore[arg-type]
235+
with self.assertRaises(error) as raised:
236+
field.post_process(octets, {}) # type: ignore[arg-type]
237+
self.assertEqual(str(raised.exception), str(expected.exception))
238+
239+
155240
class TestStringFieldDumpers(unittest.TestCase):
156241
"""The dumpers render an undecodable octet rather than failing on it."""
157242

‎tests/utilities/test_compat.py‎

Lines changed: 68 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@
5555
import importlib
5656
import sys
5757
import unittest
58+
import urllib.parse
59+
from typing import Callable
5860
from unittest import mock
5961

6062
from tests._support import load_module, purge_modules, reimport_once_per_class
@@ -106,8 +108,9 @@
106108
#: running the test until it stopped complaining, and that distinction is the
107109
#: point of having it. Every import statement on a branch reachable at ``(3, 5)``:
108110
#: :mod:`collections.abc` (line 34), :mod:`pathlib` (63), :mod:`threading` (67),
109-
#: :mod:`typing` (4, 68, 126), :mod:`aenum` (143), :mod:`typing_extensions` (148,
110-
#: 202), :mod:`contextlib` (153), :mod:`decimal` (154), :mod:`enum` (179).
111+
#: :mod:`typing` (4, 68, 126), :mod:`urllib.parse` (137, 138), :mod:`aenum` (173),
112+
#: :mod:`typing_extensions` (191, 245), :mod:`contextlib` (196), :mod:`decimal`
113+
#: (197), :mod:`enum` (222).
111114
#:
112115
#: Four of those never actually surface, and *why* is the point. Three --
113116
#: :mod:`collections.abc`, :mod:`contextlib` and :mod:`pathlib` -- are imported at
@@ -118,9 +121,12 @@
118121
#: why the four are on the list despite costing a :data:`sys.modules` lookup each
119122
#: and nothing else. Measured: with only the five that do surface warmed and
120123
#: :mod:`pathlib` forced cold, the window leaks ``['pathlib', 'pathlib._os']``;
121-
#: with the full list it is empty even with five of the nine forced cold.
124+
#: with the full list, then nine names, it is empty even with five of them forced
125+
#: cold. :mod:`urllib.parse`, added since for issue #1693, is warm before this
126+
#: module runs on 3.8 to 3.10, where :mod:`pathlib` imports it, and cold on 3.14
127+
#: (both under ``python -S``).
122128
WARM_BEFORE_FAKING = ('aenum', 'collections.abc', 'contextlib', 'decimal', 'enum',
123-
'pathlib', 'threading', 'typing', 'typing_extensions')
129+
'pathlib', 'threading', 'typing', 'typing_extensions', 'urllib.parse')
124130

125131
#: Prefix of the names the loaders themselves write, which are excluded from the
126132
#: "nothing was imported under the fake" check. :func:`tests._support.load_module`
@@ -141,6 +147,31 @@
141147
#: assertion is aimed there.
142148
OWN_MODULE_PREFIX = 'pcapkit'
143149

150+
#: ``(value, encoding, errors, outcome)`` for ``compat.unquote``, each as Python
151+
#: 3.9's :func:`urllib.parse.unquote` has it: the text returned, or the exception
152+
#: type and message raised. ``None`` keywords leave the defaults in place. Before
153+
#: 3.9 every :obj:`bytes` row raised ``TypeError: Expected str, got bytes`` (#1693).
154+
UNQUOTED = (
155+
(b'', 'utf-8', 'strict', ''),
156+
(b'a%2fb%2F', 'utf-8', 'strict', 'a/b/'),
157+
(b'a+b%20c', 'utf-8', 'strict', 'a+b c'),
158+
(b'%zz%', 'utf-8', 'strict', '%zz%'),
159+
(b'caf%E9', 'latin-1', 'strict', 'café'),
160+
(b'%FF%FEa%00', 'utf-16', 'strict', 'a'),
161+
(b'%E9', 'utf-8', 'ignore', ''),
162+
(b'%E9', None, None, '\ufffd'),
163+
(b'caf%C3%A9', None, None, 'café'),
164+
(b'%E9', 'utf-8', 'strict',
165+
(UnicodeDecodeError, "'utf-8' codec can't decode byte 0xe9 in position 0: unexpected end of data")),
166+
(b'\xff%41', 'utf-8', 'strict',
167+
(UnicodeDecodeError, "'utf-8' codec can't decode byte 0xff in position 0: invalid start byte")),
168+
('a%20b', 'utf-8', 'strict', 'a b'),
169+
('caf%E9', 'latin-1', 'strict', 'café'),
170+
('%E9', None, None, '\ufffd'),
171+
(bytearray(b'a%20b'), 'utf-8', 'strict', (TypeError, "a bytes-like object is required, not 'str'")),
172+
(memoryview(b'a%20b'), 'utf-8', 'strict', (AttributeError, "'memoryview' object has no attribute 'split'")),
173+
)
174+
144175

145176
def aenum_pyver_readings() -> 'dict[str, tuple[int, ...]]':
146177
"""``pyver`` as every imported :mod:`aenum` module currently sees it.
@@ -286,6 +317,26 @@ def test_localcontext_applies_keyword_overrides(self) -> None:
286317
self.assertEqual(decimal.getcontext().prec, 7)
287318
self.assertEqual(decimal.getcontext().prec, original_prec)
288319

320+
def assert_unquotes_as_python39(self, unquote: 'Callable[..., str]') -> None:
321+
"""``unquote`` gives each :data:`UNQUOTED` row its outcome."""
322+
for value, encoding, errors, outcome in UNQUOTED:
323+
kwargs = {} if encoding is None else {'encoding': encoding, 'errors': errors}
324+
with self.subTest(value=value, **kwargs):
325+
if isinstance(outcome, str):
326+
self.assertEqual(unquote(value, **kwargs), outcome)
327+
else:
328+
with self.assertRaises(outcome[0]) as raised:
329+
unquote(value, **kwargs)
330+
self.assertEqual(str(raised.exception), outcome[1])
331+
332+
def test_unquote_decodes_bytes_as_python39_does(self) -> None:
333+
"""From 3.9 the name is :func:`urllib.parse.unquote` itself (#1693)."""
334+
if sys.version_info >= (3, 9):
335+
self.assertIs(self.compat.unquote, urllib.parse.unquote)
336+
else:
337+
self.assertIsNot(self.compat.unquote, urllib.parse.unquote)
338+
self.assert_unquotes_as_python39(self.compat.unquote)
339+
289340
def test_show_flag_values_returns_individual_bits(self) -> None:
290341
class DemoFlag(enum.IntFlag):
291342
READ = 1
@@ -409,6 +460,19 @@ class SlotDemo:
409460
self.assertEqual(ctx.prec, 9)
410461
self.assertEqual(decimal.getcontext().prec, original_prec)
411462

463+
# The table again with the bytes rows kept from an unquote that rejects
464+
# them, as every interpreter's did before 3.9 (#1693).
465+
self.assertIsNot(compat.unquote, urllib.parse.unquote)
466+
self.assert_unquotes_as_python39(compat.unquote)
467+
468+
def unquote_before_3_9(string: 'str', *args: 'str') -> 'str':
469+
if isinstance(string, bytes):
470+
raise TypeError('Expected str, got bytes')
471+
return urllib.parse.unquote(string, *args)
472+
473+
with mock.patch.object(compat, '_unquote', unquote_before_3_9):
474+
self.assert_unquotes_as_python39(compat.unquote)
475+
412476
class OldFlag(enum.IntFlag):
413477
READ = 1
414478
EXEC = 4

0 commit comments

Comments
 (0)