[英]Why I get error when run two tests in Django APITestCase?
I make tests for my API.我对我的 API 进行测试。 When I run two tests I get error
apps.users.models.DoesNotExist: User matching query does not exist.
当我运行两个测试时,出现错误
apps.users.models.DoesNotExist: User matching query does not exist.
in line self.user = User.objects.get(pk=48)
on the second test .在第二次测试中符合
self.user = User.objects.get(pk=48)
。 But if I run only one test, test is passed.但是如果我只运行一个测试,测试就通过了。 What is the reason?
是什么原因?
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})
The method setUp
is called before every test you define in the test case.在测试用例中定义的每个测试之前调用方法
setUp
。 What's happening is the first test runs setUp and creates users with pk
values ranging from 1 to 123, and the second test creates users with pk
values from 124 to 246, so there is no user with pk=48
.发生的情况是第一个测试运行 setUp 并创建
pk
值从 1 到 123 的用户,第二个测试创建pk
值从 124 到 246 的用户,因此没有pk=48
的用户。
Try selecting the user based on another attribute like email='first@mail.com48'
, and you should be good.尝试根据另一个属性(例如
email='first@mail.com48'
)选择用户,您应该会很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.