69 lines
2.6 KiB
Python
69 lines
2.6 KiB
Python
|
|
import unittest
|
|
|
|
from spaceapi_server.template import _env_init, render, render_traverse
|
|
from spaceapi_server.plugins import template_function, template_filter
|
|
|
|
|
|
class TemplateTest(unittest.TestCase):
|
|
|
|
@staticmethod
|
|
@template_function
|
|
def template_test_function(value):
|
|
return f'test_{value}'
|
|
|
|
@staticmethod
|
|
@template_filter
|
|
def template_test_filter(value, other):
|
|
return f'test_{other}_{value}'
|
|
|
|
@staticmethod
|
|
@template_function
|
|
def template_test_function_nocache():
|
|
TemplateTest.counter1 += 1
|
|
return TemplateTest.counter1
|
|
|
|
def setUp(self) -> None:
|
|
TemplateTest.counter1 = 0
|
|
|
|
def test_template(self):
|
|
env = _env_init()
|
|
self.assertEqual('"not a template"', env.from_string('not a template').render())
|
|
self.assertEqual('"a template"', env.from_string('{{ "a template" }}').render())
|
|
self.assertEqual('42', env.from_string('{{ 42 }}').render())
|
|
self.assertEqual('["foo"]', env.from_string('{{ [ "foo" ] }}').render())
|
|
self.assertEqual('{"foo": ["bar"]}', env.from_string('{{ { "foo": [ "bar" ] } }}').render())
|
|
|
|
def test_render(self):
|
|
self.assertEqual('not a template', render('not a template'))
|
|
self.assertEqual('a template', render('{{ "a template" }}'))
|
|
self.assertEqual(42, render('{{ 42 }}'))
|
|
self.assertEqual(['foo'], render('{{ [ "foo" ] }}'))
|
|
self.assertEqual({'foo': ['bar']}, render('{{ { "foo": [ "bar" ] } }}'))
|
|
self.assertEqual('foo', render('foo{{ "bar" }}'))
|
|
|
|
def test_render_traverse(self):
|
|
template = {
|
|
'foo': 42,
|
|
'bar': [1, 2, 3],
|
|
'notemplate': 'foo',
|
|
'builtin': '{{ [ 1337, 42 ] | first }}',
|
|
'test_functions': {
|
|
'test_function': '{{ template_test_function("foo") }}',
|
|
'test_filter': '{{ "bar" | template_test_filter("other") }}'
|
|
}
|
|
}
|
|
rendered = render_traverse(template)
|
|
self.assertEqual(42, rendered['foo'])
|
|
self.assertEqual([1, 2, 3], rendered['bar'])
|
|
self.assertEqual('foo', rendered['notemplate'])
|
|
self.assertEqual(1337, rendered['builtin'])
|
|
self.assertEqual('test_foo', rendered['test_functions']['test_function'])
|
|
self.assertEqual('test_other_bar', rendered['test_functions']['test_filter'])
|
|
|
|
def test_no_cache(self):
|
|
template = ['{{ template_test_function_nocache() }}']
|
|
r1 = render_traverse(template)
|
|
r2 = render_traverse(template)
|
|
self.assertEqual(1, r1[0])
|
|
self.assertEqual(2, r2[0])
|