from typing import cast from django.http import HttpResponse from django.urls import reverse from rest_framework import status from rest_framework.response import Response from rest_framework.test import APIClient, APITestCase from accounts.models import CustomUser from accounts.models.email_address import EmailAddress class CustomPermissionTestCase(APITestCase): def setUp(self): self.user = CustomUser.objects.create( login_id="testuser", username="Test User", is_staff=True, is_active=True, is_superuser=False, password_changed=False, ) self.email1 = EmailAddress.objects.create( user=self.user, email="test1@example.com", is_primary=True, ) self.user.set_password("password") self.user.save() def test_custom_user(self): # 未認証でのアクセス users_uri = reverse("users-list") response = self.client.get(users_uri) response = cast(HttpResponse, response) self.assertEqual(response.status_code, 401) # 認証処理 token_uri = reverse("token_obtain_pair") response = self.client.post( token_uri, {"login_id": "testuser", "password": "password"}, format="json", ) response = cast(HttpResponse, response) self.assertEqual(response.status_code, status.HTTP_200_OK) response = cast(Response, response) if response.data: self.accessToken = response.data["access"] self.client: APIClient = cast(APIClient, self.client) self.client.credentials(HTTP_AUTHORIZATION="Bearer " + self.accessToken) else: self.fail("Failed to get access token") users_uri = reverse("users-list") response = self.client.get(users_uri) response = cast(HttpResponse, response) self.assertEqual(response.status_code, 200)