62 lines
2.5 KiB
Python
62 lines
2.5 KiB
Python
|
|
import unittest
|
|
|
|
from spaceapi_server.template import _env_init, render, render_traverse
|
|
from spaceapi_server.plugins import template_function, template_filter, template_test
|
|
|
|
|
|
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_test
|
|
def template_test_test(value):
|
|
return value == 'baz'
|
|
|
|
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") }}',
|
|
'test_test_true': '{{ "baz" is template_test_test }}',
|
|
'test_test_false': '{{ "foo" is template_test_test }}'
|
|
}
|
|
}
|
|
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'])
|
|
self.assertTrue(rendered['test_functions']['test_test_true'])
|
|
self.assertFalse(rendered['test_functions']['test_test_false'])
|