xref: /aosp_15_r20/external/tink/python/tink/jwt/_json_util_test.py (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1# Copyright 2021 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Tests for tink.python.tink.jwt._json_util."""
15
16from absl.testing import absltest
17from tink.jwt import _json_util
18from tink.jwt import _jwt_error
19
20
21class JwtFormatTest(absltest.TestCase):
22
23  def test_json_dumps(self):
24    self.assertEqual(
25        _json_util.json_dumps({'a': ['b', 1, True, None]}),
26        '{"a":["b",1,true,null]}')
27
28  def test_json_loads(self):
29    self.assertEqual(
30        _json_util.json_loads('{"a":["b",1,true,null]}'),
31        {'a': ['b', 1, True, None]})
32    with self.assertRaises(_jwt_error.JwtInvalidError):
33      _json_util.json_loads('{invalid')
34
35  def test_json_loads_duplidate_entries_fails(self):
36    with self.assertRaises(_jwt_error.JwtInvalidError):
37      _json_util.json_loads('{"a":"a1", "a":"a2"}')
38
39  def test_json_loads_recursion(self):
40    num_recursions = 1000
41    recursive_json = ('{"a":' * num_recursions) + '""' + ('}' * num_recursions)
42    with self.assertRaises(_jwt_error.JwtInvalidError):
43      _json_util.json_loads(recursive_json)
44
45  def test_json_loads_with_invalid_utf16(self):
46    with self.assertRaises(_jwt_error.JwtInvalidError):
47      _json_util.json_loads(u'{"a":{"b":{"c":"\\uD834"}}}')
48    with self.assertRaises(_jwt_error.JwtInvalidError):
49      _json_util.json_loads(u'{"\\uD834":"b"}')
50    with self.assertRaises(_jwt_error.JwtInvalidError):
51      _json_util.json_loads(u'{"a":["a",{"b":["c","\\uD834"]}]}')
52
53
54if __name__ == '__main__':
55  absltest.main()
56