LoginSignup
4

More than 5 years have passed since last update.

[django]テスト用にPOSTリクエストを作りたい

Posted at

RequestFactory を使う。


from django.test import Client, RequestFactory, TestCase

class HogeTestCase(TestCase):

    def setUp(self):

        self.user = User.objects.create_user('HogeTaro', 'taro@hoge.com', 'password')

        self.client = Client()

        self.client.login(username='HogeTaro', password='password')

    def test_foo(self):

        data = {
            'name': 'FooJiro',
            'email': 'jiro@foo.com',
        }

        factory = RequestFactory()

        request = factory.post('[URL PATH]', data)

        # ログインユーザ設定
        request.user = self.user

参考URL
- https://docs.djangoproject.com/ja/2.1/topics/testing/advanced/

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
4