Testing a view

Hello everybody:
I’m trying to test the following view

class PoolRescateListView(LoginRequiredMixin, ListView):

    template_name = 'coleccionistas/pool_de_rescate.html'

    def get_queryset(self):
        coordenadas = Coordenada.objects.exclude(
            pagina = 99
            ).exclude(
                barajitas__coleccionista = self.request.user,
            ).filter(
            barajitas__coleccionista__isnull = False,            
            barajitas__en_tablero = False,
            barajitas__sobre__paquete__edicion_id = self.kwargs['edicion_pk']
            )


        coordenadas = coordenadas.annotate(barajitas_disponibles = Count('barajitas')).order_by('numero')
        return coordenadas

    def get_context_data(self, **kwargs):
        context =  super().get_context_data(**kwargs)
        total_barajitas = Barajita.objects.exclude(coordenada__pagina = 99).filter(en_tablero = False,
            coleccionista__isnull = False,
            sobre__paquete__edicion_id = self.kwargs['edicion_pk']).count()
        context['total_barajitas'] = total_barajitas
        context['edicion_pk'] = self.kwargs['edicion_pk']

        return context

when I test the view in the browser (manual mode) everything seems to work fine, but when I run the corresponding test althoguht it doesn’t trhow any error or fail I can see in the coverage report that my test doesn’t touch the code. Here is the test:

class rescatarBarajitaTest(TestCase):
    # TODO: testear las opciones de rescate si es que no se han probado en otra parte
    @classmethod
    def setUpTestData(cls):
        cls.edicion = EdicionFactory(tiraje=1, coleccion=ColeccionFactory(nombre='rescatarBarajitaTest'))
        cls.ema = get_user_model().objects.create_user(
            username = 'ema', 
            email = 'camila@ejemplo.com',
            password = '123456'
        )
        cls.samuel = get_user_model().objects.create_user(
            username = 'samuel', 
            email = 'albany@ejemplo.com',
            password = '123456'
        )

        cls.album_ema = AlbumFactory(coleccionista=cls.ema,edicion=cls.edicion)
        cls.album_samuel = AlbumFactory(coleccionista=cls.samuel, edicion=cls.edicion)
        cls.compra = CompraFactory(
            paquete = cls.edicion.paquetes.first(),
        )
        cantidad = math.floor(cls.compra.paquete.sobres.all().count() / 2)

        cls.venta_ema = VentaFactory(
            coleccionista=cls.ema,
            cantidad=cantidad,
            edicion=cls.edicion,
            detallista=cls.compra.detallista
        )

        cls.venta_samuel = VentaFactory(
            coleccionista=cls.samuel,
            cantidad=cantidad,
            edicion=cls.edicion,
            detallista=cls.compra.detallista
        )

    def setUp(self):
        self.client.logout()

    def test_url_exists_at_correct_location(self):
        self.client.login(username = 'samuel', password = '123456' )

        for sobre in self.venta_samuel.sobres.all():
            data = {
            'sobre_pk': sobre.pk,
            'album_pk': self.album_samuel.pk
            }

            self.client.post("/coleccionistas/sobre/abrir/", data=data)

        response = self.client.get(f'/coleccionistas/pool_de_rescate/{self.edicion.pk}/')
        print(response.context['barajitas_detalle'])
        self.assertEqual(response.status_code, 200)

        for coordenada in response.context['object_list']:
            data = {
                'edicion_pk': self.edicion.pk,
                'coordenada_pk': coordenada.pk
            }
            print(f'se envia la data {data} a la vista')
            response = self.client.post('/coleccionistas/rescatar_barajita/', data=data)
            self.assertEqual(response.status_code, 302)
            self.assertRedirects(
                response,
                reverse(
                    'album_detail',
                     kwargs={'pk': self.album_samuel.pk}
                )
            )


    def test_url_available_by_name(self):
        login = self.client.login(username = 'ema', password = '123456')
        """Se abren todos los sobres vendidos al coleccionista"""

        for sobre in self.venta_ema.sobres.all():
            data = {
            'sobre_pk': sobre.pk,
            'album_pk': self.album_ema.pk
            }

            self.client.post("/coleccionistas/sobre/abrir/", data=data)

        response = self.client.get(f'/coleccionistas/pool_de_rescate/{self.edicion.pk}/')
        
        print(response.context['barajitas_detalle'])
        self.assertEqual(response.status_code, 200)

        for coordenada in response.context['object_list']:
            data = {
                'edicion_pk': self.edicion.pk,
                'coordenada_pk': coordenada
            }

            response = self.client.post(reverse('rescatar_barajita'), data=data)
            self.assertEqual(response.status_code, 302)
            self.assertRedirects(
                response,
                reverse(
                    'album_detail',
                     kwargs={'pk': self.album_ema.pk}
                )
            )

    def test_redirects_if_user_not_logged(self):
        data = {
            'edicion_pk': self.edicion.pk,
            'coordenada_pk': 1
        }

        response = self.client.post(reverse('rescatar_barajita'), data=data)
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response,'/accounts/login/?next=/coleccionistas/barajitas/rescatar/')

I think is neccesary to give some context at this point. I am working on an Collectible stickers Album app. The workflow is like this: When a user have repeated stickers, these stickers go to a pool and thus other users can retrieve them for their own albums. So the view only will show the available sticker to that specific user retrieve. If any aditional information or codesnippet is needed I’ll be happy of give it. Sorry for my ugly english

Another tinhg: I realized that in the test this piece of code,

        for coordenada in response.context['object_list']:
            data = {
                'edicion_pk': self.edicion.pk,
                'coordenada_pk': coordenada.pk
            }

the object_list query is empty, While if I visit the view in the browser everything works fine.

Can you explain what you mean by this or show us the report?

Have you confirmed that the test’s response from the view is correct? Not just the status code, but the actual content.

ok. here is the output of my test:

Now the coverage report(test itself):

as you can see in the image above, the for loop is ignored in the test, so you can conclude that the object_list is empty, (in fact I used a print statement to verify this). But when you go to the view in a normal way e. g. using th browser, everything works fine.

Here is also the coveragre report of the view:

coverage_view_report_1

I know it looks a bit complicated but itsn’t really. If you need some other information I’ll be happy to give it.

One more thing I had forgotten, the response content is fine but it renders the HTML corresponding to a empty page e.g. with the message ‘The are no records’.