1
0
bthlabs-jsonrpc/packages/bthlabs-jsonrpc-core/tests/codecs/test_JSONCodec.py

122 lines
2.8 KiB
Python
Raw Normal View History

2024-01-15 20:20:10 +00:00
# -*- coding: utf-8 -*-
# type: ignore
from __future__ import annotations
import json
from unittest import mock
from bthlabs_jsonrpc_core import codecs
def test_decode():
# Given
json_codec = codecs.JSONCodec()
# When
result = json_codec.decode('{"spam": true, "eggs": false}')
# Then
expected_result = {
'spam': True,
'eggs': False,
}
assert result == expected_result
@mock.patch.object(codecs.json, 'loads')
def test_decode_decoder_kwargs(mock_json_loads: mock.Mock):
# Given
mock_json_loads.return_value = 'spam'
json_codec = codecs.JSONCodec()
payload = '{"spam": true, "eggs": false}'
fake_json_decoder = mock.Mock(spec=json.JSONDecoder)
fake_object_hook = mock.Mock()
fake_parse_float = mock.Mock()
fake_parse_int = mock.Mock()
fake_parse_constant = mock.Mock()
fake_object_pairs_hook = mock.Mock()
# When
_ = json_codec.decode(
payload,
cls=fake_json_decoder,
object_hook=fake_object_hook,
parse_float=fake_parse_float,
parse_int=fake_parse_int,
parse_constant=fake_parse_constant,
object_pairs_hook=fake_object_pairs_hook,
)
# Then
mock_json_loads.assert_called_once_with(
payload,
cls=fake_json_decoder,
object_hook=fake_object_hook,
parse_float=fake_parse_float,
parse_int=fake_parse_int,
parse_constant=fake_parse_constant,
object_pairs_hook=fake_object_pairs_hook,
)
def test_encode():
# Given
json_codec = codecs.JSONCodec()
# When
result = json_codec.encode({'spam': True, 'eggs': False})
# Then
expected_result = '{"spam": true, "eggs": false}'
assert result == expected_result
@mock.patch.object(codecs.json, 'dumps')
def test_encode_encoder_kwargs(mock_json_dumps: mock.Mock):
# Given
mock_json_dumps.return_value = 'spam'
json_codec = codecs.JSONCodec()
payload = {"spam": True, "eggs": False}
fake_json_encoder = mock.Mock(spec=json.JSONEncoder)
# When
_ = json_codec.encode(
payload,
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
cls=fake_json_encoder,
indent=2, separators=(':', ','),
default='DEFAULT',
sort_keys=False,
)
# Then
mock_json_dumps.assert_called_once_with(
payload,
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
cls=fake_json_encoder,
indent=2, separators=(':', ','),
default='DEFAULT',
sort_keys=False,
)
def test_get_content_type():
# Given
json_codec = codecs.JSONCodec()
# When
result = json_codec.get_content_type()
# Then
assert result == 'application/json'