I'm testing my django project with a pytest. argument of type 'News' is not iterable

74 Views Asked by At

While testing content I got:

TypeError: argument of type 'News' is not iterable

There is two asserts in my test. I'm testing detail view of news page for anonymous user:

  1. checks if the news is in the response context of the page
  2. I check ordering by date of comments

The second part works correctly, but the first gives:

TypeError: list indices must be integers or slices, not News

Fixtures:

@pytest.fixture
def news():
    news = News.objects.create(
        title='Новость',
        text='Невероятное событие',
        date=datetime.today(),
    )
    return news


@pytest.fixture
def two_comments(author, news):
    now = timezone.now()
    list_of_comments = []
    for index in range(2):
        comment = Comment.objects.create(
            news=news,
            author=author,
            text=f'Tекст {index}',
        )
        comment.created = now + timedelta(days=index)
        comment.save()
        list_of_comments.append(comment)
    return list_of_comments

test code:

@pytest.mark.django_db
def test_comments_order(two_comments, news, client):
    detail_url = reverse('news:detail', args=(news.id,))
    response = client.get(detail_url)
    object_list = response.context['news']
    assert news in object_list
    news = response.context['news']
    print(news)
    list_comments = news.comment_set.all()
    assert list_comments[0]. created < list_comments[1].created

code of error:

@pytest.mark.django_db
    def test_comments_order(two_comments, news, client):
        detail_url = reverse('news:detail', args=(news.id,))
        response = client.get(detail_url)
>       assert news in response.context


self = [[{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at ...'object': <News: Новость>, 'news': <News: Новость>, 'view': <news.views.NewsDetail object at 0x000001CD39C53D30>}, {}]]
key = <News: Новость>

    def __getitem__(self, key):
        if isinstance(key, str):
            for subcontext in self:
                if key in subcontext:
                    return subcontext[key]
            raise KeyError(key)
        else:
>           return super().__getitem__(key)
E           TypeError: list indices must be integers or slices, not News

I had printed the value of news argument, and the response.context. the news object is included in the list of objects in the response. I don't understand why there is an error here, the news is in the context of the page.

0

There are 0 best solutions below