Django 测试失败,通用 CreateView 中的 get_inital 中的 request.user

标签 django testing django-generic-views

我有一个像这样的通用 View :

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

此 View 具有 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/' 是调用该 View 的 url(它在浏览器上运行良好 我的模型有 2 个必填字段“名称”和“用户”,因此这应该发出重定向到创建的对象页面,因为我已经通过数据传递了名称并且应该从 get_initial 方法获取用户。

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

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

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

提前致谢

最佳答案

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

The initial argument lets you specify the initial value to use when rendering this Field in an unbound Form.

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

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

关于Django 测试失败,通用 CreateView 中的 get_inital 中的 request.user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9033980/

相关文章:

python - 如何从 Django 中的查询中获取枚举结果?

django - 基于仅在新版本中存在的字段的条件Django迁移

testing - 在 angulardart 5 上运行测试

python - 如何覆盖 django rest 框架( DRF )中的 Response 类?

python - Django 通用 View :How does DetailView automatically provides the variable to the template ? ?

python - 一种以字符串形式存储相对日期的方法

django - 如何在基于 Django 类的 View 上使用 permission_required 装饰器

python - Django UpdateView 不上传 ImageField

testing - 如何在 Cypress 中点击 x 次

c# - 针对 WPF 和 Dispatcher 的 NMock 问题测试