Best Python code snippet using SeleniumBase
test_views.py
Source:test_views.py
1# posts/tests/test_views.py2import shutil3import tempfile4from django.conf import settings5from django.core.files.uploadedfile import SimpleUploadedFile6import random7from django.contrib.auth import get_user_model8from django.test import Client, TestCase, override_settings9from django.urls import reverse10from posts.models import Follow, Post, Group, Comment11# ÐбÑее колиÑеÑÑво поÑÑов12POSTS_FOR_RANDOM = 2713# колиÑеÑÑво поÑÑов на ÑÑÑаниÑе14COUNT_PAGINATOR_ON_PAGE = 915# FIRST и SECOND не менÑÑÑ!16COUNT_FIRST_POST_TEST = 017COUNT_SECOND_POST_TEST = 018# Создаем вÑеменнÑÑ Ð¿Ð°Ð¿ÐºÑ Ð´Ð»Ñ Ð¼ÐµÐ´Ð¸Ð°-Ñайлов19# на Ð¼Ð¾Ð¼ÐµÐ½Ñ ÑеÑÑа медиа папка бÑÐ´ÐµÑ Ð¿ÐµÑеопÑеделена20TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)21SMALL_GIF = (22 b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04'23 b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02'24 b'\x02\x4c\x01\x00\x3b'25)26User = get_user_model()27# ÐÐ»Ñ ÑоÑ
ÑÐ°Ð½ÐµÐ½Ð¸Ñ media-Ñайлов в ÑеÑÑаÑ
бÑÐ´ÐµÑ Ð¸ÑполÑзоваÑÑÑÑ28# вÑÐµÐ¼ÐµÐ½Ð½Ð°Ñ Ð¿Ð°Ð¿ÐºÐ° TEMP_MEDIA_ROOT, а поÑом Ð¼Ñ ÐµÐµ Ñдалим29@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)30class TaskObjectPagesTests(TestCase):31 """32 ТеÑÑиÑÑем вÑводимÑе обÑекÑÑ Ð½Ð° ÑÑÑаниÑаÑ
33 """34 @classmethod35 def setUpClass(cls) -> None:36 super().setUpClass()37 # Ñоздаем запиÑÑ Ð² ÐРполÑзоваÑелÑ38 cls.auth_user = User.objects.create_user(39 username='test_user')40 # Ñоздадим запиÑÑ Ð² модели Group в ÐÐ Ð´Ð»Ñ Ð¿ÑÐ¾Ð²ÐµÐ´ÐµÐ½Ð¸Ñ ÑеÑÑов41 cls.group_for_test = Group.objects.create(42 title='ТеÑÑовÑй заголовок',43 description='ТеÑÑовÑй ÑекÑÑ',44 slug='test-slug'45 )46 uploaded = SimpleUploadedFile(47 name='small.gif',48 content=SMALL_GIF,49 content_type='image/gif'50 )51 # Ñоздадим поÑÑ Ð² модели Post Ð´Ð»Ñ Ð¿ÑÐ¾Ð²ÐµÐ´ÐµÐ½Ð¸Ñ ÑеÑÑов52 # 1 поÑÑ-без Group(slug-ÑÑбÑики)53 cls.post_one = Post.objects.create(54 text=('ÐодÑмайÑе пеÑед ÑоÑÑавлением '55 'ÑловаÑÑ Ñ Ñаблонами и адÑеÑамиии.'),56 author=cls.auth_user,57 image=uploaded58 )59 # 2 поÑÑ-Ñ Group(slug-ÑÑбÑикой)60 cls.post_two = Post.objects.create(61 text=('ÐодÑмайÑе поÑле ÑоÑÑавлением'62 ' ÑловаÑÑ. ÐÑо здоÑово!'),63 author=cls.auth_user,64 group=cls.group_for_test,65 image=uploaded66 )67 def setUp(self):68 # ÑоздаÑм 2 клиенÑов69 # пеÑвÑй-неавÑоÑизованнÑй. ÐÐ»Ñ Ð¿ÑовеÑки доÑÑÑпа Ñам,70 # где ÑÑебÑеÑÑÑ Ð°Ð²ÑоÑизаÑиÑ71 self.quest_client = Client()72 # вÑоÑой-пÑоÑÑо авÑоÑизованнÑй клиенÑ73 self.authorized_client_auth_user = Client()74 # ÐвÑоÑизовÑваем клиенÑов auth_user75 self.authorized_client_auth_user.force_login(self.auth_user)76 @classmethod77 def tearDownClass(cls):78 super().tearDownClass()79 # ÐодÑÐ»Ñ shutil - библиоÑека Python Ñ ÑдобнÑми инÑÑÑÑменÑами80 # Ð´Ð»Ñ ÑпÑÐ°Ð²Ð»ÐµÐ½Ð¸Ñ Ñайлами и диÑекÑоÑиÑми:81 # Ñоздание, Ñдаление, копиÑование, пеÑемеÑение, изменение папок82 # ÐеÑод shutil.rmtree ÑдалÑÐµÑ Ð´Ð¸ÑекÑоÑÐ¸Ñ Ð¸ вÑÑ ÐµÑ ÑодеÑжимое83 shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True) 84 def test_index_page_show_correct_context(self):85 """86 ТеÑÑиÑование пÑавилÑноÑÑи оÑобÑажаемого конÑенÑа на главной ÑÑÑаниÑе87 """88 response = self.authorized_client_auth_user.get(reverse('posts:index'))89 page_objects = response.context['page_obj'][0]90 # Ñоздадим ÑловаÑÑ Ñ ÐºÐ»ÑÑами, коÑоÑÑе в оÑÐ²ÐµÑ Ð½Ð° запÑÐ¾Ñ Ðº ÑÑÑаниÑе91 # в знаÑениÑÑ
клÑÑа - пÑавилÑное ÑеÑÑиÑÑемое знаÑение92 test_page_objects = {93 page_objects.text: self.post_two.text,94 page_objects.group: self.post_two.group,95 page_objects.author: self.post_two.author,96 page_objects.pub_date: self.post_two.pub_date,97 page_objects.image: self.post_two.image98 }99 # ÑÑавниваем Ñо знаÑениÑми 2-го поÑÑа, Ñ.к. он Ñоздан поÑледним в ÑеÑÑе100 # во view-ÑÑнкÑии Ñ Ð½Ð°Ñ ÑоÑÑиÑовка по ÑбÑÐ²Ð°Ð½Ð¸Ñ Ð¿Ð¾ даÑе101 for page_obj, correct_data in test_page_objects.items():102 with self.subTest(page_obj=page_obj):103 self.assertEqual(page_obj, correct_data)104 def test_page_with_detail_post_context(self):105 """106 ТеÑÑ Ð´Ð°Ð½Ð½ÑÑ
, коÑоÑÑе вÑÐ²Ð¾Ð´Ð¸Ñ ÑÑÑаниÑа пÑи ÑÑении конкÑеÑного поÑÑа107 """108 # СоÑÑиÑовка поÑÑов на ÑÑÑаниÑе вÑполнена по даÑе (Ð¾Ñ Ð½Ð¾Ð²ÑÑ
к ÑÑаÑÑм)109 post_id = self.post_two.pk110 response = self.quest_client.get(111 reverse('posts:post_detail', kwargs={112 'slug': self.group_for_test.slug,113 'post_id': post_id}))114 detail_post = response.context['page_obj'][0]115 self.assertEqual(detail_post.text, self.post_two.text)116 self.assertEqual(detail_post.author, self.auth_user)117 self.assertEqual(detail_post.group, self.group_for_test)118 self.assertEqual(detail_post.image, self.post_two.image)119 def test_group_page_show_correct_context(self):120 """121 ТеÑÑиÑование пÑавилÑноÑÑи оÑобÑажаемого конÑенÑа на ÑÑÑаниÑе ÑÑбÑики122 """123 response = self.authorized_client_auth_user.get(reverse(124 'posts:group_list',125 kwargs={126 'slug': self.group_for_test.slug})127 )128 page_objects = response.context['page_obj'][0]129 # Ñоздадим ÑловаÑÑ Ñ ÐºÐ»ÑÑами, коÑоÑÑе в оÑÐ²ÐµÑ Ð½Ð° запÑÐ¾Ñ Ðº ÑÑÑаниÑе130 # в знаÑениÑÑ
клÑÑа - пÑавилÑное ÑеÑÑиÑÑемое знаÑение131 test_page_objects = {132 page_objects.text: self.post_two.text,133 page_objects.group: self.post_two.group,134 page_objects.author: self.post_two.author,135 page_objects.pub_date: self.post_two.pub_date,136 page_objects.image: self.post_two.image137 }138 # ÑÑавниваем Ñо знаÑениÑми 2-го поÑÑа, Ñ.к. он Ñоздан поÑледним в ÑеÑÑе139 # во view-ÑÑнкÑии Ñ Ð½Ð°Ñ ÑоÑÑиÑовка по ÑбÑÐ²Ð°Ð½Ð¸Ñ Ð¿Ð¾ даÑе140 for page_obj, correct_data in test_page_objects.items():141 with self.subTest(page_obj=page_obj):142 self.assertEqual(page_obj, correct_data)143 def test_author_page_show_correct_context(self):144 """145 ТеÑÑиÑование пÑавилÑноÑÑи оÑобÑажаемого конÑенÑа146 на ÑÑÑаниÑе полÑзоваÑелÑ147 """148 response = self.authorized_client_auth_user.get(reverse(149 'posts:profile',150 kwargs={151 'username': self.auth_user.username})152 )153 page_objects = response.context['page_obj'][0]154 # Ñоздадим ÑловаÑÑ Ñ ÐºÐ»ÑÑами, коÑоÑÑе в оÑÐ²ÐµÑ Ð½Ð° запÑÐ¾Ñ Ðº ÑÑÑаниÑе155 # в знаÑениÑÑ
клÑÑа - пÑавилÑное ÑеÑÑиÑÑемое знаÑение156 test_page_objects = {157 page_objects.text: self.post_two.text,158 page_objects.group: self.post_two.group,159 page_objects.author: self.post_two.author,160 page_objects.pub_date: self.post_two.pub_date,161 page_objects.image: self.post_two.image162 }163 # ÑÑавниваем Ñо знаÑениÑми 2-го поÑÑа, Ñ.к. он Ñоздан поÑледним в ÑеÑÑе164 # во view-ÑÑнкÑии Ñ Ð½Ð°Ñ ÑоÑÑиÑовка по ÑбÑÐ²Ð°Ð½Ð¸Ñ Ð¿Ð¾ даÑе165 for page_obj, correct_data in test_page_objects.items():166 with self.subTest(page_obj=page_obj):167 self.assertEqual(page_obj, correct_data)168 def test_cach_on_index_page(self):169 """170 ÐÑовеÑÑем ÑабоÑÐ°ÐµÑ Ð»Ð¸ кеÑиÑование на главной ÑÑÑаниÑе171 """172 self.post_for_cach_test = Post.objects.create(173 text=('1111ÐодÑмайÑе пеÑед задолго до pÑоÑÑавлением '174 'ÑловаÑÑ Ñ Ñаблонами и адÑеÑамиии.'),175 author=self.auth_user,176 group=self.group_for_test,177 )178 post_created = Post.objects.filter(id=self.post_for_cach_test.pk)179 # делаем запÑÐ¾Ñ Ðº ÑÑÑаниÑе до ÑÐ´Ð°Ð»ÐµÐ½Ð¸Ñ Ð¿Ð¾ÑÑа Ñ ÐÐ180 response_before = self.quest_client.get(reverse('posts:index'))181 Post.objects.filter(id=self.post_for_cach_test.pk).delete()182 post_empty = Post.objects.filter(id=self.post_for_cach_test.pk)183 # делаем запÑÐ¾Ñ Ðº ÑÑÑаниÑе Ñже поÑле ÑÐ´Ð°Ð»ÐµÐ½Ð¸Ñ Ð¿Ð¾ÑÑа184 response_after = self.quest_client.get(reverse('posts:index'))185 self.assertTrue(response_before.content, response_after.content)186 self.assertFalse(post_created, post_empty)187class PaginatorObjectsViewsTest(TestCase):188 @classmethod189 def setUpClass(cls) -> None:190 super().setUpClass()191 # Ñоздаем запиÑÑ Ð² ÐРполÑзоваÑелÑ192 cls.auth_user = User.objects.create_user(193 username='test_user')194 cls.auth_user_second = User.objects.create_user(195 username='test_user_second')196 # Ñоздадим запиÑÑ Ð² модели Group в ÐÐ Ð´Ð»Ñ Ð¿ÑÐ¾Ð²ÐµÐ´ÐµÐ½Ð¸Ñ ÑеÑÑов197 cls.group_for_test = Group.objects.create(198 title='ТеÑÑовÑй заголовок',199 description='ТеÑÑовÑй ÑекÑÑ',200 slug='test-slug'201 )202 cls.group_for_test_second = Group.objects.create(203 title='ТеÑÑовÑй заголовок ÐÑоÑой',204 description='ТеÑÑовÑй ÑекÑÑ ÐÑоÑой',205 slug='test-slug-second'206 )207 # Ð Ñикле ÑоздаÑм нÑжное колиÑеÑÑво поÑÑов Ð´Ð»Ñ ÑеÑÑов пагинаÑии208 count_posts = POSTS_FOR_RANDOM209 global COUNT_FIRST_POST_TEST210 global COUNT_SECOND_POST_TEST211 while count_posts > 0:212 if count_posts % 2 == 0:213 name_post = 'post_' + str(count_posts)214 cls.name_post = Post.objects.create(215 text=(name_post + ' ') * 2,216 author=cls.auth_user,217 group=cls.group_for_test)218 COUNT_FIRST_POST_TEST += 1219 else:220 name_post_second = 'post_' + str(count_posts)221 cls.name_post_second = Post.objects.create(222 text=(name_post_second + ' ') * 2,223 author=cls.auth_user_second,224 group=cls.group_for_test_second)225 COUNT_SECOND_POST_TEST += 1226 count_posts -= 1227 # ÑоздаÑм 2 клиенÑов228 # пеÑвÑй-неавÑоÑизованнÑй. ÐÐ»Ñ Ð¿ÑовеÑки доÑÑÑпа Ñам,229 # где ÑÑебÑеÑÑÑ Ð°Ð²ÑоÑизаÑиÑ230 cls.quest_client = Client()231 # вÑоÑой-пÑоÑÑо авÑоÑизованнÑй клиенÑ232 cls.authorized_client_auth_user = Client()233 # ÐвÑоÑизовÑваем клиенÑов auth_user234 cls.authorized_client_auth_user.force_login(cls.auth_user)235 def test_index_page_contains_nine_records(self):236 """237 ТеÑÑиÑÑÐµÑ (паджинаÑоÑ) колиÑеÑÑво поÑÑов на ÑÑÑаниÑе Ñ ÑÑеÑом пагинаÑии238 """239 if POSTS_FOR_RANDOM < COUNT_PAGINATOR_ON_PAGE:240 posts_count = POSTS_FOR_RANDOM241 else:242 posts_count = COUNT_PAGINATOR_ON_PAGE243 response = self.authorized_client_auth_user.get(reverse('posts:index'))244 # ÐÑовеÑка: колиÑеÑÑво поÑÑов на пеÑвой ÑÑÑаниÑе Ñавно 9.245 # Такое колиÑеÑÑво задано во view ÑÑнкÑии246 self.assertEqual(len(response.context['page_obj']),247 posts_count)248 def test_last_page_contains_four_records(self):249 """250 ТеÑÑиÑÑÐµÑ (паджинаÑоÑ) колиÑеÑÑво поÑÑов на251 поÑледней ÑÑÑаниÑе ÐÑего поÑÑов 22252 """253 if POSTS_FOR_RANDOM > COUNT_PAGINATOR_ON_PAGE and (254 POSTS_FOR_RANDOM < COUNT_PAGINATOR_ON_PAGE*2):255 all_pages = 2256 posts_on_last_page = POSTS_FOR_RANDOM - (257 COUNT_PAGINATOR_ON_PAGE)258 elif POSTS_FOR_RANDOM <= COUNT_PAGINATOR_ON_PAGE:259 all_pages = 1260 posts_on_last_page = POSTS_FOR_RANDOM - (261 COUNT_PAGINATOR_ON_PAGE*0)262 else:263 all_pages = int(POSTS_FOR_RANDOM/COUNT_PAGINATOR_ON_PAGE)264 if (POSTS_FOR_RANDOM % COUNT_PAGINATOR_ON_PAGE) == 0:265 posts_on_last_page = COUNT_PAGINATOR_ON_PAGE266 else:267 posts_on_last_page = POSTS_FOR_RANDOM - (268 COUNT_PAGINATOR_ON_PAGE*all_pages)269 # ÐÑовеÑка: на ÑÑеÑÑей ÑÑÑаниÑе должно бÑÑÑ 4 поÑÑа.270 response = self.authorized_client_auth_user.get(271 reverse('posts:index') + f'?page={all_pages + 1}')272 self.assertEqual(len(response.context['page_obj']), posts_on_last_page)273 def test_posts_contains_filter_author(self):274 """275 ТеÑÑиÑÑÐµÑ Ð¾ÑÑилÑÑÑованнÑе поÑÑÑ Ð½Ð° ÑÑÑаниÑе Ð´Ð»Ñ Ð¾Ð¿ÑеделÑнного авÑоÑа276 """277 # Ðа ÑÑÑаниÑе 9 поÑÑов, Ñ ÑÑеÑом Ñого, ÑÑо в response['page_obj']278 # оÑÑÑÐµÑ Ð±ÑÐ´ÐµÑ Ñ 0, Ñо Ð´Ð»Ñ Ñандома ÑказÑваем на 1 единиÑÑ Ð¼ÐµÐ½ÑÑе279 if COUNT_SECOND_POST_TEST >= COUNT_PAGINATOR_ON_PAGE:280 count_posts_on_page_for_random = COUNT_PAGINATOR_ON_PAGE - 2281 else:282 count_posts_on_page_for_random = COUNT_PAGINATOR_ON_PAGE - 3283 response = self.authorized_client_auth_user.get(284 reverse('posts:profile', kwargs={285 'username': self.auth_user_second.username286 }))287 select_post_on_page = response.context['page_obj'][random.randint(288 1, count_posts_on_page_for_random)]289 # пÑовеÑка ÑлÑÑайно вÑбÑанного поÑÑа, ÑÑо авÑоÑом ÑвлÑеÑÑÑ290 # нÑжнÑй авÑоÑ291 self.assertEqual(select_post_on_page.author, self.auth_user_second)292 def test_first_page_contains_records_filter_author_post(self):293 """294 ТеÑÑиÑÑÐµÑ (паджинаÑоÑ) колиÑеÑÑво поÑÑов на ÑÑÑаниÑе Ñ295 ÑÑеÑом пагинаÑии и оÑÑилÑÑÑованнÑÑ
по полÑзоваÑелÑ296 """297 if COUNT_SECOND_POST_TEST <= COUNT_PAGINATOR_ON_PAGE:298 count_post = COUNT_SECOND_POST_TEST299 else:300 count_post = COUNT_PAGINATOR_ON_PAGE301 response = self.authorized_client_auth_user.get(302 reverse('posts:profile', kwargs={303 'username': self.auth_user_second.username304 }))305 # ÐÑовеÑка: колиÑеÑÑво поÑÑов на пеÑвой ÑÑÑаниÑе Ñавно 9.306 # Такое колиÑеÑÑво задано во view ÑÑнкÑии307 self.assertEqual(len(308 response.context['page_obj']), count_post)309 def test_last_page_contains_records_filter_author_post(self):310 """311 ТеÑÑиÑÑÐµÑ (паджинаÑоÑ) колиÑеÑÑво поÑÑов на поÑледней ÑÑÑаниÑе312 Ñ ÑÑеÑом пагинаÑии и оÑÑилÑÑÑованнÑÑ
по полÑзоваÑелÑ.313 Ðа поÑледней ÑÑÑаниÑе314 """315 if COUNT_SECOND_POST_TEST > COUNT_PAGINATOR_ON_PAGE and (316 COUNT_SECOND_POST_TEST < COUNT_PAGINATOR_ON_PAGE*2):317 all_pages = 2318 posts_on_last_page = COUNT_SECOND_POST_TEST - (319 COUNT_PAGINATOR_ON_PAGE)320 elif COUNT_SECOND_POST_TEST < COUNT_PAGINATOR_ON_PAGE:321 all_pages = 1322 posts_on_last_page = COUNT_SECOND_POST_TEST - (323 COUNT_PAGINATOR_ON_PAGE*0)324 else:325 all_pages = int(COUNT_SECOND_POST_TEST/COUNT_PAGINATOR_ON_PAGE)326 posts_on_last_page = COUNT_SECOND_POST_TEST - (327 COUNT_PAGINATOR_ON_PAGE*all_pages)328 if posts_on_last_page == 0:329 posts_on_last_page = 9330 response = self.authorized_client_auth_user.get(331 reverse('posts:profile', kwargs={332 'username': self.auth_user_second.username333 }) + f'?page={all_pages+1}')334 # ÐÑего поÑÑов ÑÑого авÑоÑа 11. Ðа пеÑвой ÑÑÑаниÑе - 9 поÑÑов335 # ,а на вÑоÑой - бÑÐ´ÐµÑ 2 поÑÑа336 self.assertEqual(len(337 response.context['page_obj']), posts_on_last_page)338 def test_posts_with_filter_group(self):339 """340 ТеÑÑиÑÑÐµÑ Ð¿Ð¾ÑÑ Ð½Ð° ÑÑÑаниÑе оÑÑилÑÑÑованнÑе по опÑеделенной341 ÑÑбÑике (group/slug) - дÑÑгой ÑÑбÑики бÑÑÑ Ð½Ðµ должно!342 """343 # Ðа ÑÑÑаниÑе 9 поÑÑов, Ñ ÑÑеÑом Ñого, ÑÑо в response['page_obj']344 # оÑÑÑÐµÑ Ð±ÑÐ´ÐµÑ Ñ 0, Ñо Ð´Ð»Ñ Ñандома ÑказÑваем на 1 единиÑÑ Ð¼ÐµÐ½ÑÑе345 if COUNT_SECOND_POST_TEST >= COUNT_PAGINATOR_ON_PAGE:346 count_posts_on_page_for_random = COUNT_PAGINATOR_ON_PAGE - 2347 else:348 count_posts_on_page_for_random = COUNT_PAGINATOR_ON_PAGE - 3349 response = self.authorized_client_auth_user.get(350 reverse('posts:group_list', kwargs={351 'slug': self.group_for_test_second.slug}))352 select_post_on_page = response.context['page_obj'][random.randint(353 1, count_posts_on_page_for_random)]354 # пÑовеÑка гÑÑÐ¿Ð¿Ñ Ñ ÑлÑÑайно вÑбÑанного поÑÑа355 # <Group: ТеÑÑовÑй заголовок ÐÑоÑой>356 self.assertEqual(select_post_on_page.group,357 self.group_for_test_second)358 def test_first_page_contains_nine_records_filter_group_post(self):359 """360 ТеÑÑиÑÑÐµÑ (паджинаÑоÑ) на наÑалÑной ÑÑÑаниÑе вÑбÑонной гÑÑÐ¿Ð¿Ñ (ÑÑбÑики)361 """362 if COUNT_SECOND_POST_TEST < COUNT_PAGINATOR_ON_PAGE:363 count_posts_on_page = COUNT_SECOND_POST_TEST364 else:365 count_posts_on_page = COUNT_PAGINATOR_ON_PAGE366 # slug=test-slug-second - url вÑоÑой'367 response = self.quest_client.get(368 reverse('posts:group_list', kwargs={369 'slug': self.group_for_test_second.slug}))370 self.assertEqual(len(response.context['page_obj']),371 count_posts_on_page)372 def test_last_page_contains_records_filter_group_post(self):373 """374 ТеÑÑиÑÑÐµÑ (паджинаÑоÑ) на поÑледней ÑÑÑаниÑе вÑбÑонной гÑÑÐ¿Ð¿Ñ (ÑÑбÑики)375 """376 if COUNT_SECOND_POST_TEST > COUNT_PAGINATOR_ON_PAGE and (377 COUNT_SECOND_POST_TEST < COUNT_PAGINATOR_ON_PAGE*2):378 all_pages = 2379 posts_on_last_page = COUNT_SECOND_POST_TEST - (380 COUNT_PAGINATOR_ON_PAGE)381 elif COUNT_SECOND_POST_TEST < COUNT_PAGINATOR_ON_PAGE:382 all_pages = 1383 posts_on_last_page = COUNT_SECOND_POST_TEST - (384 COUNT_PAGINATOR_ON_PAGE*0)385 else:386 all_pages = int(COUNT_SECOND_POST_TEST/COUNT_PAGINATOR_ON_PAGE)387 posts_on_last_page = COUNT_SECOND_POST_TEST - (388 COUNT_PAGINATOR_ON_PAGE*all_pages)389 if posts_on_last_page == 0:390 posts_on_last_page = 9391 # slug='test-slug-second'392 response = self.quest_client.get(393 reverse('posts:group_list', kwargs={394 'slug': self.group_for_test_second.slug}395 ) + f'?page={all_pages+1}')396 self.assertEqual(len(response.context['page_obj']),397 posts_on_last_page)398class CommentsViewsTest(TestCase):399 """400 ÐÑовеÑÑем, ÑÑо:401 ---------------402 - ÐомменÑиÑоваÑÑ Ð¿Ð¾ÑÑÑ Ð¼Ð¾Ð¶ÐµÑ ÑолÑко авÑоÑизованнÑй полÑзоваÑелÑ;403 - ÐоÑле ÑÑпеÑной оÑпÑавки комменÑаÑий поÑвлÑеÑÑÑ Ð½Ð° ÑÑÑаниÑе поÑÑа.404 """405 @classmethod406 def setUpClass(cls):407 super().setUpClass()408 uploaded = SimpleUploadedFile(409 name='small.gif',410 content=SMALL_GIF,411 content_type='image/gif'412 )413 cls.user = User.objects.create(414 username='test-user'415 )416 cls.group = Group.objects.create(417 title='ТеÑÑовÑй заголовок',418 description='ТеÑÑовÑй ÑекÑÑ',419 slug='test-slug'420 )421 cls.post_one = Post.objects.create(422 text=('Рбазе даннÑÑ
пÑоекÑа Yatube Ñже Ñ
ÑаниÑÑÑ Ð¸Ð½ÑоÑмаÑиÑ'423 'об авÑоÑаÑ
и иÑ
поÑÑаÑ
. Ðадим полÑзоваÑелÑм '424 'возможноÑÑÑ ÐºÐ¾Ð¼Ð¼ÐµÐ½ÑиÑоваÑÑ Ð·Ð°Ð¿Ð¸Ñи дÑÑг дÑÑга.'),425 author=cls.user,426 group=cls.group,427 image=uploaded428 )429 cls.quest_user = Client()430 cls.auth_user = Client()431 cls.auth_user.force_login(cls.user)432 def test_create_comment_only_auth_user(self):433 """434 ТеÑÑиÑование комменÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ Ð¿Ð¾ÑÑа - ÑолÑко авÑоÑизованнÑе435 """436 comments_count_first = Comment.objects.count()437 text_comment = {438 'text': 'ÐеÑвÑй комменÑаÑий, к ÑÑÐ¾Ð¼Ñ ÑÑдеÑÐ½Ð¾Ð¼Ñ ÑеÑÑÑ',439 'post': self.post_one,440 'author': self.user}441 response = self.auth_user.post(reverse(442 'posts:add_comment',443 kwargs={'post_id': self.post_one.pk}),444 data=text_comment,445 follow=True)446 comments_count_second = Comment.objects.count()447 self.assertTrue(comments_count_second, (comments_count_first+1))448 self.assertRedirects(response, reverse(449 'posts:post_detail',450 kwargs={451 'slug': self.group.slug,452 'post_id': self.post_one.pk453 }))454 def test_comment_on_page(self):455 self.comment_on_page = Comment.objects.create(456 text='ÐеÑвÑй комменÑаÑий, к ÑÑÐ¾Ð¼Ñ ÑÑдеÑÐ½Ð¾Ð¼Ñ ÑеÑÑÑ',457 post=self.post_one,458 author=self.user459 )460 response = self.quest_user.get(reverse(461 'posts:post_detail',462 kwargs={463 'slug': self.group.slug,464 'post_id': self.post_one.pk465 }))466 page_objects = response.context['page_obj'][0]467 self.assertTrue(page_objects.comments, self.comment_on_page.text)468class FollowingViewsTest(TestCase):469 """470 ÐÑовеÑÑем, ÑÑо:471 ---------------472 - ÐвÑоÑизованнÑй полÑзоваÑÐµÐ»Ñ Ð¼Ð¾Ð¶ÐµÑ Ð¿Ð¾Ð´Ð¿Ð¸ÑÑваÑÑÑÑ Ð½Ð° дÑÑгиÑ
473 полÑзоваÑелей и ÑдалÑÑÑ Ð¸Ñ
из подпиÑок.474 - ÐÐ¾Ð²Ð°Ñ Ð·Ð°Ð¿Ð¸ÑÑ Ð¿Ð¾Ð»ÑзоваÑÐµÐ»Ñ Ð¿Ð¾ÑвлÑеÑÑÑ Ð² ленÑе ÑеÑ
, кÑо на него475 подпиÑан.476 """477 @classmethod478 def setUpClass(cls) -> None:479 super().setUpClass()480 cls.user_1 = User.objects.create(481 username='test-user'482 )483 cls.user_2 = User.objects.create(484 username='test-user-2'485 )486 cls.user_3 = User.objects.create(487 username='test-user-3'488 )489 cls.group = Group.objects.create(490 title='ТеÑÑовÑй заголовок',491 description='ТеÑÑовÑй ÑекÑÑ',492 slug='test-slug'493 )494 cls.post_one = Post.objects.create(495 text=('Yatube Ñже Ñ
ÑаниÑÑÑ Ð¸Ð½ÑоÑмаÑиÑ'496 'об авÑоÑаÑ
и иÑ
поÑÑаÑ
. Ðадим полÑзоваÑелÑм '497 'возможноÑÑÑ ÐºÐ¾Ð¼Ð¼ÐµÐ½ÑиÑоваÑÑ Ð·Ð°Ð¿Ð¸Ñи дÑÑг дÑÑга.'),498 author=cls.user_1,499 group=cls.group500 )501 cls.post_two = Post.objects.create(502 text=('базе даннÑÑ
пÑоекÑа Yatube Ñже Ñ
ÑаниÑÑÑ Ð¸Ð½ÑоÑмаÑиÑ'503 'об авÑоÑаÑ
и иÑ
поÑÑаÑ
. Ðадим полÑзоваÑелÑм '504 'возможноÑÑÑ Ð´ÑÑга.'),505 author=cls.user_2,506 group=cls.group507 )508 cls.post_three = Post.objects.create(509 text=('даннÑÑ
пÑоекÑа Ñ
ÑаниÑÑÑ Ð¸Ð½ÑоÑмаÑиÑ'510 'об авÑоÑаÑ
и иÑ
поÑÑаÑ
. Ðадим полÑзоваÑелÑм '511 'возможноÑÑÑ ÐºÐ¾Ð¼Ð¼ÐµÐ½ÑиÑоваÑÑ Ð·Ð°Ð¿Ð¸Ñи дÑÑг дÑÑга.'),512 author=cls.user_3,513 group=cls.group514 )515 cls.auth_user_one = Client()516 cls.auth_user_one.force_login(cls.user_1)517 cls.auth_user_two = Client()518 cls.auth_user_two.force_login(cls.user_2)519 cls.client_user_three = Client()520 def test_follow_other_author(self):521 """522 ТеÑÑиÑÑем подпиÑÐºÑ "user_1" на "user_3"523 """524 # бÑÐ´ÐµÑ False525 is_follow_firsttime = Follow.objects.filter(526 author=self.user_3, user=self.user_1).exists()527 response = self.auth_user_one.get(528 reverse('posts:profile_follow',529 kwargs={530 'username': self.user_3.username,531 }))532 # бÑÐ´ÐµÑ True533 is_follow_secondtime = Follow.objects.filter(534 author=self.user_3, user=self.user_1).exists()535 self.assertRedirects(response, reverse('posts:profile',536 kwargs={'username': self.user_3.username, }))537 self.assertEqual(is_follow_firsttime, False)538 self.assertEqual(is_follow_secondtime, True)539 def test_unfollow_other_author(self):540 """541 ТеÑÑиÑÑем Ñдаление из подпиÑок ("user_1" ÑдалÑÐµÑ Ð¿Ð¾Ð´Ð¿Ð¸ÑÐºÑ Ð½Ð° "user_3")542 """543 pass544 self.start_following = Follow.objects.create(545 author=self.user_3, user=self.user_1)546 # "is_follow_firsttime" должна бÑÑÑ True547 is_follow_firsttime = Follow.objects.filter(548 author=self.user_3, user=self.user_1).exists()549 response = self.auth_user_one.get(550 reverse('posts:profile_unfollow',551 kwargs={552 'username': self.user_3.username,553 }))554 # бÑÐ´ÐµÑ False555 is_follow_secondtime = Follow.objects.filter(556 author=self.user_3, user=self.user_1).exists()557 self.assertRedirects(response, reverse('posts:profile',558 kwargs={'username': self.user_3.username, }))559 self.assertEqual(is_follow_firsttime, True)560 self.assertEqual(is_follow_secondtime, False)561 def test_posts_on_follow_user(self):562 """563 ТеÑÑиÑÑем видимоÑÑÑ Ð¿Ð¾ÑÑов в ленÑе подпиÑÑика (Ñ "user_1" в ленÑе564 Ð´Ð¾Ð»Ð¶Ð½Ñ Ð¿Ð¾ÑвиÑÑÑÑ Ð¿Ð¾ÑÑÑ "user_3")565 """566 self.start_following = Follow.objects.create(567 author=self.user_3, user=self.user_1)568 response = self.auth_user_one.get(569 reverse('posts:follow_index'))570 # беÑÑм ÑекÑÑ Ð¿ÐµÑвого поÑÑа, авÑоÑа, на коÑоÑого подпиÑалиÑÑ571 text_post_user_3 = response.context['page_obj'][0].text572 author_post_user_3 = response.context['page_obj'][0].author573 # и ÑÑавниваем Ñ ÑекÑÑом авÑоÑа "user_3"574 self.assertEqual(text_post_user_3, self.post_three.text)...
test_page_objects.py
Source:test_page_objects.py
...19 sb.click('[for="__search"] svg')20 sb.type('form[name="search"] input', search_term)21 sb.click("li.md-search-result__item h1:contains(%s)" % search_term)22class MyTests(BaseCase):23 def test_page_objects(self):24 search_term = "SeleniumBase GitHub"25 expected_text = "seleniumbase/SeleniumBase"26 GooglePage().go_to_google(self)27 GooglePage().do_search(self, search_term)28 self.assert_text(expected_text, "#search")29 GooglePage().click_search_result(self, expected_text)30 SeleniumBaseGitHubPage().click_seleniumbase_io_link(self)31 SeleniumBaseIOPage().do_search_and_click(self, "Dashboard")...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!