diff --git a/test/test_utils.py b/test/test_utils.py index 9a7b939b8e..2a18d3df62 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -31,6 +31,7 @@ from yt_dlp.utils import ( ExtractorError, InAdvancePagedList, LazyList, + LenientJSONDecoder, NO_DEFAULT, OnDemandPagedList, Popen, @@ -887,6 +888,25 @@ class TestUtil(unittest.TestCase): self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251) self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None) + def test_LenientJSONDecoder(self): + self.assertEqual(LenientJSONDecoder().decode('{"a": 1}'), {'a': 1}) + self.assertEqual(LenientJSONDecoder(close_objects=1).decode('{"a": 1'), {'a': 1}) + self.assertEqual(LenientJSONDecoder(close_objects=2).decode('[{"a": 1'), [{'a': 1}]) + self.assertEqual(LenientJSONDecoder(ignore_extra=True).decode(' {} trailing'), {}) + + for source, kwargs, doc, pos, context in ( + ('{bad', {'close_objects': 1}, '{bad', 1, '{bad'), + ('{bad: "a long value"}', {}, '{bad: "a long value"}', 1, '{bad: "a lo'), + (' \n{bad', {'ignore_extra': True}, '{bad', 1, '{bad'), + ('[{"a": 1', {'close_objects': 1}, '[{"a": 1}', 9, '[{"a": 1}'), + ): + with self.subTest(source=source, kwargs=kwargs): + with self.assertRaises(json.JSONDecodeError) as cm: + LenientJSONDecoder(**kwargs).decode(source) + self.assertEqual(cm.exception.doc, doc) + self.assertEqual(cm.exception.pos, pos) + self.assertTrue(cm.exception.msg.endswith(f' in {context!r}')) + def test_strip_jsonp(self): stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);') d = json.loads(stripped) diff --git a/yt_dlp/utils/_utils.py b/yt_dlp/utils/_utils.py index 3e7006a8f9..6d57c3b9e3 100644 --- a/yt_dlp/utils/_utils.py +++ b/yt_dlp/utils/_utils.py @@ -546,7 +546,6 @@ def clean_html(html): class LenientJSONDecoder(json.JSONDecoder): - # TODO: Write tests def __init__(self, *args, transform_source=None, ignore_extra=False, close_objects=0, **kwargs): self.transform_source, self.ignore_extra = transform_source, ignore_extra self._close_attempts = 2 * close_objects @@ -581,7 +580,8 @@ class LenientJSONDecoder(json.JSONDecoder): s = self._close_object(e) if s is not None: continue - raise type(e)(f'{e.msg} in {s[e.pos - 10:e.pos + 10]!r}', s, e.pos) + raise type(e)( + f'{e.msg} in {e.doc[max(e.pos - 10, 0):e.pos + 10]!r}', e.doc, e.pos) assert False, 'Too many attempts to decode JSON'