首页 > 解决方案 > 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

如您所见,我想设置ritDPS_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其用作标签中的ritkwarg var

是我通过使用settingsfixture of改变相关设置来测试此行为的地方pytest-django但它失败了

正如故障排除部分所述,我还尝试了其他可能是官方的方法来做到这一点,它们会产生相同的行为。至于为什么会这样,我不知道。

故障排除

使用标准解决方案

奇怪的是我也尝试过 good-old django.test.utils.override_settingsand 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 该行中删除默认值来证明。


环境

标签: pythondjangopytestpytest-django

解决方案


推荐阅读