python - Django 不会覆盖模板标签测试中的设置
问题描述
好吧,我没有得到一些答案或评论,部分原因是下面原始内容中的代码仅限于它们自己的小上下文,所以我想与你分享整个代码库(别担心,我将永久链接选定的行),因为无论如何我都打算打开源代码,以便您可以查看尽可能多的内容。
整个代码库在这里。它是perma/1
存储库的分支。
原创内容
我有一个自定义模板标签,如下所示:
# other imports
from django.conf import settings
DPS_TEMPLATE_TRUE_DEFAULT = getattr(settings, "DPS_TEMPLATE_TRUE_DEFAULT", "True")
@register.simple_tag(name="var")
def get_var(name, rit=DPS_TEMPLATE_TRUE_DEFAULT, rif="False", rin=""):
"""
A template tag to render value of a variable.
"""
_LOGGER.debug("Rendering value for `%s`...", name)
variable = models.Variable.objects.get(name=name)
value = variable.value
if value is None:
return rin
if isinstance(value, bool):
if value:
return rit
else:
return rif
return variable.value
如您所见,我想设置rit
为DPS_TEMPLATE_TRUE_DEFAULT
. 我测试这种行为如下:
# `template_factory` and `context_factory` creates Template and Context instances accordingly.
# i use them in other tests. they work.
@pytest.mark.it("Render if True by settings")
def test_render_if_true_settings(
self, template_factory, context_factory, variable_factory, settings
):
settings.DPS_TEMPLATE_TRUE_DEFAULT = "this is true by settings"
variable_factory(True)
template = template_factory("FOO", tag_name=self.tag_name).render(
context_factory()
)
assert "<p>this is true by settings</p>" in template
我使用pytest-django
并且,正如文档所说,我可以模拟设置。但是,当我运行测试时,它看不到DPS_TEMPLATE_TRUE_DEFAULT
并使用"True"
. "True"
我通过删除on来调试此行为getattr
。
为什么DPS_TEMPLATE_TRUE_DEFAULT
即使我在测试中设置它也看不到?
添加/新内容
在自定义模板标签中,您可以看到我想从中获取DPS_TEMPLATE_TRUE_DEFAULT
并将django.conf.settings
其用作标签中的rit
kwarg var
。
这是我通过使用settings
fixture of改变相关设置来测试此行为的地方pytest-django
,但它失败了。
正如故障排除部分所述,我还尝试了其他可能是官方的方法来做到这一点,它们会产生相同的行为。至于为什么会这样,我不知道。
故障排除
使用标准解决方案
奇怪的是我也尝试过 good-old django.test.utils.override_settings
and modify_settings
,它们表现出相同的行为。
渴望初始化
我想,也许,问题是我在函数getattr
范围之外使用get_var
,它会在它执行之前加载它,这意味着在测试之前并且不知何故让我再次设置它。所以我搬到了函数getattr
内部get_var
,但行为是一样的。它的行为就像DPS_TEMPLATE_TRUE_DEFAULT
设置中不存在一样。
硬编码到设置文件中
所以我在文件中硬编码了“看不到”设置,settings.py
如下所示:
DPS_TEMPLATE_TRUE_DEFAULT = "this is true by settings"
它仍然表现得像DPS_TEMPLATE_TRUE_DEFAULT
不存在一样。
这也可以通过"True"
从getattr
该行中删除默认值来证明。
环境
- Django 2.2.8
- Pytest Django 3.7.0
解决方案
推荐阅读
- nginx - 在 Kubernetes 中使用单个复制时 NGINX 502 Bad Gateway
- sql-server - 在 SQL Server 数据库中移动 XML 文件后替换数据
- c# - c# 中的 SSAS 自动化 - 实用地重命名 c# 中的 AAS 属性
- c# - 使用 EF Core 调用存储过程并关闭连接
- unit-testing - 可以在没有 Mockito.verify 的情况下测试方法调用吗?
- python-3.6 - 无法在期货列表上运行 asyncio.wait(...)
- c++ - 我预测 Char 数组类型值只能转换指针类型
- stm32 - 在STM32板上运行后如何更改UART波特率?
- amazon-dynamodb - dynamodb 中的有序哈希键
- android - 如何为android数据绑定点击监听器编写progaurd规则?