Django ApiTestCase泄漏

nzkunb0c  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(132)

我在Django(4.2.1)中使用djangorestframework版本3.14.0测试API端点。
我们有这样的代码:

from django.core.management import call_command
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from account.models import Member, Organization, PhoneNumber
from authorization.models import AuthSMSCode

class SetUp(APITestCase):
    @classmethod
    def setUpTestData(cls):
        # super().setUpClass()
        cls.username = 'sudo'
        cls.member = Member.objects.create_user(first_name='DefaultUser', email='default@gmail.com')
        cls.organization = Organization.objects.create(name="Google", legal_address='1040 Brussels')
        cls.member.organizations.add(cls.organization)
        cls.member.save()
        cls.organization.save()
        cls.phone_number = PhoneNumber.objects.create(number='9999999999', member=cls.member)
        code = 12345
        cls.smscode = AuthSMSCode.objects.create(value=code, phone_number=cls.phone_number)
        Token.objects.create(user=cls.member)
        call_command('create_default_roles')

class ApiTestCaseGroups(SetUp, APITestCase):

    def test_authorized(self):
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.member.auth_token.key)
        url = ...
        response = self.client.get(url, format='json', REMOTE_USER=self.username)
        expected_output = ...
        response_result = response.json()
        self.maxDiff = None
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response_result, expected_output)

class ApiTestCaseMembers(SetUp, APITestCase):

    def test_authorized(self):
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.member.auth_token.key)
        url = .....

        response = self.client.get(url, format='json', REMOTE_USER=self.username)
        expected_output = ...
        response_result = response.json()
        self.maxDiff = None
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response_result, expected_output)

如果我们将ApiTestCaseGroupsApitTestCaseMembers作为类单独运行,它们可以正常工作。但是,当我们将整个文件作为测试manage.py test运行时,它在测试№2 ApiTestCaseMembers时失败,因为对象为空(它返回代码200,因此我们进行了身份验证,但response_result内部没有对象)。
我看到了一些类似的问题,但这些解决方案在这里不起作用。我们应该朝什么方向去解决这个问题?

uajslkp6

uajslkp61#

问题出在主键上。Django在测试期间一直在创建和删除数据库,但新对象是由下一个主键(或id)创建的。因此,我没有使用硬编码的id,比如1,2,而是首先从安装程序中解析它们,然后将其放入测试本身。

相关问题