【问题标题】:Django test failing with request.user in get_inital in generic CreateViewDjango 测试在通用 CreateView 中的 get_inital 中使用 request.user 失败
【发布时间】:2012-01-27 13:32:11
【问题描述】:

我有一个这样的通用视图:

class SaveView(CreateView):

    def get_initial(self):
        # Get the initial dictionary from the superclass method
        initial = super(SaveView, self).get_initial()
        # Copy the dictionary so we don't accidentally change a mutable dict
        initial = initial.copy()
        initial['user'] = self.request.user
        return initial

此视图具有 login_required 装饰器,因此 self.request.user 始终有效。

当我使用浏览器访问该页面时,一切正常,但我的测试失败了。我有以下测试设置:

from django.test import TestCase, client

class MyTest(TestCase):
    def setUp(self):
        self.client = client.Client()
    def test1(self):
        self.assertTrue(self.client.login(username='user1',password='password1'))
        data = {'name':'test 1'}
        response = self.client.post('/app/save/', data)
        self.assertEqual(response.status_code, 302)

'/app/save/' 是调用该视图的 url(它在浏览器上运行良好 我的模型有 2 个必填字段“名称”和“用户”,所以这应该会重定向到创建的对象页面,因为我已经通过数据传递了名称,并且应该从 get_initial 方法获取用户。

这确实是“现实生活”中发生的事情,即浏览器。

我可以使这个测试成功通过数据字典中的“用户”的唯一方法。

这是 django.test 模块中的错误还是这是预期的行为,为什么?

提前致谢

【问题讨论】:

标签: django testing django-generic-views


【解决方案1】:

这是预期的行为。来自初始数据的 Django 文档:

initial 参数允许您指定在以未绑定表单呈现此字段时使用的初始值。

当您在测试中发布数据时,您使用的是绑定表单,因此不使用初始数据。表单无效,因为缺少必需的user 字段,因此返回显示表单错误的 200 响应。这与清除浏览器中的用户字段并提交表单会发生的情况相同。

您需要将用户包含在您的post 数据中,然后,测试将通过。

【讨论】:

  • 那么我怎样才能模拟在浏览器中运行良好的行为呢?
  • 通过在您的帖子数据中包含user。正如我在更新的答案中所说,您当前的测试相当于清除浏览器中的用户字段然后提交表单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
  • 2016-01-08
  • 2011-10-16
相关资源
最近更新 更多