Django 2.2-使用assertQuerySetEqual测试响应上下文失败

时间:2019-06-23 06:32:27

标签: django django-testing

尝试使用assertQuerysetEqual在Django TestCase中测试响应上下文,但失败。

我尝试打印Country.objects.all().count()response.context['countries'].count()的计数。当我在测试开始时创建一条记录时,两者都返回1。

还尝试了ordered=True的断言方法,但是仍然没有运气使测试失败。我是否缺少某些东西或需要以其他方式进行?

返回响应的视图

class CountriesListView(generic.ListView):
    model = Country
    template_name = 'management/countries/countries.html'
    context_object_name = 'countries'

使用

class CountryTest(TestCase):
    def setUp(self):
        self.countries_list_url = '/countries'

    def test_response_returns_countries_context(self):
        Country.objects.create(
            name='India',
            iso_3166_1='IN'
        )
        response = self.client.get(self.countries_list_url)

        self.assertQuerysetEqual(Country.objects.all(), response.context['countries'])

我遇到错误

AssertionError: Lists differ: ['<Country: Country object (1)>'] != [<Country: Country object (1)>]

First differing element 0:
'<Country: Country object (1)>'
<Country: Country object (1)>

- ['<Country: Country object (1)>']
?  -                             -

+ [<Country: Country object (1)>]

遇到相同的错误

self.assertQuerysetEqual(Country.objects.all(), Country.objects.all())

1 个答案:

答案 0 :(得分:0)

Found solutions from other question which end up with similar issue

解决方案是使用不同的变换函数transform=lambda x: x

    def test_response_returns_countries_context(self):
        Country.objects.create(
            name='India',
            iso_3166_1='IN'
        )
        response = self.client.get(self.countries_list_url)

        self.assertQuerysetEqual(response.context['countries'], Country.objects.all(), transform=lambda x: x)