Crea una cuenta o inicia sesión

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

Solucionando el error encontrado

4/17
Recursos

Aportes 28

Preguntas 4

Ordenar por:

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

En mi caso investigué un poco y encontré que puedes crear una función setUp() en donde creas el objeto que vas a usar en tus pruebas.
Este es mi resultado.

Para preguntas en el pasado debe ser False.
Para preguntas actuales debe ser True.
A continuación el código:

    def test_was_published_recently_with_past_questions(self):
        """was_published_recently() must return Flase for questions whose pub_date is more than 1 day in the past"""
        time = timezone.now() - datetime.timedelta(days=30)
        past_question = Question(question_text="¿Quien es el mejor Course Direct de Platzi?",pub_date=time)
        self.assertIs(past_question.was_published_recently(),False)

    def test_was_published_recently_with_present_questions(self):
        """was_published_recently() must return True for questions whose pub_date is actual"""
        time = timezone.now()
        present_question = Question(question_text="¿Quien es el mejor Course Direct de Platzi?",pub_date=time)
        self.assertIs(present_question.was_published_recently(),True)

Espero les sirva 😃

Mi solución:

import datetime

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

from polls.models import Question
#Acá se testean views y models

class QuestionModelTest(TestCase):

    def creat_a_question(self, pub_date):
        """
        Create Question 
        
        This function create a question to run tests
        
        Parameter:
            -pub_date:timezone
        
        Return a question
        """
        question = Question(question_text="¿Am I a time traveler?", pub_date=pub_date)
        return question
    
    def test_was_publish_recently_with_future_cuestion(self):
        """was_publish_recently return False for questions whose pub_date is in the future"""
        time = timezone.now() + datetime.timedelta(days=30)
        future_question=self.creat_a_question(time)
        self.assertIs(future_question.was_published_recently(), False)

    def test_was_publish_recently_with_present_cuestion(self):
        """was_publish_recently return False for questions whose pub_date is in the future"""
        time = timezone.now()
        future_question=self.creat_a_question(time)
        self.assertIs(future_question.was_published_recently(), True)

    def test_was_publish_recently_with_past_cuestion(self):
        """was_publish_recently return False for questions whose pub_date is in the future"""
        time = timezone.now() - datetime.timedelta(days=30)
        future_question=self.creat_a_question(time)
        self.assertIs(future_question.was_published_recently(), False)

Hola compañeros, comparto mi implementacion

pasos para hacer test

Mi solución:

También existe assertFalse() y assertTrue(), los cuales reciben un solo parámetro, son igual de explícitas que assertIs() y quizás, para este caso, sean una buena elección.

Mi solución al reto:

class QuestionModelTest(TestCase):
    
    #Test for question created on Future
    def test_was_published_recently_wiht_future_questions(self):
        time = timezone.now() + datetime.timedelta(days=30)
        future_question =  Question("¿Quién es el mejor Course Director de Platzi?", pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)
        # self.assertEqual(future_question.was_published_recently(), False)
    
    #Test for questions created on past
    def test_was_published_in_the_past_questions(self):
        time = timezone.now()
        present_question = Question('¿Pregunta x ?', pub_date = time)
        self.assertLess(present_question.was_published_past(), False)
        

    # Test for questions created on present 
    def test_was_published_in_the_present_questions(self):
        time = timezone.now()
        present_question = Question('¿Pregunta x ?', pub_date = time)
        self.assertEqual(present_question.was_published_past(), False)



