1. import math
    
  2. from decimal import Decimal
    
  3. 
    
  4. from django.db.models import DecimalField
    
  5. from django.db.models.functions import Ln
    
  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 LnTests(TestCase):
    
  13.     def test_null(self):
    
  14.         IntegerModel.objects.create()
    
  15.         obj = IntegerModel.objects.annotate(null_ln=Ln("normal")).first()
    
  16.         self.assertIsNone(obj.null_ln)
    
  17. 
    
  18.     def test_decimal(self):
    
  19.         DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("0.6"))
    
  20.         obj = DecimalModel.objects.annotate(n1_ln=Ln("n1"), n2_ln=Ln("n2")).first()
    
  21.         self.assertIsInstance(obj.n1_ln, Decimal)
    
  22.         self.assertIsInstance(obj.n2_ln, Decimal)
    
  23.         self.assertAlmostEqual(obj.n1_ln, Decimal(math.log(obj.n1)))
    
  24.         self.assertAlmostEqual(obj.n2_ln, Decimal(math.log(obj.n2)))
    
  25. 
    
  26.     def test_float(self):
    
  27.         FloatModel.objects.create(f1=27.5, f2=0.33)
    
  28.         obj = FloatModel.objects.annotate(f1_ln=Ln("f1"), f2_ln=Ln("f2")).first()
    
  29.         self.assertIsInstance(obj.f1_ln, float)
    
  30.         self.assertIsInstance(obj.f2_ln, float)
    
  31.         self.assertAlmostEqual(obj.f1_ln, math.log(obj.f1))
    
  32.         self.assertAlmostEqual(obj.f2_ln, math.log(obj.f2))
    
  33. 
    
  34.     def test_integer(self):
    
  35.         IntegerModel.objects.create(small=20, normal=15, big=1)
    
  36.         obj = IntegerModel.objects.annotate(
    
  37.             small_ln=Ln("small"),
    
  38.             normal_ln=Ln("normal"),
    
  39.             big_ln=Ln("big"),
    
  40.         ).first()
    
  41.         self.assertIsInstance(obj.small_ln, float)
    
  42.         self.assertIsInstance(obj.normal_ln, float)
    
  43.         self.assertIsInstance(obj.big_ln, float)
    
  44.         self.assertAlmostEqual(obj.small_ln, math.log(obj.small))
    
  45.         self.assertAlmostEqual(obj.normal_ln, math.log(obj.normal))
    
  46.         self.assertAlmostEqual(obj.big_ln, math.log(obj.big))
    
  47. 
    
  48.     def test_transform(self):
    
  49.         with register_lookup(DecimalField, Ln):
    
  50.             DecimalModel.objects.create(n1=Decimal("12.0"), n2=Decimal("0"))
    
  51.             DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("0"))
    
  52.             obj = DecimalModel.objects.filter(n1__ln__gt=0).get()
    
  53.             self.assertEqual(obj.n1, Decimal("12.0"))