我有以下Django单元测试:
def test_highscores_no_n_success_(self):
"""Checks that top 10 highscores of an owner are returned,
if no number of highscores is specified in the request"""
high_score = 100
for users in range(15):
user = create_user(1, 1, "aguha")
user.high_score = high_score
user.save()
high_score +=10
response = self.client.get('/api/highscores/',
{'token': 1, 'key': 1})
self.assertContains(response,
"\"id\": 10, \"high_score\": 180")
对于以下功能:
def highscores(request):
"""Returns the top n (or 10) high scores for an owner"""
r = request.GET
token = r['token']
owner = Owner.objects.get(api_token=token)
try:
n = r['n']
except KeyError:
user_count = User.objects.filter(owner=owner).count()
if user_count >= 10:
n = 10
else:
n = user_count
top_scorers = User.objects.filter(owner=owner).order_by('-high_score').values('id', 'high_score')[:n]
top_scorers_json = json.dumps(list(top_scorers))
return HttpResponse(top_scorers_json,
content_type="application/json")
这是create_user
函数:
def create_user(token, key, owner_username):
"""Creates a user object for the purpose of testing"""
try:
owner = Owner.objects.get(api_token=token)
except ObjectDoesNotExist:
owner = Owner.objects.create(api_token=token, api_key=key,
username=owner_username)
return User.objects.create(owner=owner)
奇怪的是,这个测试有时会成功,而在其他时候会失败。如果失败,则说它无法在响应中找到"id": 10, "high_score": 180
。这怎么可能?每次新测试都会重置数据库,并在测试完成后删除,因此不应该成为问题。这里的问题是什么?
我最初的假设是它可能与运行测试之间的时间有关。但这似乎没有效果。我可以一个接一个地运行它,它可以正常工作。然后我回来跑了几分钟后就失败了。我的功能或测试有问题吗?
答案 0 :(得分:0)
我弄明白为什么我会收到错误。在返回的列表中,有时id
出现在high_score
之前,即我得到"id": 10, "high_score": 180
,这就是测试运行正常的原因。但有时high_score
出现在id
之前,即"high_score": 180, "id": 10
,这就是测试失败的原因。