I can't get my test to accept the redirect works... I keep getting this error "AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)"
but the redirect working
logs
web_1 | [11/Oct/2020 12:41:33] "GET /calendar/5d8b6a0a-66b8-4909-bf8f-8616593d2663/update/ HTTP/1.1" 302 0
web_1 | [11/Oct/2020 12:41:33] "GET /calendar/list/ HTTP/1.1" 200 4076
Please can some advise where I am going wrong. I have tried using assertRedirects but this still doesn't pass
test.py
class EventTests(TestCase):
def setUp(self):
self.eventbooked = Event.objects.create(
manage=self.user,
availability='Booked',
start_time='2020-09-30 08:00:00+00:00',
end_time='2020-09-30 17:00:00+00:00',
)
def test_event_update_redirect_if_booked_view(self):
self.client.login(email='[email protected]', password='da_password')
response = self.client.get(self.eventbooked.get_absolute_url_edit())
self.assertEqual(response.status_code, 302)
self.assertContains(response, 'Update Availability')
view.py - this is where the redirect happens, this the object is excluded.
class CalendarEventUpdate(LoginRequiredMixin, UpdateView):
model= Event
form_class = EventForm
template_name='calendar_update_event_form.html'
def get_queryset(self):
return Event.objects.filter(manage=self.request.user).exclude(availability='Booked')
def get(self, request, *args, **kwargs):
try:
return super(CalendarEventUpdate, self).get(request, *args, **kwargs)
except Http404:
return redirect(reverse('calendar_list'))
models.py
def get_absolute_url_edit(self):
return reverse('calendar_event_detail_update', args=[str(self.id)])
The assertion error is not your expectation failing.
self.assertEqual(response.status_code, 302)
This passes just fine.self.assertContains(response, 'Update Availability')
This however fails. Your response is a 302 response which doesn't have a content. In the actual example you gave:
"GET /calendar/5d8b6a0a-66b8-4909-bf8f-8616593d2663/update/ HTTP/1.1" 302
-> You're trying to test the content in the response for this request whereas..."GET /calendar/list/ HTTP/1.1" 200
-> ... the content is in the response to this request.