Debian Codegraph @

tests/db_functions/math/test_log.py

raw
1 import math
2 from decimal import Decimal
3
4 from django.db.models.functions import Log
5 from django.test import TestCase
6
7 from ..models import DecimalModel, FloatModel, IntegerModel
8
9
10 class LogTests(TestCase):
11 def test_null(self):
12 IntegerModel.objects.create(big=100)
13 obj = IntegerModel.objects.annotate(
14 null_log_small=Log("small", "normal"),
15 null_log_normal=Log("normal", "big"),
16 null_log_big=Log("big", "normal"),
17 ).first()
18 self.assertIsNone(obj.null_log_small)
19 self.assertIsNone(obj.null_log_normal)
20 self.assertIsNone(obj.null_log_big)
21
22 def test_decimal(self):
23 DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("3.6"))
24 obj = DecimalModel.objects.annotate(n_log=Log("n1", "n2")).first()
25 self.assertIsInstance(obj.n_log, Decimal)
26 self.assertAlmostEqual(obj.n_log, Decimal(math.log(obj.n2, obj.n1)))
27
28 def test_float(self):
29 FloatModel.objects.create(f1=2.0, f2=4.0)
30 obj = FloatModel.objects.annotate(f_log=Log("f1", "f2")).first()
31 self.assertIsInstance(obj.f_log, float)
32 self.assertAlmostEqual(obj.f_log, math.log(obj.f2, obj.f1))
33
34 def test_integer(self):
35 IntegerModel.objects.create(small=4, normal=8, big=2)
36 obj = IntegerModel.objects.annotate(
37 small_log=Log("small", "big"),
38 normal_log=Log("normal", "big"),
39 big_log=Log("big", "big"),
40 ).first()
41 self.assertIsInstance(obj.small_log, float)
42 self.assertIsInstance(obj.normal_log, float)
43 self.assertIsInstance(obj.big_log, float)
44 self.assertAlmostEqual(obj.small_log, math.log(obj.big, obj.small))
45 self.assertAlmostEqual(obj.normal_log, math.log(obj.big, obj.normal))
46 self.assertAlmostEqual(obj.big_log, math.log(obj.big, obj.big))