0
0

More than 1 year has passed since last update.

Djangoでcookieを使うJWTレスポンスのテストコードの書き方

Posted at

Djangoでcookieを使うJWTレスポンスのテストコードの書き方

ポイント

・JWTレスポンスのテストはunittestでやります。
・SimpleCookieでtokenをジェネレーターする

test.py
import pytest
import uuid

from unittest import mock
from django.http import HttpResponse
from django.test import TestCase
from http.cookies import SimpleCookie

from rest_framework.test import APIRequestFactory
from rest_framework import status

from . import AuthMiddleware

def user_login():
    factory = APIRequestFactory()
    url = "http://127.0.0.1:8000/login"
    post_data = {
        "email": "unit@test.com",
        "password": "test"
    }
    request = factory.post(url, data=post_data)
    response = login(request)
    return response

@pytest.mark.django_db
class MiddlewareTest(TestCase):
    """
    JWTテスト
    """
    def setUp(self):
        # tokenをバリデートするミドルウェアをイニシャル
        self.mock_init = mock.patch.object(
            AuthMiddleware, "__init__", fake_init
        ).start()

        self.addCleanup(mock.patch.stopall)

    def test_JWTテスト_成功_200(self):
        # get token
        # 前に作成されたuser_loginフンクションでtokenを取得する
        response = user_login()
        token = response.cookies.get('jwt_cookie').value

        # create URL
        id = str(uuid.uuid4())
        url = "http://127.0.0.1:8000/users" + "/" + id

        # call API
        # modify token for NOT pass the token authorization
        self.client.cookies = SimpleCookie({'jwt_cookie': token})
        # getメソッドを呼び出し、tokenバリデーションが成功になったら200を返します
        # 自動的にAuthMiddleware(ミドルウェア)でtokenをバリデーションする
        response = self.client.get(url, content_type='application/json')

        # check is the response is correct
        assert(response.status_code == status.HTTP_200_OK)
0
0
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
0