【问题标题】:Django 2.2 - Testing response context with assertQuerySetEqual failsDjango 2.2 - 使用 assertQuerySetEqual 测试响应上下文失败
【发布时间】:2019-11-05 09:02:07
【问题描述】:

尝试使用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())

【问题讨论】:

  • 到目前为止在断言错误中注意到字符串语法

标签: django django-testing


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 2019-05-04
    • 2011-05-07
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多