Add support for logarithm in templates (#10824)

* Add support for logarithm in templates

This adds a 'log' filter that takes the logarithm of the given value,
with an optional base number. The base defaults to 'e' - the natural
logarithm

* Remove usage of log10 in template filter 'log'

* Add logarithm as a global

This makes it possible to write:
'{{ log(4, 2) }}'
This commit is contained in:
Odin Ugedal authored and Paulus Schoutsen committed 2017-11-27 21:29:01 -08:00
1 parent 27270b49b4
commit 0668fba7bd
2 files changed
+35

No files matched your search

+24
View File
@@ -3,6 +3,7 @@ import asyncio
from datetime import datetime
import unittest
import random
import math
from unittest.mock import patch
from homeassistant.components import group
@@ -125,6 +126,29 @@ class TestHelpersTemplate(unittest.TestCase):
template.Template('{{ %s | multiply(10) | round }}' % inp,
self.hass).render())
def test_logarithm(self):
"""Test logarithm."""
tests = [
(4, 2, '2.0'),
(1000, 10, '3.0'),
(math.e, '', '1.0'),
('"invalid"', '_', 'invalid'),
(10, '"invalid"', '10.0'),
]
for value, base, expected in tests:
self.assertEqual(
expected,
template.Template(
'{{ %s | log(%s) | round(1) }}' % (value, base),
self.hass).render())
self.assertEqual(
expected,
template.Template(
'{{ log(%s, %s) | round(1) }}' % (value, base),
self.hass).render())
def test_strptime(self):
"""Test the parse timestamp method."""
tests = [