LoginSignup
0
1

More than 3 years have passed since last update.

Djangoのテストでrequest.POSTに任意の値を設定する方法

Last updated at Posted at 2020-11-22

テスト対象の関数

my_view.py
class MyView(LoginRequiredMixin, View):
    def post(self, request, *args, **kwargs):
        if 'test_value' in request.POST:
            # 何らかの処理

上記のpostメソッドでrequest.POSTが'test_value'という情報を持っている場合のテストをしたい。

テストコード

test_my_view.py
from django.test import TestCase, Client

class MyViewTests(TestCase):
    def setUp(self):
        self.client = Client()
        self.client.login(email='email', password='password')

    def test_my_view(self):
        response = self.client.post(
            path='/my_app/my_view',
            data={'test_value': 'A'},
        )
        # 検証
        self.assertXxx(xxx, xxx)

これでOK

breakpoint()を貼って確認してみる。

% python manage.py test

.> /views/MyView.py(191)post()
-> if 'test_value' in request.POST:
(Pdb) l
188     class MyView(LoginRequiredMixin, View):
189         def post(self, request, *args, **kwargs):
190             breakpoint()
191  ->         if 'test_value' in request.POST:
192                 # 何らかの処理
...
(Pdb) request.POST
<QueryDict: {'test_value': ['A']}>
(Pdb) request.POST['test_value']
'A'

おまけ

test_my_viewで使用しているself.client.post()にcontent_type='application/json'を渡すとrequest.POSTではなくrequest.bodyに値が設定されるので注意。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1