Skip to content

Commit

Permalink
Финальное задание
Browse files Browse the repository at this point in the history
  • Loading branch information
esaviv committed Jan 13, 2023
1 parent 6ab9967 commit 5525897
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 13 deletions.
31 changes: 25 additions & 6 deletions yatube/posts/tests/test_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class PostsURLTests(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user = User.objects.create_user(username="user")
cls.auth = User.objects.create_user(username="auth")
cls.group = Group.objects.create(
title='Тестовая группа',
Expand Down Expand Up @@ -56,15 +57,21 @@ def test_urls_post_create_edit_exists_at_desired_location_authorized(self):
responce = self.authorized_author.get(url)
self.assertEqual(responce.status_code, HTTPStatus.OK)

def test_urls_post_create_edit_redirect_anonymous_on_admin_login(self):
"""Страницы по адресу /create/, /posts/1/edit/
def test_urls_redirect_anonymous_on_admin_login(self):
"""Страницы по адресу /create/, /posts/1/edit/,
/follow/, /profile/auth/follow/, /profile/auth/unfollow/
перенаправят анонимного пользователя на страницу логина.
"""
login_first = "/auth/login/?next="
urls = {
"/create/": f"{login_first}/create/",
f"/posts/{self.post.pk}/edit/":
f"{login_first}/posts/{self.post.pk}/edit/"
f"{login_first}/posts/{self.post.pk}/edit/",
"/follow/": f"{login_first}/follow/",
f"/profile/{self.auth}/follow/":
f"{login_first}/profile/{self.auth}/follow/",
f"/profile/{self.auth}/unfollow/":
f"{login_first}/profile/{self.auth}/unfollow/"
}
for url, redirect_url in urls.items():
with self.subTest(url=url):
Expand All @@ -77,15 +84,26 @@ def test_url_post_edit_redirect_anonymous(self):
"""Страница по адресу /posts/1/edit/ перенаправят авторизированного
не автора на страницу с детальной информацией о посте.
"""
user = User.objects.create_user(username="user")
authorized_client = Client()
authorized_client.force_login(user)
authorized_client.force_login(self.user)

response = authorized_client.get(
f"/posts/{self.post.pk}/edit/",
follow=True)
self.assertRedirects(response, f"/posts/{self.post.pk}/")

def test_url_profile_follow_unfollow_redirect_to_follow_index(self):
urls = [
f"/profile/{self.user}/follow/",
f"/profile/{self.user}/unfollow/"
]
for url in urls:
with self.subTest(url=url):
response = self.authorized_author.get(
url,
follow=True)
self.assertRedirects(response, "/follow/")

def test_posts_urls_use_correct_template(self):
"""URL-адреса страниц, доступных аторизированному автору,
используют соответствующие шаблоны.
Expand All @@ -96,7 +114,8 @@ def test_posts_urls_use_correct_template(self):
f"/group/{self.group.slug}/": "posts/group_list.html",
f"/posts/{self.post.pk}/": "posts/post_detail.html",
"/create/": "posts/create_post.html",
f"/posts/{self.post.pk}/edit/": "posts/create_post.html"
f"/posts/{self.post.pk}/edit/": "posts/create_post.html",
"/follow/": "posts/follow.html"
}
for url, template in url_template_names.items():
with self.subTest(url=url):
Expand Down
41 changes: 34 additions & 7 deletions yatube/posts/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ class PostsPagesTests(TestCase):
def setUpClass(cls):
super().setUpClass()
cls.group = Group.objects.create(
title='Тестовая группа',
slug='test-slug',
description='Тестовое описание',
title="Тестовая группа",
slug="test-slug",
description="Тестовое описание",
)
cls.auth = User.objects.create_user(username="auth")
cls.user = User.objects.create_user(username="user")
small_gif = (
b'\x47\x49\x46\x38\x39\x61\x02\x00'
b'\x01\x00\x80\x00\x00\x00\x00\x00'
Expand All @@ -35,13 +36,13 @@ def setUpClass(cls):
b'\x0A\x00\x3B'
)
uploaded = SimpleUploadedFile(
name='small.gif',
name="small.gif",
content=small_gif,
content_type='image/gif'
content_type="image/gif"
)
cls.post = Post.objects.create(
author=cls.auth,
text='Тестовый пост',
text="Тестовый пост",
group=cls.group,
image=uploaded
)
Expand All @@ -55,6 +56,9 @@ def setUp(self):
self.authorized_author = Client()
self.authorized_author.force_login(self.auth)

self.authorized_client = Client()
self.authorized_client.force_login(self.user)

cache.clear()

def test_pages_uses_correct_template(self):
Expand All @@ -74,6 +78,7 @@ def test_pages_uses_correct_template(self):
reverse("posts:post_edit",
kwargs={"post_id": f"{self.post.pk}"}
): "posts/create_post.html",
reverse("posts:follow_index"): "posts/follow.html"
}
for reverse_name, template in templates_pages_names.items():
with self.subTest(reverse_name=reverse_name):
Expand Down Expand Up @@ -185,7 +190,8 @@ def test_post_detail_page_show_correct_context(self):

def test_post_create_edit_page_show_correct_context(self):
"""Шаблоны post_create сформирован с правильным контекстом
для создания и редоктирования поста."""
для создания и редоктирования поста.
"""
urls_parameters = {
"posts:post_create": ({}, False),
"posts:post_edit": ({"post_id": self.post.pk}, True)
Expand All @@ -200,6 +206,7 @@ def test_post_create_edit_page_show_correct_context(self):
self.assertEqual(is_edit, parameters[1])

def test_index_cache(self):
"""Проверка кеширования главной страницы."""
def get_page_obj(self):
responce = self.authorized_author.get(reverse("posts:index"))
return responce.content
Expand All @@ -217,3 +224,23 @@ def get_page_obj(self):
page_obj_after_clear_cache = get_page_obj(self)
self.assertNotEqual(page_obj_after_delete_posts,
page_obj_after_clear_cache)

def test_follow_index_page_show_correct_context_follow_unfollow(self):
"""Авторизованный пользователь может подписываться на других
пользователей и удалять их из подписок.
Запись пользователя появляется в ленте тех, кто на него подписан
и не появляется в ленте тех, кто не подписан.
"""
self.authorized_client.get(
reverse("posts:profile_follow", kwargs={"username": self.auth}))

response = self.authorized_client.get(reverse("posts:follow_index"))
posts = response.context["page_obj"]
self.assertEqual(len(posts), 1)
self.check_post(posts[0])

self.authorized_client.get(
reverse("posts:profile_unfollow", kwargs={"username": self.auth}))

response = self.authorized_client.get(reverse("posts:follow_index"))
self.assertEqual(len(response.context["page_obj"]), 0)

0 comments on commit 5525897

Please sign in to comment.