Refuse to serialize None, True, False.

If someone explicitly removes the literal mappings, then refuse to
serialize None, True, and False instead of guessing.  Note that I
explicitly included True and False in the branch logic since bool is a
subclass of int but str(True) != str(int(True)) :/
This commit is contained in:
Dave Shawley 2021-10-08 07:03:14 -04:00
parent 3aa08b7435
commit e99d41a8b4
No known key found for this signature in database
GPG key ID: F41A8A99298F8EED
2 changed files with 11 additions and 0 deletions

View file

@ -398,6 +398,10 @@ class FormUrlEncodedTranscoder:
try:
datum = self.options.literal_mapping[datum] # type: ignore
except (KeyError, TypeError):
if datum in {None, True, False}:
raise TypeError(
f'{datum.__class__.__name__} is not serializable'
) from None
if isinstance(datum, (float, int, str)):
datum = str(datum)
elif hasattr(datum, 'isoformat'):

View file

@ -636,3 +636,10 @@ class FormUrlEncodingTranscoderTests(unittest.TestCase):
for value, expected in expectations.items():
_, result = self.transcoder.to_bytes(value)
self.assertEqual(expected, result)
def test_serialization_with_empty_literal_map(self):
self.transcoder: transcoders.FormUrlEncodedTranscoder
self.transcoder.options.literal_mapping.clear()
for value in {None, True, False}:
with self.assertRaises(TypeError):
self.transcoder.to_bytes(value)