0

Trying to test response context in Django TestCase with assertQuerysetEqualbut it fails.

I tried printing count of Country.objects.all().count() and response.context['countries'].count(). both returns 1 as I create one record at start of the test.

Also tried ordered=True on assertion method but no luck still fails the test. Am I missing something or need do it other way?

View that returns response

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

Test using

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'])

Error I'm getting

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)>]

Getting same error for

self.assertQuerysetEqual(Country.objects.all(), Country.objects.all())
Priyash
  • 162
  • 2
  • 12

1 Answers1

1

Found solutions from other question which end up with similar issue

Solution was to use different transform function 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)
Priyash
  • 162
  • 2
  • 12