EDIT
Here is my test:
def test_admin_sees_unpublished_questions(self):
"""
Logged-in admin users see unpublished questions on the index page.
"""
# create admin user and log her in
password = 'password'
my_admin = User.objects.create_superuser('myuser', 'myemail@test.com', password)
user = authenticate(username="myuser", password="password")
if user is not None:
print(user.username)
else:
print('Not found!')
self.client.login(username=my_admin.username, password=password)
#create future question and check she can see it
create_question(question_text="Unpublished question.", days=5)
response = self.client.get(reverse('polls:index'))
self.assertContains('Please review these unpublished questions:')
self.assertEqual(response.context["user"], user)
self.assertQuerysetEqual(
response.context['unpublished_question_list'],
['<Question: Unpublished question.>']
)
It's a bit messy. There are a few lines checking if there is a user in context which all appear to show response.context["user"] is there.
Here is my view:
class IndexView(generic.ListView):
template_name = 'polls/index.html'
def get_queryset(self):
"""
Return the last five published questions (not including those set to be
published in the future).
"""
queryset = Question.objects.filter(
pub_date__lte=timezone.now()
).exclude(
#question without choices
choice=None
).order_by('-pub_date')[:5]
return queryset
def get_context_data(self, **kwargs):
"""
Override get_context_data to add another variable to the context.
"""
context = super(IndexView, self).get_context_data(**kwargs)
context['unpublished_question_list'] = Question.objects.filter(pub_date__gte=timezone.now())
print(context)
return context
I am writing tests for the django polls app tutorial.
I want to write a test which which logs in a user, creates an instance of the question model with a publish date in the future, and ensures that this logged in user can see this question.
I've tried using
self.assertContains('Please review these unpublished questions: ')
in the test method because my template looks like this:
{% if user.is_authenticated %}
<p>Hello, {{ user.username }}. Please review these unpublished questions: </p>
{% if unpublished_question_list %} etc
but even though
self.assertEqual(response.context["user"], user)
passes testing after
self.client.login(username=my_admin.username, password=password)
my template doesn't seem to be rendering properly to the test client.
Some help would be much appreciated!
AssertionError: False is not true : Couldn't find 'Please review these unpublished questions: ' in response