test_exp.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import math
  2. from decimal import Decimal
  3. from django.db.models import DecimalField
  4. from django.db.models.functions import Exp
  5. from django.test import TestCase
  6. from ..models import DecimalModel, FloatModel, IntegerModel
  7. class ExpTests(TestCase):
  8. def test_decimal(self):
  9. DecimalModel.objects.create(n1=Decimal('-12.9'), n2=Decimal('0.6'))
  10. obj = DecimalModel.objects.annotate(n1_exp=Exp('n1'), n2_exp=Exp('n2')).first()
  11. self.assertIsInstance(obj.n1_exp, Decimal)
  12. self.assertIsInstance(obj.n2_exp, Decimal)
  13. self.assertAlmostEqual(obj.n1_exp, Decimal(math.exp(obj.n1)))
  14. self.assertAlmostEqual(obj.n2_exp, Decimal(math.exp(obj.n2)))
  15. def test_float(self):
  16. FloatModel.objects.create(f1=-27.5, f2=0.33)
  17. obj = FloatModel.objects.annotate(f1_exp=Exp('f1'), f2_exp=Exp('f2')).first()
  18. self.assertIsInstance(obj.f1_exp, float)
  19. self.assertIsInstance(obj.f2_exp, float)
  20. self.assertAlmostEqual(obj.f1_exp, math.exp(obj.f1))
  21. self.assertAlmostEqual(obj.f2_exp, math.exp(obj.f2))
  22. def test_integer(self):
  23. IntegerModel.objects.create(small=-20, normal=15, big=-1)
  24. obj = IntegerModel.objects.annotate(
  25. small_exp=Exp('small'),
  26. normal_exp=Exp('normal'),
  27. big_exp=Exp('big'),
  28. ).first()
  29. self.assertIsInstance(obj.small_exp, float)
  30. self.assertIsInstance(obj.normal_exp, float)
  31. self.assertIsInstance(obj.big_exp, float)
  32. self.assertAlmostEqual(obj.small_exp, math.exp(obj.small))
  33. self.assertAlmostEqual(obj.normal_exp, math.exp(obj.normal))
  34. self.assertAlmostEqual(obj.big_exp, math.exp(obj.big))
  35. def test_transform(self):
  36. try:
  37. DecimalField.register_lookup(Exp)
  38. DecimalModel.objects.create(n1=Decimal('12.0'), n2=Decimal('0'))
  39. DecimalModel.objects.create(n1=Decimal('-1.0'), n2=Decimal('0'))
  40. objs = DecimalModel.objects.filter(n1__exp__gt=10)
  41. self.assertQuerysetEqual(objs, [Decimal('12.0')], lambda a: a.n1)
  42. finally:
  43. DecimalField._unregister_lookup(Exp)