【问题标题】:Django response context using pytest-django client is always None使用 pytest-django 客户端的 Django 响应上下文总是无
【发布时间】:2017-08-10 18:06:08
【问题描述】:

我正在使用pytest-django 来测试一些 Django 视图。

我想测试响应上下文是否包含某些值,但它始终是None

我的看法:

from django.views.generic import TemplateView

class MyView(TemplateView):
    template_name = 'my_template.html'

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['hello'] = 'hi'
        return context

我的测试:

def test_context(client):
    response = client.get('/test/')
    print('status', response.status_code)
    print('content', response.content)
    print('context', response.context)

如果我使用-s 标志运行此程序以查看打印语句,则状态代码为200content 包含呈现的模板,包括上下文中的"hi"。但是contextNone

我认为这个 clientdjango.test.Client 相同,这应该让我看到上下文......那我错过了什么?

我试过this answer,但得到了

RuntimeError: setup_test_environment() 已被调用,如果不先调用 teardown_test_environment() 就无法再次调用。

【问题讨论】:

  • 您是否正在使用超级用户创建设置?因为有时你的应用程序没有找到这个。你能否展示更多关于你的类Test和你的urls.py,而不是使用硬编码url尝试使用from django.core.urlresolvers import reverse
  • 不,这是一个可公开访问的页面。通常我会在测试中使用reverse(),并在这里尝试过同样的效果,我只是尽可能简化事情以尝试找到问题。
  • 你能插入更多关于这个测试代码的信息吗?
  • 我不确定你想看什么。我已经展示了整个视图和整个测试。
  • 您可以尝试使用django.test import TestCase 并创建一个继承此的类,此方法继承test_context(self)。因为显然,这种方法是可以的。我不知道您是如何将客户传递给此的。

标签: python django pytest-django


【解决方案1】:

在您提供的client link 中,声明clientdjango.test.Client 的一个实例,因此实际上它在那里并没有做任何特别的事情,也不应该成为问题。

您需要按照正确的说明设置环境。
现在让我们看一下错误:

来自setup_test_environment()源代码:

if hasattr(_TestState, 'saved_data'):
      # Executing this function twice would overwrite the saved values.
      raise RuntimeError(
          "setup_test_environment() was already called and can't be called "
          "again without first calling teardown_test_environment()."
)

这就是上面提到的RuntimeError

现在让我们看看teardown_test_environment() 方法:

...
del _TestState.saved_data

所以它删除了上述异常的罪魁祸首。

因此:

from django.test.utils import teardown_test_environment, setup_test_environment

try:
    # If setup_test_environment haven't been called previously this
    # will produce an AttributeError.
    teardown_test_environment()
except AttributeError:
    pass

setup_test_environment() 

...

【讨论】:

  • 谢谢约翰。这一切都说得通……除非我尝试,否则teardown_test_environment() 中的saved_data = _TestState.saved_data 行会生成“AttributeError: type object '_TestState' has no attribute 'saved_data'”...
  • @PhilGyford Well 似乎第一次可以正常工作,但从第二次开始就出现运行时错误。我进行了编辑并将teardown_test_environment 放在try-except block 上,如果它崩溃,它不会取消你的测试。
  • 谢谢......虽然现在我回到了最初遇到的原始 RuntimeError。
  • @PhilGyford 你能把setup_test_environment 也放在try-except block 中并告诉我结果吗?
  • 无论我是否这样做,我仍然会收到 RuntimeError,但我刚刚意识到它是由 pytest_django/plugin.py here 中的 setup_test_environment 调用生成的
猜你喜欢
  • 2011-05-07
  • 1970-01-01
  • 2013-01-01
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-24
相关资源
最近更新 更多