Django不会在模板标记测试中覆盖设置

时间:2019-12-09 15:27:55

标签: python django pytest pytest-django

嗯,我之所以没有得到任何答案或评论,部分原因是下面原始内容中的代码仅限于它们自己的小上下文,因此,我想与您共享整个代码库(不要不用担心,我会永久链接选中的行),因为无论如何我都打算打开源代码,以便您可以随意查看任何内容。

整个代码库为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是我通过用settingsit failspytest-django固定来改变相关设置来测试此行为的地方。

正如故障排除部分所述,我也尝试了其他可能的官方方法来执行此操作,它们产生相同的行为。至于为什么这样做,我一无所知。

问题排查

使用标准解决方案

奇怪的是,我还尝试了老旧的django.test.utils.override_settingsmodify_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来证明。


环境

  • Django 2.2.8
  • Pytest Django 3.7.0

0 个答案:

没有答案