如何测试同一视图中的两个 django 表单

问题描述 投票:0回答:2

所以我有一个视图可以在同一个 POST 请求中处理两种不同的表单。

以前测试很容易,因为我只有一种表格,所以它会是这样的:

def test_post_success(self):
    response = self.client.post("/books/add/", data={"title": "Dombey and Son"})

    self.assertEqual(response.status_code, HTTPStatus.FOUND)
    self.assertEqual(response["Location"], "/books/")

如果我有一个带有“前缀”的第二种形式,我将如何构造请求的data对象。

我在想:

form_1_data = {foo}
form_2_data = {bar}
response = self.client.post("/books/add/", data={form_1_data, form_2_data)

但它显然不起作用

django unit-testing django-forms
2个回答
0
投票

您可以将带有

**
标记的词典组合起来。像这样:

>>> data_1 = {"title": "Dombey and Son"}
>>> data_2 = {"character": "Donald Duck"}
>>> {**data_2, **data_1}
{'character': 'Donald Duck', 'title': 'Dombey and Son'}

0
投票

就我而言,我是这样解决的:

class RegisterTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.data = {
            **{'username': 'J0hnDo3', 'first_name': 'John', 'last_name': 'Doe',
            'email': '[email protected]', 'password1': 'secureP4ssword123', 'password2': 'secureP4ssword123'},
            **{'company': 2, 'phone': '', 'type_user': 'student', 'branch': 2}
        }

def test_register_success(self):
    response = self.client.post(reverse('register'), data=self.data)
    self.assertRedirects(response, '/login/', 302)

我意识到更新:

response = self.client.post(
    reverse('register'),
    data=json.dumps(self.data),
    content_type='application/json'
)

response = self.client.post(reverse('register'), data=self.data)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.