Skip to main content
 首页 » 编程设计

python之在 Django 模板的自定义加载器的单元测试用例中出现问题

2024年10月24日36三少

我在 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)