test_sign.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from decimal import Decimal
  2. from django.db.models import DecimalField
  3. from django.db.models.functions import Sign
  4. from django.test import TestCase
  5. from django.test.utils import register_lookup
  6. from ..models import DecimalModel, FloatModel, IntegerModel
  7. class SignTests(TestCase):
  8. def test_null(self):
  9. IntegerModel.objects.create()
  10. obj = IntegerModel.objects.annotate(null_sign=Sign('normal')).first()
  11. self.assertIsNone(obj.null_sign)
  12. def test_decimal(self):
  13. DecimalModel.objects.create(n1=Decimal('-12.9'), n2=Decimal('0.6'))
  14. obj = DecimalModel.objects.annotate(n1_sign=Sign('n1'), n2_sign=Sign('n2')).first()
  15. self.assertIsInstance(obj.n1_sign, Decimal)
  16. self.assertIsInstance(obj.n2_sign, Decimal)
  17. self.assertEqual(obj.n1_sign, Decimal('-1'))
  18. self.assertEqual(obj.n2_sign, Decimal('1'))
  19. def test_float(self):
  20. FloatModel.objects.create(f1=-27.5, f2=0.33)
  21. obj = FloatModel.objects.annotate(f1_sign=Sign('f1'), f2_sign=Sign('f2')).first()
  22. self.assertIsInstance(obj.f1_sign, float)
  23. self.assertIsInstance(obj.f2_sign, float)
  24. self.assertEqual(obj.f1_sign, -1.0)
  25. self.assertEqual(obj.f2_sign, 1.0)
  26. def test_integer(self):
  27. IntegerModel.objects.create(small=-20, normal=0, big=20)
  28. obj = IntegerModel.objects.annotate(
  29. small_sign=Sign('small'),
  30. normal_sign=Sign('normal'),
  31. big_sign=Sign('big'),
  32. ).first()
  33. self.assertIsInstance(obj.small_sign, int)
  34. self.assertIsInstance(obj.normal_sign, int)
  35. self.assertIsInstance(obj.big_sign, int)
  36. self.assertEqual(obj.small_sign, -1)
  37. self.assertEqual(obj.normal_sign, 0)
  38. self.assertEqual(obj.big_sign, 1)
  39. def test_transform(self):
  40. with register_lookup(DecimalField, Sign):
  41. DecimalModel.objects.create(n1=Decimal('5.4'), n2=Decimal('0'))
  42. DecimalModel.objects.create(n1=Decimal('-0.1'), n2=Decimal('0'))
  43. obj = DecimalModel.objects.filter(n1__sign__lt=0, n2__sign=0).get()
  44. self.assertEqual(obj.n1, Decimal('-0.1'))