def test_was_published_recently_with_past_questions(self):
""“was_published_recently returns Fasle for questions whose pub_date is in the past”"“
time = timezone.now() - datetime.timedelta(days=30)
past_question = Question(question_text=”¿Quién es el más mamador de Platzi", pub_date=time)
if past_question.pub_date <= timezone.now() - datetime.timedelta(days=1):

        self.assertIs(past_question.was_published__recently(), False)
    
    else:

        self.assertIs(past_question.was_published__recently(), True)


def test_was_published_recently_with_now_questions(self):
    """was_published_recently returns Fasle for questions whose pub_date is in the now"""
    time = timezone.now()
    now_question = Question(question_text="¿Quién es el mejor influencer de Platzi", pub_date=time)
    self.assertIs(now_question.was_published__recently(), True)

Aqui está el segundo test para comprobar que una Question con pub_date actual devuelve True con la funcion was_published_recently

def test_was_published_recently_with_present_questions(self):
        '''was_published_recently returns True for questions whose pub_date is in present'''
        time = timezone.now()
        present_question = Question(question_text="¿Quién es el mejor Course Director de Platzi?", pub_date=time)
        self.assertIs(present_question.was_published_recently(), True)
def test_was_published_recently_with_past_questions(self):
        """was_published_recently returns False for questions whose pub_date is in the past"""
        time = timezone.now() - datetime.timedelta(days=15)
        future_question = Question(question_text="Who is the best platzi's CD ?", pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)
        
        
    def test_was_published_recently_with_recent_questions(self):
        """was_published_recently returns True for questions whose pub_date is recently"""
        time = timezone.now()
        future_question = Question(question_text="Who is the best platzi's CD ?", pub_date=time)
        self.assertIs(future_question.was_published_recently(), True)

comparto como resolvi el reto:

class QuestionModelTests(TestCase):

    def setUp(self):
        self.question = Question(question_text="¿Quien es el mejor Course Directos de Platzi?")


    def test_was_published_recently_with_futures_question(self):
        """was_published_recently return False for questions whose pub_date is in the future"""
        time = timezone.now() + timedelta( days=30)
        self.question.pub_date = time 
        self.assertIs(self.question.was_published_recently(), False)


    def test_was_published_recently_with_present_question(self):
        """was_published_recently return False for questions whose pub_date is in the prsent"""
        time = timezone.now() - timedelta( hours=24)
        self.question.pub_date = time 
        self.assertIs(self.question.was_published_recently(), False)


    def test_was_published_recently_with_past_question(self):
        """was_published_recently return False for questions whose pub_date is in the past"""
        time = timezone.now() - timedelta( days=1, minutes=1)
        self.question.pub_date = time 
        self.assertIs(self.question.was_published_recently(), False)

Espero asi este bien XD

    def test_was_published_recently_with_past_questions(self):
        """
            Must must return false for questions published in the past
        """
        time = timezone.now() - datetime.timedelta(days = 3) 
        q = Question(question_text = "Question in the past?", pub_date = time)
        self.assertFalse(q.was_published_recently())
        

    def test_was_published_recently_with_present_questions(self):
        """
            Must return True for questions published in the present
        """
        self.assertTrue(Question(question_text = "Question in the present?", pub_date = timezone.now()).was_published_recently())

Acá va mi aporte.
Saludos a Facundo y a todos quienes seguimos la saga Django.

def test_was_published_recently_with_past_questions(self):
        "was_published_recently returns False for question whose pub_date is 1 day or more in the past."
        time = timezone.now() - datetime.timedelta(days = 30)
        past_question = Question(question_text = '¿Quién es el mejor Course Director en Platzi?', pub_date = time)
        self.assertIs(past_question.was_published_recently(), False)

    def test_was_published_recently_with_present_question(self):
        "was_published_recently returns True for question whose pub_date is in the last 24 hours."
        time = timezone.now() - datetime.timedelta(hours = 12)
        present_question = Question(question_text = '¿Quién es el mejor Course Director en Platzi?', pub_date = time)
        self.assertEqual(present_question.was_published_recently(), True)

Para evitar crear objetos en cada test y tener código repetitivo, pueden usar la función setUp que permite crear un set de datos para todos los test dentro de clase, de igual forma si hay bastantes datos a crear, puede cargar fixtures https://docs.djangoproject.com/en/4.0/topics/testing/tools/#fixture-loading

Dejaré mi código por aquí

Mi aporte. Guía en la Django Documentation:

    def test_was_published_recently_with_old_question(self):
        """
        was_published_recently() returns False for questions whose pub_date
        is older than 1 day.
        """
        time = timezone.now() - datetime.timedelta(days=1, seconds=1)
        old_question = Question(pub_date=time)
        self.assertIs(old_question.was_published_recently(), False)

    def test_was_published_recently_with_recent_question(self):
        """
        was_published_recently() returns 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(pub_date=time)
        self.assertIs(recent_question.was_published_recently(), True)

Aquí va mi solución al reto:

Les comparto mi aporte

import datetime

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

from .models import Question

#Testing Models
class QuestionModelTest(TestCase):
    """Define a battery of test """
    def test_was_published_recently_with_future_questions(self):
        """was_published_recenty returns False for questions whose pub_date is in the future"""
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(question_text="¿Quién es el mejor Course Director de Platzi?",pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

   def test_was_published_recently_with_past_questions(self):
        """was_published_recenty_with_past_questions returns False for questions whose pub_date is in the past"""
        time = timezone.now() - datetime.timedelta(days=30)
        past_question = Question(question_text="¿Quién es el mejor Course Director de Platzi?",pub_date=time)
        self.assertIs(past_question.was_published_recently(), False)

    def test_was_published_recently_with_today_questions(self):
        """was_published_recenty returns True for questions whose pub_date is today"""
        time = timezone.now()
        today_question = Question(question_text="¿Quién es el mejor Course Director de Platzi?",pub_date=time)
        self.assertIs(today_question.was_published_recently(), True)
 

Al Parecer quedó bien 😁

(venv) [email protected]:~/work/premiosplatziapp # python manage.py test polls
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...
----------------------------------------------------------------------
Ran 3 tests in 0.002s

OK
Destroying test database for alias 'default'...

Aqui mi clase:

Hola amigos, comparto mi solución.

Código:

Resultado:

Mi aporte

from django.utils import timezone

from .models import Question
# Model.
# Vistas
class QuestionModelTest(TestCase):

    def test_was_published_recently_whith_future_questions(self):
        """was_published_recently return False for question whose pub_date is in the furture"""
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question( question_text="¿Quien es el mejor Course Director de Platzi?", pub_date = time )
        self.assertIs(future_question.was_published_recently(), False)
    
    def test_was_published_recently_whith_past_questions(self):
        """was_published_recently return False for question whose pub_date is in the past"""
        time = timezone.now() - datetime.timedelta(days=30)
        past_question = Question( question_text="¿Quien es el mejor Course Director de Platzi?", pub_date = time )
        self.assertIs(past_question.was_published_recently(), False)
    
    def test_was_published_recently_whith_present_questions(self):
        """was_published_recently return False for question whose pub_date is in the present"""
        time = timezone.now()
        present_question = Question( question_text="¿Quien es el mejor Course Director de Platzi?", pub_date = time )
        self.assertIs(present_question.was_published_recently(), True)```

Pregunta creada en el futuro

    def test_was_published_recently_with_future_questions(self):
        """was_published_recently returns False for questions whose pub_date is in the future"""
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(question_text="¿quien es el mejor profesor?", pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

Pregunta creada en el pasado

    def test_was_published_recently_with_past_questions(self):
        """was_published_recently returns False for questions whose pub_date is in the Past"""
        time = timezone.now() - datetime.timedelta(days=3)
        past_question = Question(question_text="¿quien es el mejor profesor?", pub_date=time)
        self.assertIs(past_question.was_published_recently(), False)

Pregunta creada en el presente

    def test_was_published_recently_with_present_questions(self):
        """was_published_recently returns True for questions whose pub_date is in the Present"""
        time = timezone.now()
        present_questions = Question(question_text="¿quien es el mejor profesor?", pub_date=time)
        self.assertIs(present_questions.was_published_recently(), True)

polls/test.py

class QuestionModelTest(TestCase):
    def test_was_published_recently_for_future_questions(self):
        """was_published_recently return False for questions whose pub_date is in the future"""
        question="Which is the best CD?"
        date = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(question_text=question, pub_date=date)
        self.assertIs(future_question.was_published_recently(), False)


    def test_was_published_recently_for_past_questions(self):
        """was_published_recently return False for questions in the present"""
        date = timezone.now() - datetime.timedelta(days=2)
        past_question = Question(question_text="question", pub_date=date)
        self.assertIs(past_question.was_published_recently(), False)

    def test_was_published_recently_for_present_questions(self):
        """was_published_recently return True for questions in the present"""
        date = timezone.now()
        present_question = Question(question_text="question?", pub_date=date)
        self.assertIs(present_question.was_published_recently(), True)

polls/models.py

 def was_published_recently(self):
        present = timezone.now()
        recently_range = timezone.now() - datetime.timedelta(days=1)
        return present >= self.pub_date >= recently_range