Прошу помочь пройти ревью по тестированию
from http import HTTPStatus
from django.test import Client, TestCase
from django.urls import reverse
from ..models import Group, Post, User
STATUS_FOUND = HTTPStatus.FOUND
class URLTests(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.author = User.objects.create_user(username='test_user')
cls.no_author = User.objects.create_user(username='no_author')
cls.group = Group.objects.create(
title='Тестовый заголовок',
slug='test-slug',
description='Тестовый текст',
)
cls.post = Post.objects.create(
author=cls.author,
group=cls.group,
text='Тестовый заголовок',
pub_date='18.03.2022',
)
cls.authorized_client = Client()
cls.authorized_client.force_login(cls.author)
cls.authorized_client_1 = Client()
cls.authorized_client_1.force_login(cls.no_author)
def test_pages_exists_at_desired_location(self):
"""Страница доступна любому пользователю"""
pages_url = {
'/': HTTPStatus.OK,
f'/group/{self.group.slug}/': HTTPStatus.OK,
f'/profile/{self.author}/': HTTPStatus.OK,
f'/posts/{self.post.id}/': HTTPStatus.OK,
'/about/author/': HTTPStatus.OK,
'/about/tech/': HTTPStatus.OK,
}
for adress, http_status in pages_url.items():
with self.subTest(adress=adress):
response = Client().get(adress)
self.assertEqual(response.status_code, http_status)
def test_post_edit_url_redirect_anonymous(self):
"""Страница post_edit/ перенаправляет анонимного пользователя."""
response = Client().post(
"Ревьюер мне пишет: ""В self.client уже есть готовый клиент, который унаследован от класса TestCase" - я пробовал self.authorized_client в качестве замены - не подходит, тесты "падают".
reverse('posts:post_edit', kwargs={'post_id': '1'},)
"Ревьюер мне пишет, что в этом месте присутствует "хардкод". Не знаю как мне это исправить/оптимизировать.
)
self.assertRedirects(response, ('/auth/login/?next=/posts/1/edit/'))
self.assertEqual(response.status_code, STATUS_FOUND)
def test_urls_uses_correct_template(self):
"""URL-адрес использует соответствующий шаблон."""
templates_url_names = {
'posts/index.html': '',
'posts/create_change_post.html': '/create/',
'posts/post_detail.html': '/posts/1/',
'posts/group_list.html': '/group/test-slug/',
'posts/profile.html': '/profile/test_user/',
}
for template, url in templates_url_names.items():
with self.subTest(url=url):
response = self.authorized_client.get(url)
self.assertTemplateUsed(response, template)
def test_post_edit_url_exists_at_desired_location(self):
"""Страница posts/<post_id>/edit/ доступна автору поста."""
response = self.authorized_client.get('/posts/1/edit/')
self.assertEqual(response.status_code, HTTPStatus.OK)
def test_unknown_page_url_unexists_at_desired_location(self):
"""Страница не существует"""
response = Client().get('/none/')
self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
def test_no_author_of_post_cant_edit_post(self):
"""Страница posts/<post_id>/edit/ не доступна
авторизованному пользователю, но не автору поста"""
response = self.authorized_client_1.get('/posts/1/edit/')
self.assertRedirects(response, '/posts/1/')
self.assertEqual(response.status_code, STATUS_FOUND)
Вернуться на верх