python - django 中模板的自定义加载器的单元测试用例存在问题

标签 python django unit-testing

我在 django 中编写了一个自定义加载程序,它正在模板中执行一些“正则表达式”更改,并且在加载程序的单元测试用例中我想检查模板中的更改。但 django 加载器没有返回任何带有模板对象的 template_string 属性。

例如

我将在自定义加载程序的帮助下通过对其执行重新操作来删除模板中每个“%}”之后的新行,即“\n”。

现在我需要在加载程序对测试用例中的模板执行重新操作后检查这一点。

模板:

{% for i in list %}\n
{{ i }}
{% endfor %}\n

在单元测试用例中:

template = loader.get_template("path/to/template")

#How I can retrieve template_string from template object? 
#to put in place of 'output'

self.assertEqual(output ,"{% for i in list%}{{ i }}{% endfor %}")

我需要匹配的预期输出是{% for i in list%}{{ i }}{% endfor %}。如何从模板对象中获取 template_string?

最佳答案

您可以在tests.py模块中创建一个测试自定义加载器,如下例所示。测试自定义加载器将扩展您的自定义模板加载器以添加模板的更新源。

如果 core 是您创建的应用程序。

core/
   __init__.py
   models.py
   tests.py
   views.py
   loader.py # where your custom template loader can be located.
   templates

测试.py

import io

from django.test import TestCase
from django.template.engine import Engine

from core.loader import CustomLoader as BaseLoader  # this is your custom template loader you want to test 

class HelperLoader(BaseLoader):
    is_usable = True

    def load_template_source(self, template_name, template_dirs=None):
        out_source, path = super(HelperLoader, self).load_template_source(template_name, template_dirs=None)
        self.out_source = out_source
        return out_source, path


    class CustomLoaderTest(TestCase):    
        def test_custom_loader(self):
            template_path = 'index.html'
            engine = Engine()
            engine.dirs = ['core/templates',]  # `core/templates` is where your test template_path is located.
            out = HelperLoader(engine)
            template = out.load_template(template_path )
            self.assertEqual('template source with updated content.', out.out_source)

关于python - django 中模板的自定义加载器的单元测试用例存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33935815/

相关文章:

python - Bokeh 条图 |

django - View 集的自定义权限

Django-Admin:集成自定义表单

java - 比较器排序不正确

unit-testing - 在 grails + acegi 中测试 securityConfig 映射

python - 在单元格中的第一个字母之后拆分 Pandas 数据框列(一分为二)

python - 自动启动时 Tkinter GUI 无法正常运行

python - 评估 Pandas DataFrame 中 if-then-else block 中的多个条件

python - Django REST 框架 : AttributeError: object has no attribute 'serializer'

unit-testing - 使用 Moq 返回模拟列表的模拟对象