Esempio n. 1
0
 def test_converted_value(self):
     field = JSONField(required=False)
     tests = [
         '["a", "b", "c"]',
         '{"a": 1, "b": 2}',
         "1",
         "1.5",
         '"foo"',
         "true",
         "false",
         "null",
     ]
     for json_string in tests:
         with self.subTest(json_string=json_string):
             val = field.clean(json_string)
             self.assertEqual(field.clean(val), val)
Esempio n. 2
0
    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)
Esempio n. 3
0
 def test_valid_empty(self):
     field = JSONField(required=False)
     value = field.clean("")
     self.assertIsNone(value)
Esempio n. 4
0
 def test_invalid(self):
     field = JSONField()
     with self.assertRaisesMessage(ValidationError, "Enter a valid JSON."):
         field.clean("{some badly formed: json}")
Esempio n. 5
0
 def test_valid(self):
     field = JSONField()
     value = field.clean('{"a": "b"}')
     self.assertEqual(value, {"a": "b"})