| 1 |
import math |
| 2 |
from decimal import Decimal |
| 3 |
|
| 4 |
from django.db.models import DecimalField |
| 5 |
from django.db.models.functions import Floor |
| 6 |
from django.test import TestCase |
| 7 |
from django.test.utils import register_lookup |
| 8 |
|
| 9 |
from ..models import DecimalModel, FloatModel, IntegerModel |
| 10 |
|
| 11 |
|
| 12 |
class FloorTests(TestCase): |
| 13 |
def test_null(self): |
| 14 |
IntegerModel.objects.create() |
| 15 |
obj = IntegerModel.objects.annotate(null_floor=Floor("normal")).first() |
| 16 |
self.assertIsNone(obj.null_floor) |
| 17 |
|
| 18 |
def test_decimal(self): |
| 19 |
DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) |
| 20 |
obj = DecimalModel.objects.annotate( |
| 21 |
n1_floor=Floor("n1"), n2_floor=Floor("n2") |
| 22 |
).first() |
| 23 |
self.assertIsInstance(obj.n1_floor, Decimal) |
| 24 |
self.assertIsInstance(obj.n2_floor, Decimal) |
| 25 |
self.assertEqual(obj.n1_floor, Decimal(math.floor(obj.n1))) |
| 26 |
self.assertEqual(obj.n2_floor, Decimal(math.floor(obj.n2))) |
| 27 |
|
| 28 |
def test_float(self): |
| 29 |
FloatModel.objects.create(f1=-27.5, f2=0.33) |
| 30 |
obj = FloatModel.objects.annotate( |
| 31 |
f1_floor=Floor("f1"), f2_floor=Floor("f2") |
| 32 |
).first() |
| 33 |
self.assertIsInstance(obj.f1_floor, float) |
| 34 |
self.assertIsInstance(obj.f2_floor, float) |
| 35 |
self.assertEqual(obj.f1_floor, math.floor(obj.f1)) |
| 36 |
self.assertEqual(obj.f2_floor, math.floor(obj.f2)) |
| 37 |
|
| 38 |
def test_integer(self): |
| 39 |
IntegerModel.objects.create(small=-20, normal=15, big=-1) |
| 40 |
obj = IntegerModel.objects.annotate( |
| 41 |
small_floor=Floor("small"), |
| 42 |
normal_floor=Floor("normal"), |
| 43 |
big_floor=Floor("big"), |
| 44 |
).first() |
| 45 |
self.assertIsInstance(obj.small_floor, int) |
| 46 |
self.assertIsInstance(obj.normal_floor, int) |
| 47 |
self.assertIsInstance(obj.big_floor, int) |
| 48 |
self.assertEqual(obj.small_floor, math.floor(obj.small)) |
| 49 |
self.assertEqual(obj.normal_floor, math.floor(obj.normal)) |
| 50 |
self.assertEqual(obj.big_floor, math.floor(obj.big)) |
| 51 |
|
| 52 |
def test_transform(self): |
| 53 |
with register_lookup(DecimalField, Floor): |
| 54 |
DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0")) |
| 55 |
DecimalModel.objects.create(n1=Decimal("3.4"), n2=Decimal("0")) |
| 56 |
obj = DecimalModel.objects.filter(n1__floor__gt=4).get() |
| 57 |
self.assertEqual(obj.n1, Decimal("5.4")) |