如何在不提供模板路径的情况下测试使用get_template的函数?

时间:2010-12-15 15:58:43

标签: django unit-testing mocking

我有这个功能:

def _render(object, template, context_name=None, classes=None):
"""
Helper function that execute the form/field actual rendering.

"""
if not context_name:
    context_name = 'object'
template = get_template(template)
c = {
    context_name: object,
    'classes': classes,
}
return template.render(Context(c))

我想测试它,但我不想在我的文件系统中提供任何现有模板,只是像“虚拟”那样。 input_chunk

class RenderCustomChunk(TestCase):
"""
The ``_render()`` class should return a fully rendered html code
based on the given template chunk and parameters passed
with the rendering function ie. classes.

"""
def setUp(self):
    self.test_object = 'Test Object'
    self.test_template_name = 'TestTemplate.html'

    self.input_chunk = u'<p>{{ object }}</p>'
    self.render_output = u'<p>%s</p>' % self.test_object

def test_should_render_custom_object(self):
    self.assertEqual(forms._render(self.test_object, self.test_template_name),
                     self.render_output)

有没有优雅的方法呢?

1 个答案:

答案 0 :(得分:1)

因为我认为你没有尝试测试get_template函数(毕竟你使用的是“虚拟”文件,这不是get_template的用途),另一种解决方案就是模拟get_template。

# tests.py
from foo import forms

def mock_get_template():
    return django.template.Template(u'<p>{{ object }}</p>')

forms.get_template = mock_get_template

或内联,如果它在setUp()

中看起来更干净
class RenderCustomChunk(TestCase):
    def setUp(self):
        self.test_object = 'Test Object'
        self.test_template_name = 'TestTemplate.html'

        self.render_output = u'<p>%s</p>' % self.test_object

        # this is a unit test for _render, not get_template.
        forms.get_template = lambda x: Template(u'<p>{{ object }}</p>')

    def test_should_render_custom_object(self):
        self.assertEqual(forms._render(self.test_object, self.test_template_name),
                         self.render_output)
相关问题