我在Django单元测试(Python 3.4)中遇到了AssertEquals()的一些奇怪行为。下面的测试结果在断言错误这样:Python 3.4 AssertEqual()在Django单元测试中使用时的不可预测行为
line 113, in test_index_view_with_questions_without_choices self.assertEqual(response.context['lastest_question_list'], []) AssertionError: [] != []
下面是测试本身:
def test_index_view_with_questions_without_choices(self):
'''
If a question has no choices it should not be
displayed on the questions index page no matter if it's
a past or a future question.
'''
create_question_with_no_choices(question_text='no choices q1', days=-5)
create_question_with_no_choices(question_text='no choices q2', days=5)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, 'No polls are available.', status_code=200)
self.assertEqual(response.context['lastest_question_list'], [])
更改最后一行,像这样:
self.assertEqual(len(response.context['lastest_question_list']), 0)
使测试工作正常但我无法得到它的原因拒绝与清单本身一起工作。
我也有同样的应用程序和项目非常类似的测试,它工作得很好:
def test_index_view_with_no_questions(self):
'''
If no questions exist, an appropriate message
should be displayed.
'''
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No polls are available.')
self.assertQuerysetEqual(response.context['lastest_question_list'], [])
这里的视图本身以显示查询集是如何定义的:
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'lastest_question_list'
def get_queryset(self):
'''
Returns last five published questions
(not including those set to be published in the future)
Also excludes the questions with an empty choice_set.
'''
qset = Question.objects.annotate(choices_count=Count('choice'))
qset = qset.filter(choices_count__gte=1, pub_date__lte=timezone.now())
qset = qset.order_by('-pub_date')[:5]
return qset
PS:我发现了一个类似的问题描述HERE,但我仍然困惑什么是真正导致这样的一种行为。尽管我知道如何使这个测试在这个特定的例子中起作用,但对于我理解发生的事情仍然很重要。 :)
谢谢你的回复!我自己也检查过它..所以response.context ['some key']我们实际访问的是一个QuerySet本身,并且有类型django.db.models.query.QuerySet,所以它不是一个列表。但是如何解释其他测试工作正常?它也包含行:** self.assertQuerysetEqual(response.context ['lastest_question_list'],[])**,但在这种情况下,它的工作原理..差异在哪里? – sancau
我更新了我的答案。检查这个问题上的答案以及:http://stackoverflow.com/questions/11610943/django-1-4-assertquerysetequal-how-to-use-method?answertab=votes#tab-top –
非常有帮助,谢谢! – sancau