| 1 |
from decimal import Decimal |
| 2 |
|
| 3 |
from django.db.models import DecimalField |
| 4 |
from django.db.models.functions import Sign |
| 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 SignTests(TestCase): |
| 12 |
def test_null(self): |
| 13 |
IntegerModel.objects.create() |
| 14 |
obj = IntegerModel.objects.annotate(null_sign=Sign("normal")).first() |
| 15 |
self.assertIsNone(obj.null_sign) |
| 16 |
|
| 17 |
def test_decimal(self): |
| 18 |
DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) |
| 19 |
obj = DecimalModel.objects.annotate( |
| 20 |
n1_sign=Sign("n1"), n2_sign=Sign("n2") |
| 21 |
).first() |
| 22 |
self.assertIsInstance(obj.n1_sign, Decimal) |
| 23 |
self.assertIsInstance(obj.n2_sign, Decimal) |
| 24 |
self.assertEqual(obj.n1_sign, Decimal("-1")) |
| 25 |
self.assertEqual(obj.n2_sign, Decimal("1")) |
| 26 |
|
| 27 |
def test_float(self): |
| 28 |
FloatModel.objects.create(f1=-27.5, f2=0.33) |
| 29 |
obj = FloatModel.objects.annotate( |
| 30 |
f1_sign=Sign("f1"), f2_sign=Sign("f2") |
| 31 |
).first() |
| 32 |
self.assertIsInstance(obj.f1_sign, float) |
| 33 |
self.assertIsInstance(obj.f2_sign, float) |
| 34 |
self.assertEqual(obj.f1_sign, -1.0) |
| 35 |
self.assertEqual(obj.f2_sign, 1.0) |
| 36 |
|
| 37 |
def test_integer(self): |
| 38 |
IntegerModel.objects.create(small=-20, normal=0, big=20) |
| 39 |
obj = IntegerModel.objects.annotate( |
| 40 |
small_sign=Sign("small"), |
| 41 |
normal_sign=Sign("normal"), |
| 42 |
big_sign=Sign("big"), |
| 43 |
).first() |
| 44 |
self.assertIsInstance(obj.small_sign, int) |
| 45 |
self.assertIsInstance(obj.normal_sign, int) |
| 46 |
self.assertIsInstance(obj.big_sign, int) |
| 47 |
self.assertEqual(obj.small_sign, -1) |
| 48 |
self.assertEqual(obj.normal_sign, 0) |
| 49 |
self.assertEqual(obj.big_sign, 1) |
| 50 |
|
| 51 |
def test_transform(self): |
| 52 |
with register_lookup(DecimalField, Sign): |
| 53 |
DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0")) |
| 54 |
DecimalModel.objects.create(n1=Decimal("-0.1"), n2=Decimal("0")) |
| 55 |
obj = DecimalModel.objects.filter(n1__sign__lt=0, n2__sign=0).get() |
| 56 |
self.assertEqual(obj.n1, Decimal("-0.1")) |