| 1 |
from decimal import Decimal |
| 2 |
|
| 3 |
from django.db.models import DecimalField |
| 4 |
from django.db.models.functions import Abs |
| 5 |
from django.test import TestCase |
| 6 |
from django.test.utils import register_lookup |
| 7 |
|
| 8 |
from ..models import DecimalModel, FloatModel, IntegerModel |
| 9 |
|
| 10 |
|
| 11 |
class AbsTests(TestCase): |
| 12 |
def test_null(self): |
| 13 |
IntegerModel.objects.create() |
| 14 |
obj = IntegerModel.objects.annotate(null_abs=Abs("normal")).first() |
| 15 |
self.assertIsNone(obj.null_abs) |
| 16 |
|
| 17 |
def test_decimal(self): |
| 18 |
DecimalModel.objects.create(n1=Decimal("-0.8"), n2=Decimal("1.2")) |
| 19 |
obj = DecimalModel.objects.annotate(n1_abs=Abs("n1"), n2_abs=Abs("n2")).first() |
| 20 |
self.assertIsInstance(obj.n1_abs, Decimal) |
| 21 |
self.assertIsInstance(obj.n2_abs, Decimal) |
| 22 |
self.assertEqual(obj.n1, -obj.n1_abs) |
| 23 |
self.assertEqual(obj.n2, obj.n2_abs) |
| 24 |
|
| 25 |
def test_float(self): |
| 26 |
obj = FloatModel.objects.create(f1=-0.5, f2=12) |
| 27 |
obj = FloatModel.objects.annotate(f1_abs=Abs("f1"), f2_abs=Abs("f2")).first() |
| 28 |
self.assertIsInstance(obj.f1_abs, float) |
| 29 |
self.assertIsInstance(obj.f2_abs, float) |
| 30 |
self.assertEqual(obj.f1, -obj.f1_abs) |
| 31 |
self.assertEqual(obj.f2, obj.f2_abs) |
| 32 |
|
| 33 |
def test_integer(self): |
| 34 |
IntegerModel.objects.create(small=12, normal=0, big=-45) |
| 35 |
obj = IntegerModel.objects.annotate( |
| 36 |
small_abs=Abs("small"), |
| 37 |
normal_abs=Abs("normal"), |
| 38 |
big_abs=Abs("big"), |
| 39 |
).first() |
| 40 |
self.assertIsInstance(obj.small_abs, int) |
| 41 |
self.assertIsInstance(obj.normal_abs, int) |
| 42 |
self.assertIsInstance(obj.big_abs, int) |
| 43 |
self.assertEqual(obj.small, obj.small_abs) |
| 44 |
self.assertEqual(obj.normal, obj.normal_abs) |
| 45 |
self.assertEqual(obj.big, -obj.big_abs) |
| 46 |
|
| 47 |
def test_transform(self): |
| 48 |
with register_lookup(DecimalField, Abs): |
| 49 |
DecimalModel.objects.create(n1=Decimal("-1.5"), n2=Decimal("0")) |
| 50 |
DecimalModel.objects.create(n1=Decimal("-0.5"), n2=Decimal("0")) |
| 51 |
obj = DecimalModel.objects.filter(n1__abs__gt=1).get() |
| 52 |
self.assertEqual(obj.n1, Decimal("-1.5")) |