test_round.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from decimal import Decimal
  2. from django.db.models import DecimalField
  3. from django.db.models.functions import Round
  4. from django.test import TestCase
  5. from ..models import DecimalModel, FloatModel, IntegerModel
  6. class RoundTests(TestCase):
  7. def test_decimal(self):
  8. DecimalModel.objects.create(n1=Decimal('-12.9'), n2=Decimal('0.6'))
  9. obj = DecimalModel.objects.annotate(n1_round=Round('n1'), n2_round=Round('n2')).first()
  10. self.assertIsInstance(obj.n1_round, Decimal)
  11. self.assertIsInstance(obj.n2_round, Decimal)
  12. self.assertAlmostEqual(obj.n1_round, round(obj.n1))
  13. self.assertAlmostEqual(obj.n2_round, round(obj.n2))
  14. def test_float(self):
  15. FloatModel.objects.create(f1=-27.55, f2=0.55)
  16. obj = FloatModel.objects.annotate(f1_round=Round('f1'), f2_round=Round('f2')).first()
  17. self.assertIsInstance(obj.f1_round, float)
  18. self.assertIsInstance(obj.f2_round, float)
  19. self.assertAlmostEqual(obj.f1_round, round(obj.f1))
  20. self.assertAlmostEqual(obj.f2_round, round(obj.f2))
  21. def test_integer(self):
  22. IntegerModel.objects.create(small=-20, normal=15, big=-1)
  23. obj = IntegerModel.objects.annotate(
  24. small_round=Round('small'),
  25. normal_round=Round('normal'),
  26. big_round=Round('big'),
  27. ).first()
  28. self.assertIsInstance(obj.small_round, int)
  29. self.assertIsInstance(obj.normal_round, int)
  30. self.assertIsInstance(obj.big_round, int)
  31. self.assertEqual(obj.small_round, round(obj.small))
  32. self.assertEqual(obj.normal_round, round(obj.normal))
  33. self.assertEqual(obj.big_round, round(obj.big))
  34. def test_transform(self):
  35. try:
  36. DecimalField.register_lookup(Round)
  37. DecimalModel.objects.create(n1=Decimal('2.0'), n2=Decimal('0'))
  38. DecimalModel.objects.create(n1=Decimal('-1.0'), n2=Decimal('0'))
  39. objs = DecimalModel.objects.filter(n1__round__gt=0)
  40. self.assertQuerysetEqual(objs, [Decimal('2.0')], lambda a: a.n1)
  41. finally:
  42. DecimalField._unregister_lookup(Round)