| 1 |
from django.db import transaction |
| 2 |
from django.test import TestCase |
| 3 |
|
| 4 |
from .models import FloatModel |
| 5 |
|
| 6 |
|
| 7 |
class TestFloatField(TestCase): |
| 8 |
def test_float_validates_object(self): |
| 9 |
instance = FloatModel(size=2.5) |
| 10 |
# Try setting float field to unsaved object |
| 11 |
instance.size = instance |
| 12 |
with transaction.atomic(): |
| 13 |
with self.assertRaises(TypeError): |
| 14 |
instance.save() |
| 15 |
# Set value to valid and save |
| 16 |
instance.size = 2.5 |
| 17 |
instance.save() |
| 18 |
self.assertTrue(instance.id) |
| 19 |
# Set field to object on saved instance |
| 20 |
instance.size = instance |
| 21 |
msg = ( |
| 22 |
"Tried to update field model_fields.FloatModel.size with a model " |
| 23 |
"instance, %r. Use a value compatible with FloatField." |
| 24 |
) % instance |
| 25 |
with transaction.atomic(): |
| 26 |
with self.assertRaisesMessage(TypeError, msg): |
| 27 |
instance.save() |
| 28 |
# Try setting field to object on retrieved object |
| 29 |
obj = FloatModel.objects.get(pk=instance.id) |
| 30 |
obj.size = obj |
| 31 |
with self.assertRaisesMessage(TypeError, msg): |
| 32 |
obj.save() |
| 33 |
|
| 34 |
def test_invalid_value(self): |
| 35 |
tests = [ |
| 36 |
(TypeError, ()), |
| 37 |
(TypeError, []), |
| 38 |
(TypeError, {}), |
| 39 |
(TypeError, set()), |
| 40 |
(TypeError, object()), |
| 41 |
(TypeError, complex()), |
| 42 |
(ValueError, "non-numeric string"), |
| 43 |
(ValueError, b"non-numeric byte-string"), |
| 44 |
] |
| 45 |
for exception, value in tests: |
| 46 |
with self.subTest(value): |
| 47 |
msg = "Field 'size' expected a number but got %r." % (value,) |
| 48 |
with self.assertRaisesMessage(exception, msg): |
| 49 |
FloatModel.objects.create(size=value) |