Crea una cuenta o inicia sesión

¡Continúa aprendiendo sin ningún costo! Únete y comienza a potenciar tu carrera

Testing de Views

5/17
Recursos

Aportes 23

Preguntas 3

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

Mi solución

    def test_questions_with_future_pub_date(self):
        """
            Questions with a pub_date greater than the current date should not appear in the Index View.
        """
        Question(question_text='Present Question', pub_date=timezone.now()).save()
        Question(question_text='Future Question', pub_date=timezone.now() + datetime.timedelta(days=30)).save()

        response = self.client.get(reverse('polls:index'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Present Question")
        self.assertNotContains(response, "Future Question")

Solución al Challenge (atento a la retroalimentación)

def test_questions_with_future_pub_date(self):
        """Questions with date greater to timezone.now shouldn't be displayed"""
        time = timezone.now() + datetime.timedelta(days = 30)
        future_question = Question(question_text = "This is a Question for the test", pub_date = time)
        future_question.save()
        response = self.client.get(reverse('polls:index'))
        self.assertNotIn(future_question, response.context['latest_question_list'])
(venv) [email protected]:~/work/premiosplatziapp # python manage.py test polls
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.....
----------------------------------------------------------------------
Ran 5 tests in 0.018s

OK
Destroying test database for alias 'default'...
def test_future_question_no_published(self):
        """If question pub date is in the future, don't show it in the index page"""
        response = self.client.get(reverse("polls:index"))
        time = timezone.now() + datetime.timedelta(days=15)
        future_question = Question(question_text="Who is the best Platzi's Course Director ?", pub_date=time)
        self.assertNotContains(response, future_question)

Mi aporte al reto:

Para evitar el error de los paréntesis que tuvo Facundo, les recomiendo instalar la extensión de VSCode llamado “Rainbow Brackets”. Es muy útil ya que identifica cada par de paréntesis con un color diferente y resalta que paréntesis le corresponde a su par.

Si alguien tiene el mismo problema que yo con la view index y estan utilizando funciones view pueden aplicar el filtro de esta manera

def index(request):
    latest_question_list = Question.objects.all().filter(pub_date__lte=timezone.now()).order_by("-pub_date")[:5]
    return render(request,"polls/index.html",{
        "latest_question_list":latest_question_list
    })

Mi solución al reto luce de la siguiente manera (estaré atento a sus criticas constructivas xd):

Si quieren correr los test usando Pychar Community, les dejo la configuarion

Si te aparece el siguiente error al ejecutar el test :

name ‘reverse’ is not defined

debes de importar el modulo reverse de Django

from django.urls import reverse

Mi Test queda así

def test_no_questions_in_the_future(self):
        """Question created in the future has not been included in latest_question_list"""
        Question(question_text="Question in the future?", pub_date=timezone.now() + timezone.timedelta(days=1)).save()
        response = self.client.get(reverse("polls:index"))
        self.assertQuerysetEqual(response.context["latest_question_list"], [])

Mi propuesta: al ser una pregunta futura, no debería estar dentro del “latest_question_list”, que luego se representa en el index view 😃

def test_future_question_is_not_displayed(self):
        """"If there is a future question, it is not shown in the index view"""
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(question_text="Quién es el mejor CD de Platzi?", pub_date=time).save()
        response = self.client.get(reverse("polls:index"))
        self.assertQuerysetEqual(response.context["latest_question_list"], [])

En la documentación no encontré nada que ayudase 😦

**Soluciob al reto de la clase anterior. **
Utilize el metodo assertEqual como lo recomendo el profe

    def test_was_pusblished_recentely_with_present_question(self):
        """Was_published_recently returns True for quiestion whose pub_date is at now"""
        time = timezone.now() 
        now_question = Question(question_text='¿Cual es el mejor estudiante de platzi?', pub_date= time)
        self.assertEqual(now_question.was_published_recentely(), True)

    def  test_was_published_recentely_with_past_question(self):
        """Was_published_recently returns False for question Whose pub_date is in Past"""
        time = timezone.now() - datetime.timedelta(days=1)
        past_question = Question(question_text= '¿Cual es la mejor escuela de platzi?', pub_date= time)
        self.assertAlmostEqual(past_question.was_published_recentely(), False)

Aquí va mi reto ;D

Esto de los tests es buenisimo, pero me gustaría saber si es posible debbugear los tests en VS Code para ver el flujo de la inofrmación.

Saludos.

Muy generalista, se pueden dividir los tests para ser mas especificos. Como hacer assertEqual en la longitud, assert de la pregunta esperada, etc.

Supongo que lo veremos en breve 😃

    def test_future_question(self):
        """if the new question is in a future, dont let to see sach question"""
        time = timezone.now() + timezone.timedelta(days=30)
        future_question = Question.objects.create(question_text="future question",pub_date=time)
        response = self.client.get(reverse("polls:index"))

        self.assertNotContains(response,future_question)

Dejo las que hice

En Test

def test_get_queryset_with_future_questions(self):
    """If question.pub_date is in the future, it is not displayed"""
    time = timezone.now() + dt.timedelta(days = 30)
    future_question = Question(question_text = "Any Question", pub_date = time)
    future_question.save()
    response = self.client.get(reverse('polls:index'))
    self.assertNotIn(future_question, response.context['latest_question_list'])
    
def test_get_queryset_with_old_questions(self):
    """If question.pub_date is older than 1 day, it is not displayed"""
    time = timezone.now() - dt.timedelta(days = 1, seconds = 1)
    old_question = Question(question_text = "Any Question", pub_date = time)
    old_question.save()
    response = self.client.get(reverse('polls:index'))
    self.assertNotIn(old_question, response.context['latest_question_list'])

En views

def get_queryset(self):
    """Return the last five published questions."""
    # return Question.objects.order_by("-pub_date")[:5]
    # return Question.objects.filter(pub_date__lte = timezone.now()).order_by('-pub_date')[:5]
    questions = Question.objects.filter(pub_date__lte = timezone.now())
    questions = questions.filter(pub_date__gt = timezone.now() - dt.timedelta(days = 1))
    questions = questions.order_by('-pub_date')[:5]
    return questions

Comparto mis testCases

import datetime
from django.test import TestCase
from django.utils import timezone

from .models import Question

class QuestionModelTests(TestCase):

    SAMPLE_QUESTION = "¿Is this a question?"

    def test_was_published_recently_with_future_questions(self):
        """Was published recently should return False for questions whose
        pub_date is in the future."""
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(question_text=self.SAMPLE_QUESTION, pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)


    def test_was_not_published_recently(self):
        """Was published recently should return False for questions whose
        pub_date is older than 1 day."""
        time = timezone.now() - datetime.timedelta(days=1, seconds=1)
        old_question = Question(question_text=self.SAMPLE_QUESTION, pub_date=time)
        self.assertIs(old_question.was_published_recently(), False)
    
    def test_was_published_recently_with_recent_question(self):
        """Was published recently should return True for questions whose
        pub_date is within the last day."""
        time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
        recent_question = Question(question_text=self.SAMPLE_QUESTION, pub_date=time)
        self.assertIs(recent_question.was_published_recently(), True)

Hola profe, tengo un error en la linea:
self.assertContains(response, “No Polls are available”)
En la consola: AssertionError: False is not true : Couldn’t find ‘No Polls are available’ in response
He revisado el codigo mil veces, es igualito al tuyo. Si comento la linea, el test funciona. Ayuda porfa!!

Yo hice 2 pruebas.
Una con un solo registro en el futuro.
La segunda con 2 registros uno en el futuro y otro en el presente

class QuestionIndexViewTest(TestCase):
    
    def test_no_questions(self):
        """ If no question exits, an appropiate message is displayed"""
        response = self.client.get(reverse("polls:index"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No Polls are avariable.")
        self.assertQuerysetEqual(response.context["latest_question_list"], [])
    
    def test_was_no_publish_questions_in_the_future(self):
        """If there is a publication that has a date in the future, it should not be published. and send the message: No Polls are avariable."""
        time = timezone.now() + datetime.timedelta(days=30)
        Question( question_text="¿Quien es el mejor Course Director de Platzi?", pub_date = time ).save()
        response = self.client.get(reverse("polls:index"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No Polls are avariable.")
        self.assertQuerysetEqual(response.context["latest_question_list"], [])
    
    def test_was_no_publish_questions_in_the_future_and_publish_question_now(self):
        """If there is a publication that has the future date and today's publications, only those of today should be published. """
        time = timezone.now() + datetime.timedelta(days=30)
        Question( question_text="¿Quien es el mejor Course Director de Platzi?", pub_date = time ).save()
        Question( question_text="¿Cual es el mejor curso de Platzi?", pub_date = timezone.now() ).save()
        response = self.client.get(reverse("polls:index"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "¿Cual es el mejor curso de Platzi?")
        self.assertEqual(len(response.context["latest_question_list"]), 1)

Yo hice esta (para los 30 días después), pero quería hacer (la de un día en concreto).

tests

    def test_was_published_last_time(self):
        """
        was_published_last_time returns True for questions whose pub_date is in the past time
        """
        time = timezone.now() - datetime.timedelta(days=30)
        last_question = Question(question_text="¿Quién es el mejor Course Director de Platzi?", pub_date=time)
        # Verificar que el resultado de aplicar el método was_published_last_time() sobre last_question es igual a verdad
        self.assertIs(last_question.was_published_last_time(), True)

models

    def was_published_last_time(self):
        return self.pub_date <= timezone.now() -datetime.timedelta(days=30)