def test_invalid(self): field = forms.JSONField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean('{some badly formed: json}') self.assertEqual( cm.exception.messages[0], "'{some badly formed: json}' value must be valid JSON.")
def test_has_changed(self): field = forms.JSONField() self.assertIs(field.has_changed({'a': True}, '{"a": 1}'), True) self.assertIs(field.has_changed({ 'a': 1, 'b': 2 }, '{"b": 2, "a": 1}'), False)
def test_already_converted_value(self): field = forms.JSONField(required=False) tests = [ '["a", "b", "c"]', '{"a": 1, "b": 2}', '1', '1.5', '"foo"', 'true', 'false', 'null', ] for json_string in tests: val = field.clean(json_string) self.assertEqual(field.clean(val), val)
def test_custom_widget_kwarg(self): """The widget can be overridden with a kwarg.""" field = forms.JSONField(widget=widgets.Input) self.assertIsInstance(field.widget, widgets.Input)
def test_widget(self): """The default widget of a JSONField is a Textarea.""" field = forms.JSONField() self.assertIsInstance(field.widget, widgets.Textarea)
class JsonForm(Form): name = CharField(max_length=2) jfield = forms.JSONField()
def test_prepare_value(self): field = forms.JSONField() self.assertEqual(field.prepare_value({'a': 'b'}), '{"a": "b"}') self.assertEqual(field.prepare_value(None), 'null') self.assertEqual(field.prepare_value('foo'), '"foo"')
class JsonForm(Form): name = CharField() jfield = forms.JSONField(disabled=True)
def test_valid_empty(self): field = forms.JSONField(required=False) value = field.clean('') self.assertIsNone(value)
def test_valid(self): field = forms.JSONField() value = field.clean('{"a": "b"}') self.assertEqual(value, {'a': 'b'})
def test_form_field_deprecation_message(self): msg = ( 'django.contrib.postgres.forms.JSONField is deprecated in favor ' 'of django.forms.JSONField.') with self.assertWarnsMessage(RemovedInDjango40Warning, msg): forms.JSONField()