How to use test_user_context method in locust

Best Python code snippet using locust

test_views.py

Source:test_views.py Github

copy

Full Screen

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')...

Full Screen

Full Screen

test_meta.py

Source:test_meta.py Github

copy

Full Screen

...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...

Full Screen

Full Screen

cory_testbench (2014_09_19 06_02_41 UTC).py

Source:cory_testbench (2014_09_19 06_02_41 UTC).py Github

copy

Full Screen

...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__':...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run locust automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful