为什么在 Django APITestCase 中 运行 两个测试时出现错误?

Why I get error when run two tests in Django APITestCase?

我为我的 API 做测试。当我 运行 两次测试时,我在 第二次测试 的行 self.user = User.objects.get(pk=48) 中收到错误 apps.users.models.DoesNotExist: User matching query does not exist.。但是如果我运行只测试一个,测试就通过了。这是什么原因?

class MyTestCase(APITestCase):
    def setUp(self):
        user_data = []
        for i in range(1, 124):
            user_data.append({
                'email': 'first@mail.com'+str(i),
                'first_name': "firstname"+str(i),
                'last_name': "lastname"+str(i),
                'ip_address': "192.168.0."+str(i),
            })
        users = User.objects.bulk_create([User(**i) for i in user_data])
        self.user = User.objects.get(pk=48)   # I get error in this line

    def test_users_list(self):
        ...

    def test_users_pagination(self):
        url = reverse('users-list')
        self.client.force_authenticate(self.user)
        response = self.client.get(url, {'users_count': 24, 'page': 2})

在测试用例中定义的每个测试之前调用方法 setUp。发生的事情是第一个测试运行 setUp 并创建 pk 值从 1 到 123 的用户,第二个测试创建 pk 值从 124 到 246 的用户,因此没有用户 pk=48.

尝试根据 email='first@mail.com48' 等其他属性选择用户,您应该会成功。