def test_prepare_value(self): field = JSONField() self.assertEqual(field.prepare_value({"a": "b"}), '{"a": "b"}') self.assertEqual(field.prepare_value(None), "null") self.assertEqual(field.prepare_value("foo"), '"foo"') self.assertEqual(field.prepare_value("你好,世界"), '"你好,世界"') self.assertEqual(field.prepare_value({"a": "😀🐱"}), '{"a": "😀🐱"}') self.assertEqual(field.prepare_value(["你好,世界", "jaźń"]), '["你好,世界", "jaźń"]')
def test_custom_encoder_decoder(self): class CustomDecoder(json.JSONDecoder): def __init__(self, object_hook=None, *args, **kwargs): return super().__init__(object_hook=self.as_uuid, *args, **kwargs) def as_uuid(self, dct): if "uuid" in dct: dct["uuid"] = uuid.UUID(dct["uuid"]) return dct value = {"uuid": uuid.UUID("{c141e152-6550-4172-a784-05448d98204b}")} encoded_value = '{"uuid": "c141e152-6550-4172-a784-05448d98204b"}' field = JSONField(encoder=DjangoJSONEncoder, decoder=CustomDecoder) self.assertEqual(field.prepare_value(value), encoded_value) self.assertEqual(field.clean(encoded_value), value)
def test_prepare_value(self): field = JSONField() self.assertEqual(field.prepare_value({"a": "b"}), '{"a": "b"}') self.assertEqual(field.prepare_value(None), "null") self.assertEqual(field.prepare_value("foo"), '"foo"')