Best Python code snippet using locust
test_views.py
Source:test_views.py
1import shutil2import tempfile3from django import forms4from django.conf import settings5from django.contrib.auth import get_user_model6from django.core.cache import cache7from django.core.files.uploadedfile import SimpleUploadedFile8from django.test import Client, TestCase, override_settings9from django.urls import reverse10from ..models import Follow, Group, Post11User = get_user_model()12@override_settings(MEDIA_ROOT=tempfile.mkdtemp())13class PostGroupPagesTests(TestCase):14 @classmethod15 def setUpClass(cls):16 super().setUpClass()17 cls.test_user = User.objects.create_user(username='AndreyG')18 cls.group = Group.objects.create(19 title='ÐоÑÑовÑй ÑекÑÑ',20 slug='some-slug',21 description='Ðакое-Ñо опиÑание'22 )23 small_gif = (24 b'\x47\x49\x46\x38\x39\x61\x02\x00'25 b'\x01\x00\x80\x00\x00\x00\x00\x00'26 b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00'27 b'\x00\x00\x00\x2C\x00\x00\x00\x00'28 b'\x02\x00\x01\x00\x00\x02\x02\x0C'29 b'\x0A\x00\x3B'30 )31 cls.uploaded = SimpleUploadedFile(32 name='small.gif',33 content=small_gif,34 content_type='image/gif'35 )36 cls.post = Post.objects.create(37 text='ТеÑÑовÑй ÑекÑÑ',38 author=cls.test_user,39 group=cls.group,40 image=cls.uploaded41 )42 cls.username = cls.post.author.username43 cls.post_id = cls.post.id44 @classmethod45 def tearDownClass(cls):46 shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True)47 super().tearDownClass()48 def setUp(self):49 self.guest_client = Client()50 self.user = PostGroupPagesTests.post.author51 self.authorized_client = Client()52 self.authorized_client.force_login(self.user)53 self.another_user = User.objects.create_user(username='DaBaby')54 self.another_authorized_client = Client()55 self.another_authorized_client.force_login(self.another_user)56 self.additional_user = User.objects.create_user(username='NaBaby')57 self.additional_client = Client()58 self.additional_client.force_login(self.additional_user)59 cache.clear()60 def _assert_post_fields(self, first_object):61 author = self.test_user62 text = self.post.text63 group = self.group64 image = self.post.image65 self.assertEqual(first_object.author, author)66 self.assertEqual(first_object.text, text)67 self.assertEqual(first_object.group, group)68 self.assertEqual(first_object.image, image)69 def test_pages_use_correct_template(self):70 """URL-адÑÐµÑ Ð¸ÑполÑзÑÐµÑ ÑооÑвеÑÑÑвÑÑÑий Ñаблон."""71 templates_pages_names = {72 'posts/index.html': reverse('index'),73 'posts/post_new_or_edit.html': reverse('new_post'),74 'posts/group.html': (75 reverse('group_posts', kwargs={'slug': 'some-slug'})76 ),77 }78 for template, reverse_name in templates_pages_names.items():79 with self.subTest(reverse_name=reverse_name):80 response = self.authorized_client.get(reverse_name)81 self.assertTemplateUsed(response, template)82 def test_new_post_page_shows_correct_context(self):83 """Шаблон new_post ÑÑоÑмиÑован Ñ Ð¿ÑавилÑнÑм конÑекÑÑом."""84 response = self.authorized_client.get(reverse('new_post'))85 form_fields = {86 'text': forms.fields.CharField,87 'group': forms.fields.ChoiceField,88 'image': forms.fields.ImageField,89 }90 for value, expected in form_fields.items():91 with self.subTest(value=value):92 form_field = response.context['form'].fields[value]93 self.assertIsInstance(form_field, expected)94 def test_index_page_shows_correct_context(self):95 """Шаблон index ÑÑоÑмиÑован Ñ Ð¿ÑавилÑнÑм конÑекÑÑом."""96 response = self.authorized_client.get(reverse('index'))97 first_object = response.context['page'][0]98 self._assert_post_fields(first_object)99 def test_profile_page_shows_correct_context(self):100 """Шаблон profile ÑÑоÑмиÑован Ñ Ð¿ÑавилÑнÑм конÑекÑÑом."""101 response = self.authorized_client.get(reverse('profile', kwargs={102 'username': PostGroupPagesTests.username,103 }))104 first_object = response.context['page'][0]105 self._assert_post_fields(first_object)106 def test_post_page_shows_correct_context(self):107 """Шаблон post ÑÑоÑмиÑован Ñ Ð¿ÑавилÑнÑм конÑекÑÑом."""108 response = self.authorized_client.get(reverse('post', kwargs={109 'username': PostGroupPagesTests.username,110 'post_id': PostGroupPagesTests.post_id,111 }))112 first_object = response.context['post']113 self._assert_post_fields(first_object)114 def test_post_edit_post_page_shows_correct_context(self):115 """Шаблон post_edit ÑÑоÑмиÑован Ñ Ð¿ÑавилÑнÑм конÑекÑÑом."""116 response = self.authorized_client.get(reverse('post_edit', kwargs={117 'username': PostGroupPagesTests.username,118 'post_id': PostGroupPagesTests.post_id,119 }))120 content = response.context['form'].instance121 form_fields = {122 'text': forms.fields.CharField,123 'group': forms.fields.ChoiceField,124 }125 for value, expected in form_fields.items():126 with self.subTest(value=value):127 form_field = response.context['form'].fields[value]128 self.assertIsInstance(form_field, expected)129 self.assertEqual(content.text, 'ТеÑÑовÑй ÑекÑÑ')130 self.assertEqual(content.author, PostGroupPagesTests.test_user)131 self.assertEqual(content.group, PostGroupPagesTests.group)132 def test_group_posts_page_shows_correct_context(self):133 """Шаблон group_posts ÑÑоÑмиÑован Ñ Ð¿ÑавилÑнÑм конÑекÑÑом."""134 response = self.authorized_client.get(135 reverse('group_posts', kwargs={'slug': 'some-slug'}))136 first_object = response.context['page'][0]137 self._assert_post_fields(first_object)138 def test_index_use_cache_appropriately(self):139 """СÑÑаниÑа index иÑполÑзÑÐµÑ ÐºÑÑ Ð¿ÑавилÑно."""140 initial_response = self.guest_client.get(reverse('index'))141 Post.objects.create(142 text='УÑловнÑй ÑекÑÑ',143 author=self.another_user144 )145 cached_response = self.guest_client.get(reverse('index'))146 cache.clear()147 non_cached_response = self.guest_client.get(reverse('index'))148 self.assertEqual(initial_response.content, cached_response.content)149 self.assertNotEqual(initial_response.content,150 non_cached_response.content)151class FollowViewsTest(TestCase):152 @classmethod153 def setUpClass(cls):154 super().setUpClass()155 cls.guest_client = Client()156 cls.test_user = User.objects.create_user(username='AndreyB')157 cls.authorized_client = Client()158 cls.authorized_client.force_login(cls.test_user)159 cls.another_user = User.objects.create_user(username='DaBaby')160 cls.another_authorized_client = Client()161 cls.another_authorized_client.force_login(cls.another_user)162 cls.additional_user = User.objects.create_user(username='NaBaby')163 cls.additional_client = Client()164 cls.additional_client.force_login(cls.additional_user)165 def test_follow_page_work_properly_for_subscribers(self):166 """ÐÐ¾Ð²Ð°Ñ Ð·Ð°Ð¿Ð¸ÑÑ Ð¿Ð¾Ð»ÑзоваÑÐµÐ»Ñ Ð¿Ð¾ÑвлÑеÑÑÑ Ð² ленÑе ÑеÑ
,167 кÑо на него подпиÑан."""168 Follow.objects.create(169 user=self.test_user,170 author=self.another_user171 )172 post = Post.objects.create(173 text='СпеÑиалÑнÑй ÑекÑÑ',174 author=self.another_user,175 )176 response = self.authorized_client.get(reverse("follow_index"))177 test_user_context = response.context['page'][0]178 self.assertEqual(test_user_context.author, post.author)179 def test_follow_page_work_properly_for_not_subscribers(self):180 """ÐÐ¾Ð²Ð°Ñ Ð·Ð°Ð¿Ð¸ÑÑ Ð¿Ð¾Ð»ÑзоваÑÐµÐ»Ñ Ð½Ðµ поÑвлÑеÑÑÑ Ð² ленÑе ÑеÑ
,181 кÑо не подпиÑан на него."""182 Post.objects.create(183 text='ÐÑобÑй ÑекÑÑ',184 author=self.additional_user,185 )186 response = self.authorized_client.get(reverse("follow_index"))187 test_user_context = response.context['page']188 self.assertEqual(len(test_user_context), 0)189 def test_authorized_can_follow(self):190 """ÐвÑоÑизиÑованнÑй полÑзоваÑÐµÐ»Ñ Ð¼Ð¾Ð¶ÐµÑ Ð¿Ð¾Ð´Ð¿Ð¸ÑÑваÑÑÑÑ."""191 self.authorized_client.get(reverse(192 "profile_follow",193 kwargs={'username': 'DaBaby'}194 ))195 existence = Follow.objects.filter(196 user=self.test_user,197 author=self.another_user198 ).exists()199 self.assertTrue(existence)200 def test_authorized_can_unfollow(self):201 """ÐвÑоÑизиÑованнÑй полÑзоваÑÐµÐ»Ñ Ð¼Ð¾Ð¶ÐµÑ Ð¾ÑпиÑÑваÑÑÑÑ."""202 Follow.objects.create(203 user=self.test_user,204 author=self.another_user205 )206 self.authorized_client.get(reverse(207 "profile_unfollow",208 kwargs={'username': 'DaBaby'}209 ))210 existence = Follow.objects.filter(211 user=self.test_user,212 author=self.another_user213 ).exists()214 self.assertFalse(existence)215class PaginatorViewsTest(TestCase):216 @classmethod217 def setUpClass(cls):218 super().setUpClass()219 cls.user = User.objects.create_user(username='AndreyG')220 Post.objects.bulk_create([221 Post(text=f'ТеÑÑовÑй ÑекÑÑ{i}', author=cls.user)222 for i in range(1, 14)223 ])224 def test_first_page_contains_ten_records(self):225 response = self.client.get(reverse('index'))226 self.assertEqual(len(response.context.get('page').object_list), 10)227 def test_second_page_contains_three_records(self):228 response = self.client.get(reverse('index') + '?page=2')...
test_meta.py
Source:test_meta.py
...4 """Test that a generated workspace exists when querying the API."""5 with conftest.login(managed_user, server):6 resp = server.get(f"/api/workspaces/{managed_workspace.name}/permissions")7 assert resp.status_code == 2008def test_user_context(managed_workspace, managed_user, server):9 """Test that the user context properly controls login."""10 with conftest.login(managed_user, server):11 resp = server.get(f"/api/workspaces/{managed_workspace.name}/tables")12 assert resp.status_code == 20013 resp = server.get(f"/api/workspaces/{managed_workspace.name}/tables")14 assert resp.status_code == 40115def test_populated_workspace(populated_workspace, managed_user, server):16 """Test that the populated workspace has a graph, an edge and node table."""17 workspace, graphs, *tables = populated_workspace18 with conftest.login(managed_user, server):19 # Graphs20 resp = server.get(f"/api/workspaces/{workspace.name}/graphs")21 assert resp.status_code == 20022 graphs = resp.json...
cory_testbench (2014_09_19 06_02_41 UTC).py
Source:cory_testbench (2014_09_19 06_02_41 UTC).py
...4import binascii5class Test_cory_testbench(unittest.TestCase):6 def setUp(self):7 self.app = current_app.test_client(True)8 def test_user_context(self):9 pw = SHA256.new('test' + binascii.hexlify(seed))10 assert user is not None11 assert user.username == 'Cory'12 assert user.password is not None13 assert user.seed is not None14if __name__ == '__main__':...
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!!