bwilburn
bwilburn

Reputation: 23

Django Testing - TypeError: argument of type model is not iterable

I'm getting an error when running python manage.py test:

TypeError: argument of type 'Course' is not iterable

Here are my tests:

    def test_course_list_view(self):
       resp = self.client.get(reverse('courses:list'))
       self.assertEqual(resp.status_code, 200)
       self.assertIn(self.course, resp.context['courses'])
       self.assertIn(self.course2, resp.context['courses'])

    def test_course_detail_view(self):
       resp = self.client.get(reverse('courses:detail', args=[self.course.pk]))
       self.assertEqual(resp.status_code, 200)
       self.assertIn(self.course, resp.context['course'])

Here is my view that I'm testing:

def course_list(request):
   courses = Course.objects.all()
   return render(request, 'courses/course_list.html', {'courses': courses})

def course_detail(request, pk):
   course = get_object_or_404(Course, pk=pk)
   return render(request, 'courses/course_detail.html', {'course': course})

Confused because i'm not getting an error in test_course_list_view but test_course_detail_view does throw an error?

Upvotes: 0

Views: 1776

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

assertIn does what the name implies: it asserts that argument one is in argument two. But in your test for the detail view, you are passing resp.context['course'] as your argument two, which is not a list or container, it is a single instance.

You need to compare that the two are equal, not that one is in the other.

self.assertEqual(self.course, resp.context['course'])

Upvotes: 1

Related Questions