嗯,我之所以没有得到任何答案或评论,部分原因是下面原始内容中的代码仅限于它们自己的小上下文,因此,我想与您共享整个代码库(不要不用担心,我会永久链接选中的行),因为无论如何我都打算打开源代码,以便您可以随意查看任何内容。
整个代码库为here。这是存储库的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
,作为the docs put,我可以 kinda 模拟设置。但是,当我运行测试时,它没有看到DPS_TEMPLATE_TRUE_DEFAULT
并使用"True"
。我通过删除"True"
上的getattr
来调试此行为。
即使我在测试中进行了设置,为什么仍看不到DPS_TEMPLATE_TRUE_DEFAULT
?
In the custom template tag,您会看到我想从DPS_TEMPLATE_TRUE_DEFAULT
抓取django.conf.settings
并将其用作rit
标签中的var
kwarg。 / p>
This是我通过用settings
和it fails的pytest-django
固定来改变相关设置来测试此行为的地方。
正如故障排除部分所述,我也尝试了其他可能的官方方法来执行此操作,它们产生相同的行为。至于为什么这样做,我一无所知。
奇怪的是,我还尝试了老旧的django.test.utils.override_settings
和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"
in this line中删除默认值getattr
来证明。