Tests de django no funcionan
Publicado por Jesus David (1 intervención) el 22/04/2020 04:01:48
Estoy haciendo el tutorial de django (Estoy especificamente ahorita en esta parte https://docs.djangoproject.com/es/3.0/intro/tutorial05/) y cuando ejecuto los test obtengo que la variable 'fecha_publicacion' no esta definida, cuando esta viene del modelo 'Pregunta' y ese esta importado en el archivo donde se ejecutan los test
models.py
tests.py
Este es el error que me sale en el Anaconda Prompt
Como pueden ver, dice como 1000 veces que 'fecha_publicacion is not defined', aun viniendo del modelo 'Pregunta', ni siquiera pasa lo mismo con 'texto_pregunta' que tambien es una variable de 'Pregunta', solo con 'fecha_publicacion'.
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from django.db import models
import datetime
from django.utils import timezone
class Pregunta(models.Model):
texto_pregunta = models.CharField(max_length=200)
fecha_publicacion=models.DateTimeField('Fecha de publicacion: ')
def __str__(self):
return (self.texto_pregunta)
def publicacion_reciente(self):
ahora=timezone.now()
return (ahora-datetime.timedelta(days=1)<=self.fecha_publicacion<=ahora)
class eleccion(models.Model):
pregunta = models.ForeignKey(Pregunta, on_delete=models.CASCADE)
texto_eleccion= models.CharField(max_length=200)
votos=models.IntegerField(default=0)
def __str__(self):
return (self.texto_eleccion)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import datetime
from django.test import TestCase
from django.utils import timezone
from .models import Pregunta
from django.urls import reverse
from django.views import generic
class PreguntaModelTests(TestCase):
def test_publicacion_reciente(self):
tiempo = timezone.now() + datetime.timedelta(days=30)
pregunta_futura = Pregunta(fecha_publicacion=tiempo)
return (self.assertIs(pregunta_futura.publicacion_reciente(), False))
def publicacion_reciente_pregunta_vieja(self):
tiempo = timezone.now() - datetime.timedelta(days=1,seconds=1)
pregunta_vieja = Pregunta(fecha_publicacion=tiempo)
return (self.assertIs(pregunta_vieja.publicacion_reciente(), False))
def publicacion_reciente_pregunta_nueva(self):
tiempo = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
pregunta_nueva = Pregunta(fecha_publicacion=tiempo)
return (self.assertIs(pregunta_nueva.publicacion_reciente(), True))
def crear_pregunta(texto_pregunta, days):
tiempo=timezone.now() + datetime.timedelta(days=days)
return Pregunta.objects.create(texto_pregunta, fecha_publicacion)
class QuestionIndexViewTest(TestCase):
def test_sin_preguntas(self):
"""
Si no existen preguntas, se avisa
"""
respuesta=self.client.get(reverse('polls:indice'))
self.assertEqual(respuesta.status_code, 200)
self.assertContains(respuesta, "No hay encuentas disponibles.")
self.assertQuerysetEqual(respuesta.context['ultima_pregunta_lista'], [])
def test_preguntas_pasadas(self):
"""
Preguntas publicadas en el pasado no se publican en el indice
"""
crear_pregunta(texto_pregunta='Pregunta_futura',days=30)
respuesta=self.client.get(reverse('polls:inidce'))
self.assertQuerysetEqual(respuesta.context['lista_ultima_pregunta'], ['<Pregunta:Pregunta pasada.>'])
def test_preguntas_futuras(self):
"""
Preguntas con una fecha de publicacion a futuro no se publican en el indice hasta llegada la fecha.
"""
crear_pregunta(texto_pregunta="Pregunta futura.", days=30)
respuesta = self.client.get(reverse('polls:indice'))
self.assertContains(respuesta, "No hay encuestas disponibles.")
self.assertQuerysetEqual(respuesta.context['lista_ultima_pregunta'], [])
def test_pregunta_futua_y_pasada(self):
"""
Incluso si existen preguntas pasadas y futuras, solo preguntas pasadas
son mostrados.
"""
crear_pregunta(texto_pregunta="Past question.", days=-30)
crear_pregunta(question_text="Future question.", days=30)
respuesta = self.client.get(reverse('polls:indice'))
self.assertQuerysetEqual(
response.context['lista_ultima_pregunta'],
['<Pregunta: Pregunta pasada.>']
)
def test_dos_preguntas(self, fecha_publicacion):
"""
El indice puede desplegar multiples preguntas.
"""
crear_pregunta(texto_pregunta="Past question 1.", days=-30)
crear_pregunta(question_text="Past question 2.", days=-5)
respuesta = self.client.get(reverse('polls:indice'))
self.assertQuerysetEqual(
respuesta.context['lista_ultima_pregunta'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)
class PreguntaDetailView(TestCase):
def test_pregunta_futura(self):
"""
La DetailView de una pregunta con fecha_publicacion en el futuro
devuelve un 404.
"""
pregunta_futura=crear_pregunta(texto_pregunta='Pregunta Futura', days=5)
url =reverse('polls:detail', args=(pregunta_futura.id,))
respuesta=self.client.get(url)
self.assertEqual(respuesta.status_code, 404)
def test_pregunta_pasada(self):
"""
La vista detallada de una pregunta con pub_date en el pasado
Muestra el texto de la pregunta.
"""
pregunta_pasada=crear_pregunta(texto_pregunta='Pregunta pasada', days=5)
url=reverse('polls:detail',args=(pregunta_pasada.id,))
respuesta=self.client.get(url)
self.assertContains(respuesta, pregunta_pasada.texto_pregunta)
Este es el error que me sale en el Anaconda Prompt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
(base) C:\ProgramData\Anaconda3\proyectos django\pagina>python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
EE.EEEEF
======================================================================
ERROR: test_pregunta_futura (polls.tests.PreguntaDetailView)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 82, in test_pregunta_futura
pregunta_futura=crear_pregunta(texto_pregunta='Pregunta Futura', days=5)
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 26, in crear_pregunta
return Pregunta.objects.create(texto_pregunta, fecha_publicacion)
NameError: name 'fecha_publicacion' is not defined
======================================================================
ERROR: test_pregunta_pasada (polls.tests.PreguntaDetailView)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 91, in test_pregunta_pasada
pregunta_pasada=crear_pregunta(texto_pregunta='Pregunta pasada', days=5)
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 26, in crear_pregunta
return Pregunta.objects.create(texto_pregunta, fecha_publicacion)
NameError: name 'fecha_publicacion' is not defined
======================================================================
ERROR: test_dos_preguntas (polls.tests.QuestionIndexViewTest)
----------------------------------------------------------------------
TypeError: test_dos_preguntas() missing 1 required positional argument: 'fecha_publicacion'
======================================================================
ERROR: test_pregunta_futua_y_pasada (polls.tests.QuestionIndexViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 57, in test_pregunta_futua_y_pasada
crear_pregunta(texto_pregunta="Past question.", days=-30)
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 26, in crear_pregunta
return Pregunta.objects.create(texto_pregunta, fecha_publicacion)
NameError: name 'fecha_publicacion' is not defined
======================================================================
ERROR: test_preguntas_futuras (polls.tests.QuestionIndexViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 48, in test_preguntas_futuras
crear_pregunta(texto_pregunta="Pregunta futura.", days=30)
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 26, in crear_pregunta
return Pregunta.objects.create(texto_pregunta, fecha_publicacion)
NameError: name 'fecha_publicacion' is not defined
======================================================================
ERROR: test_preguntas_pasadas (polls.tests.QuestionIndexViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 41, in test_preguntas_pasadas
crear_pregunta(texto_pregunta='Pregunta_futura',days=30)
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 26, in crear_pregunta
return Pregunta.objects.create(texto_pregunta, fecha_publicacion)
NameError: name 'fecha_publicacion' is not defined
======================================================================
FAIL: test_sin_preguntas (polls.tests.QuestionIndexViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\proyectos django\pagina\polls\tests.py", line 35, in test_sin_preguntas
self.assertContains(respuesta, "No hay encuentas disponibles.")
File "C:\ProgramData\Anaconda3\lib\site-packages\django\test\testcases.py", line 454, in assertContains
self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr)
AssertionError: False is not true : Couldn't find 'No hay encuentas disponibles.' in response
----------------------------------------------------------------------
Ran 8 tests in 0.027s
FAILED (failures=1, errors=6)
Destroying test database for alias 'default'...
Valora esta pregunta


0