Best Python code snippet using playwright-python
testcases.py
Source:testcases.py
...21 # Test the pagination22 self.assertContains(page, 'Page 1 of 2')23class ResponseObjectMixin:24 url_name = None25 def _test_success_response(self):26 response = self.response27 self.assertEqual(response.status_code, http_client.FOUND)28 self.assertRedirectsTo(response, self.success_url_name)29 messages = list(response.follow().context['messages'])30 self.assertEqual(len(messages), 1)31 self.assertEqual(messages[0].level, INFO)32 self.assertEqual(messages[0].message, self.success_message)33 def _get_url(self):34 raise NotImplementedError35class PopUpWindowMixin:36 is_popup_testcase = None37 @property38 def is_popup(self):39 return RelatedFieldWidgetWrapper.IS_POPUP_VALUE40 @property41 def is_popup_var(self):42 return RelatedFieldWidgetWrapper.IS_POPUP_VAR43 @property44 def to_field(self):45 return self.model._meta.pk.name46 @property47 def to_field_var(self):48 return RelatedFieldWidgetWrapper.TO_FIELD_VAR49 def _test_popup_window_success_response(self):50 response = self.response51 self.assertEqual(response.status_code, http_client.OK)52 self.assertTemplateUsed(response, 'oscar/dashboard/widgets/popup_response.html')53 self.assertInContext(response, 'popup_response_data')54 self.popup_response_data = json.loads(response.context['popup_response_data'])55 def _test_display_regular_window_response(self):56 response = self.response57 self.assertTrue('is_popup' not in response.context)58 self.assertTrue('is_popup_var' not in response.context)59 def _get_popup_params(self):60 return {61 self.is_popup_var: self.is_popup,62 }63 def _get_popup_url(self, url):64 querystring = urlencode(self._get_popup_params())65 return '%s?%s' % (url, querystring)66class PopUpWindowCreateUpdateMixin(PopUpWindowMixin):67 def _test_display_regular_window_response(self):68 super()._test_display_regular_window_response()69 response = self.response70 self.assertTrue('to_field' not in response.context)71 self.assertTrue('to_field_var' not in response.context)72 def _test_display_popup_window_response(self):73 response = self.response74 self.assertInContext(response, 'to_field')75 self.assertEqual(response.context['to_field'], self.to_field)76 self.assertInContext(response, 'is_popup')77 self.assertEqual(response.context['is_popup'], self.is_popup)78 self.assertInContext(response, 'to_field_var')79 self.assertEqual(response.context['to_field_var'], self.to_field_var)80 self.assertInContext(response, 'is_popup_var')81 self.assertEqual(response.context['is_popup_var'], self.is_popup_var)82 def _get_popup_params(self):83 params = super()._get_popup_params()84 params.update({self.to_field_var: self.to_field})85 return params86class ObjectCreateMixin(ResponseObjectMixin):87 model = None88 form = None89 page_title = None90 url_name = None91 template_name = None92 success_message = None93 success_url_name = None94 create_check_attr = None95 object_check_str = None96 def _get_url(self):97 return reverse(self.url_name)98 def _test_display_create_form_response(self):99 response = self.response100 self.assertEqual(response.status_code, http_client.OK)101 self.assertTemplateUsed(response, self.template_name)102 self.assertInContext(response, 'form')103 self.assertIsInstance(response.context['form'], self.form)104 self.assertTrue(response.context['form'].instance._state.adding)105 self.assertInContext(response, 'title')106 self.assertEqual(response.context['title'], self.page_title)107 def test_display_create_form(self):108 self.response = self.get(reverse(self.url_name))109 # Test the response110 self._test_display_create_form_response()111 def _test_creation_of_objects(self):112 # Test the creation of an object113 self.assertEqual(1, self.model.objects.all().count())114 self.obj = self.model.objects.first()115 self.assertEqual(116 getattr(self.obj, self.create_check_attr), self.object_check_str)117 def _get_create_obj_response(self):118 raise NotImplementedError119 def test_create_object(self):120 self.response = self._get_create_obj_response()121 # Test the creation of an object122 self._test_creation_of_objects()123 # Test the response124 self._test_success_response()125class PopUpObjectCreateMixin(PopUpWindowCreateUpdateMixin, ObjectCreateMixin):126 def _get_url(self):127 url = super()._get_url()128 if self.is_popup_testcase:129 return self._get_popup_url(url)130 return url131 def test_display_create_form(self):132 super().test_display_create_form()133 self._test_display_regular_window_response()134 def test_display_create_popup_form(self):135 self.is_popup_testcase = True136 self.url = self._get_url()137 self.response = self.get(self._get_url())138 # Test the response139 self._test_display_create_form_response()140 self._test_display_popup_window_response()141 def test_create_popup_object(self):142 self.is_popup_testcase = True143 self.response = self._get_create_obj_response()144 # Test the creation of an object145 self._test_creation_of_objects()146 # Test the response147 self._test_create_popup_success_response()148 def _test_create_popup_success_response(self):149 self._test_popup_window_success_response()150 popup_response_data = self.popup_response_data151 self.assertTrue('value' in popup_response_data)152 self.assertTrue('obj' in popup_response_data)153 self.assertFalse('action' in popup_response_data)154 response = self.response155 messages = list(response.context['messages'])156 self.assertEqual(len(messages), 0)157class ObjectUpdateMixin(ResponseObjectMixin):158 model = None159 form = None160 page_title = None161 url_name = None162 template_name = None163 success_message = None164 success_url_name = None165 create_check_attr = None166 object_check_str = None167 def _get_url(self):168 return reverse(self.url_name, kwargs={'pk': self.obj.pk})169 def _get_page_title(self):170 raise NotImplementedError171 def _create_object_factory(self):172 raise NotImplementedError173 def setUp(self):174 super().setUp()175 self.obj = self._create_object_factory()176 def _test_display_update_form_response(self):177 response = self.response178 self.assertEqual(response.status_code, http_client.OK)179 self.assertTemplateUsed(response, self.template_name)180 self.assertInContext(response, 'form')181 self.assertIsInstance(response.context['form'], self.form)182 self.assertEqual(response.context['form'].instance, self.obj)183 self.assertInContext(response, 'title')184 self.assertEqual(response.context['title'], self._get_page_title())185 def test_display_update_form(self):186 self.response = self.get(self._get_url())187 # Test the response188 self._test_display_update_form_response()189 def _test_update_of_objects(self):190 # Test the update of an object191 self.obj = self.model.objects.first()192 self.assertEqual(193 getattr(self.obj, self.create_check_attr), self.object_check_str)194 def _get_update_obj_response(self):195 raise NotImplementedError196 def test_update_object(self):197 self.response = self._get_update_obj_response()198 # Test the update of an object199 self._test_update_of_objects()200 # Test the response201 self._test_success_response()202class PopUpObjectUpdateMixin(PopUpWindowCreateUpdateMixin, ObjectUpdateMixin):203 def _get_url(self):204 url = super()._get_url()205 if self.is_popup_testcase:206 return self._get_popup_url(url)207 return url208 def test_display_update_form(self):209 super().test_display_update_form()210 self._test_display_regular_window_response()211 def test_display_update_popup_form(self):212 self.is_popup_testcase = True213 self.url = self._get_url()214 self.response = self.get(self._get_url())215 # Test the response216 self._test_display_update_form_response()217 self._test_display_popup_window_response()218 def test_update_popup_object(self):219 self.is_popup_testcase = True220 self.response = self._get_update_obj_response()221 # Test the creation of an object222 self._test_update_of_objects()223 # Test the response224 self._test_update_popup_success_response()225 def _test_update_popup_success_response(self):226 self._test_popup_window_success_response()227 popup_response_data = self.popup_response_data228 self.assertTrue('action' in popup_response_data)229 self.assertEqual(popup_response_data['action'], 'change')230 self.assertTrue('value' in popup_response_data)231 self.assertTrue('obj' in popup_response_data)232 self.assertTrue('new_value' in popup_response_data)233 response = self.response234 messages = list(response.context['messages'])235 self.assertEqual(len(messages), 0)236class ObjectDeleteMixin(ResponseObjectMixin):237 model = None238 page_title = None239 url_name = None240 template_name = None241 success_message = None242 success_url_name = None243 delete_dissalowed_possible = None244 def _get_url(self):245 return reverse(self.url_name, kwargs={'pk': self.obj.pk})246 def _get_page_title(self):247 raise NotImplementedError248 def _create_object_factory(self):249 raise NotImplementedError250 def setUp(self):251 super().setUp()252 self.obj = self._create_object_factory()253 def _test_display_delete_form_response(self):254 response = self.response255 self.assertEqual(response.status_code, http_client.OK)256 self.assertTemplateUsed(response, self.template_name)257 self.assertInContext(response, 'title')258 self.assertEqual(response.context['title'], self._get_page_title())259 def test_display_delete_form(self):260 self.response = self.get(self._get_url())261 # Test the response262 self._test_display_delete_form_response()263 def test_delete_object(self):264 self.response = self._get_delete_obj_response()265 # Test the deletion of an object266 self._test_deletion_of_objects()267 # Test the response268 self._test_success_response()269 def _get_delete_obj_response(self):270 raise NotImplementedError271 def _test_deletion_of_objects(self):272 # Test the deletion of an object273 obj_exists = self.model.objects.exists()274 self.assertFalse(obj_exists)275 def test_display_disallowed_delete(self):276 if self.delete_dissalowed_possible:277 self.is_disallowed_test = True278 self._create_dissalowed_object_factory()279 self.response = self.get(self._get_url())280 # Test the response281 self._test_display_delete_disallowed_response()282 def _create_dissalowed_object_factory(self):283 raise NotImplementedError284 def _test_display_delete_disallowed_response(self):285 response = self.response286 self.assertInContext(response, 'disallow')287 self.assertTrue(response.context['disallow'])288class PopUpObjectDeleteMixin(PopUpWindowMixin, ObjectDeleteMixin):289 def _get_url(self):290 url = super()._get_url()291 if self.is_popup_testcase:292 return self._get_popup_url(url)293 return url294 def test_display_delete_form(self):295 super().test_display_delete_form()296 self._test_display_regular_window_response()297 def test_display_delete_popup_form(self):298 self.is_popup_testcase = True299 self.url = self._get_url()300 self.response = self.get(self._get_url())301 # Test the response302 self._test_display_delete_form_response()303 self._test_display_popup_delete_response()304 def _test_display_popup_delete_response(self):305 response = self.response306 self.assertInContext(response, 'is_popup')307 self.assertEqual(response.context['is_popup'], self.is_popup)308 self.assertInContext(response, 'is_popup_var')309 self.assertEqual(response.context['is_popup_var'], self.is_popup_var)310 def test_delete_popup_object(self):311 self.is_popup_testcase = True312 self.response = self._get_delete_obj_response()313 # Test the deletion of an object314 self._test_deletion_of_objects()315 # Test the response316 self._test_delete_popup_success_response()317 def _test_delete_popup_success_response(self):318 self._test_popup_window_success_response()319 popup_response_data = self.popup_response_data320 self.assertTrue('action' in popup_response_data)321 self.assertEqual(popup_response_data['action'], 'delete')322 self.assertTrue('value' in popup_response_data)323 response = self.response324 messages = list(response.context['messages'])325 self.assertEqual(len(messages), 0)326 def test_display_disallowed_delete(self):327 super().test_display_disallowed_delete()328 self._test_display_regular_window_response()329 def test_display_disallowed_popup_delete(self):330 if self.delete_dissalowed_possible:331 self.is_popup_testcase = True332 self.is_disallowed_test = True333 self._create_dissalowed_object_factory()334 self.response = self.get(self._get_url())335 # Test the response336 self._test_display_popup_delete_response()...
base.py
Source:base.py
...24 self._view_middleware = []25 self._template_response_middleware = []26 self._exception_middleware = []27 get_response = self._get_response_async if is_async else self._get_response28 handler = convert_exception_to_response(get_response)29 handler_is_async = is_async30 for middleware_path in reversed(settings.MIDDLEWARE):31 middleware = import_string(middleware_path)32 middleware_can_sync = getattr(middleware, 'sync_capable', True)33 middleware_can_async = getattr(middleware, 'async_capable', False)34 if not middleware_can_sync and not middleware_can_async:35 raise RuntimeError(36 'Middleware %s must have at least one of '37 'sync_capable/async_capable set to True.' % middleware_path38 )39 elif not handler_is_async and middleware_can_sync:40 middleware_is_async = False41 else:42 middleware_is_async = middleware_can_async43 try:44 # Adapt handler, if needed.45 adapted_handler = self.adapt_method_mode(46 middleware_is_async, handler, handler_is_async,47 debug=settings.DEBUG, name='middleware %s' % middleware_path,48 )49 mw_instance = middleware(adapted_handler)50 except MiddlewareNotUsed as exc:51 if settings.DEBUG:52 if str(exc):53 logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc)54 else:55 logger.debug('MiddlewareNotUsed: %r', middleware_path)56 continue57 else:58 handler = adapted_handler59 if mw_instance is None:60 raise ImproperlyConfigured(61 'Middleware factory %s returned None.' % middleware_path62 )63 if hasattr(mw_instance, 'process_view'):64 self._view_middleware.insert(65 0,66 self.adapt_method_mode(is_async, mw_instance.process_view),67 )68 if hasattr(mw_instance, 'process_template_response'):69 self._template_response_middleware.append(70 self.adapt_method_mode(is_async, mw_instance.process_template_response),71 )72 if hasattr(mw_instance, 'process_exception'):73 # The exception-handling stack is still always synchronous for74 # now, so adapt that way.75 self._exception_middleware.append(76 self.adapt_method_mode(False, mw_instance.process_exception),77 )78 handler = convert_exception_to_response(mw_instance)79 handler_is_async = middleware_is_async80 # Adapt the top of the stack, if needed.81 handler = self.adapt_method_mode(is_async, handler, handler_is_async)82 # We only assign to this when initialization is complete as it is used83 # as a flag for initialization being complete.84 self._middleware_chain = handler85 def adapt_method_mode(86 self, is_async, method, method_is_async=None, debug=False, name=None,87 ):88 """89 Adapt a method to be in the correct "mode":90 - If is_async is False:91 - Synchronous methods are left alone92 - Asynchronous methods are wrapped with async_to_sync93 - If is_async is True:94 - Synchronous methods are wrapped with sync_to_async()95 - Asynchronous methods are left alone96 """97 if method_is_async is None:98 method_is_async = asyncio.iscoroutinefunction(method)99 if debug and not name:100 name = name or 'method %s()' % method.__qualname__101 if is_async:102 if not method_is_async:103 if debug:104 logger.debug('Synchronous %s adapted.', name)105 return sync_to_async(method, thread_sensitive=True)106 elif method_is_async:107 if debug:108 logger.debug('Asynchronous %s adapted.', name)109 return async_to_sync(method)110 return method111 def get_response(self, request):112 """Return an HttpResponse object for the given HttpRequest."""113 # Setup default url resolver for this thread114 set_urlconf(settings.ROOT_URLCONF)115 response = self._middleware_chain(request)116 response._resource_closers.append(request.close)117 if response.status_code >= 400:118 log_response(119 '%s: %s', response.reason_phrase, request.path,120 response=response,121 request=request,122 )123 return response124 async def get_response_async(self, request):125 """126 Asynchronous version of get_response.127 Funneling everything, including WSGI, into a single async128 get_response() is too slow. Avoid the context switch by using129 a separate async response path.130 """131 # Setup default url resolver for this thread.132 set_urlconf(settings.ROOT_URLCONF)133 response = await self._middleware_chain(request)134 response._resource_closers.append(request.close)135 if response.status_code >= 400:136 await sync_to_async(log_response, thread_sensitive=False)(137 '%s: %s', response.reason_phrase, request.path,138 response=response,139 request=request,140 )141 return response142 def _get_response(self, request):143 """144 Resolve and call the view, then apply view, exception, and145 template_response middleware. This method is everything that happens146 inside the request/response middleware.147 """148 response = None149 callback, callback_args, callback_kwargs = self.resolve_request(request)150 # Apply view middleware151 for middleware_method in self._view_middleware:152 response = middleware_method(request, callback, callback_args, callback_kwargs)153 if response:154 break155 if response is None:156 wrapped_callback = self.make_view_atomic(callback)157 # If it is an asynchronous view, run it in a subthread.158 if asyncio.iscoroutinefunction(wrapped_callback):159 wrapped_callback = async_to_sync(wrapped_callback)160 try:161 response = wrapped_callback(request, *callback_args, **callback_kwargs)162 except Exception as e:163 response = self.process_exception_by_middleware(e, request)164 if response is None:165 raise166 # Complain if the view returned None (a common error).167 self.check_response(response, callback)168 # If the response supports deferred rendering, apply template169 # response middleware and then render the response170 if hasattr(response, 'render') and callable(response.render):171 for middleware_method in self._template_response_middleware:172 response = middleware_method(request, response)173 # Complain if the template response middleware returned None (a common error).174 self.check_response(175 response,176 middleware_method,177 name='%s.process_template_response' % (178 middleware_method.__self__.__class__.__name__,179 )180 )181 try:182 response = response.render()183 except Exception as e:184 response = self.process_exception_by_middleware(e, request)185 if response is None:186 raise187 return response188 async def _get_response_async(self, request):189 """190 Resolve and call the view, then apply view, exception, and191 template_response middleware. This method is everything that happens192 inside the request/response middleware.193 """194 response = None195 callback, callback_args, callback_kwargs = self.resolve_request(request)196 # Apply view middleware.197 for middleware_method in self._view_middleware:198 response = await middleware_method(request, callback, callback_args, callback_kwargs)199 if response:200 break201 if response is None:202 wrapped_callback = self.make_view_atomic(callback)203 # If it is a synchronous view, run it in a subthread204 if not asyncio.iscoroutinefunction(wrapped_callback):205 wrapped_callback = sync_to_async(wrapped_callback, thread_sensitive=True)206 try:207 response = await wrapped_callback(request, *callback_args, **callback_kwargs)208 except Exception as e:209 response = await sync_to_async(210 self.process_exception_by_middleware,211 thread_sensitive=True,212 )(e, request)213 if response is None:214 raise215 # Complain if the view returned None or an uncalled coroutine.216 self.check_response(response, callback)217 # If the response supports deferred rendering, apply template218 # response middleware and then render the response219 if hasattr(response, 'render') and callable(response.render):220 for middleware_method in self._template_response_middleware:221 response = await middleware_method(request, response)222 # Complain if the template response middleware returned None or223 # an uncalled coroutine.224 self.check_response(225 response,226 middleware_method,227 name='%s.process_template_response' % (228 middleware_method.__self__.__class__.__name__,229 )230 )231 try:232 if asyncio.iscoroutinefunction(response.render):233 response = await response.render()234 else:235 response = await sync_to_async(response.render, thread_sensitive=True)()236 except Exception as e:237 response = await sync_to_async(238 self.process_exception_by_middleware,239 thread_sensitive=True,240 )(e, request)241 if response is None:242 raise243 # Make sure the response is not a coroutine244 if asyncio.iscoroutine(response):245 raise RuntimeError('Response is still a coroutine.')246 return response247 def resolve_request(self, request):248 """249 Retrieve/set the urlconf for the request. Return the view resolved,250 with its args and kwargs.251 """252 # Work out the resolver.253 if hasattr(request, 'urlconf'):254 urlconf = request.urlconf255 set_urlconf(urlconf)256 resolver = get_resolver(urlconf)257 else:258 resolver = get_resolver()259 # Resolve the view, and assign the match object back to the request.260 resolver_match = resolver.resolve(request.path_info)261 request.resolver_match = resolver_match262 return resolver_match263 def check_response(self, response, callback, name=None):264 """265 Raise an error if the view returned None or an uncalled coroutine.266 """267 if not(response is None or asyncio.iscoroutine(response)):268 return269 if not name:270 if isinstance(callback, types.FunctionType): # FBV271 name = 'The view %s.%s' % (callback.__module__, callback.__name__)272 else: # CBV273 name = 'The view %s.%s.__call__' % (274 callback.__module__,275 callback.__class__.__name__,276 )277 if response is None:...
test_response.py
Source:test_response.py
...16# A test middleware that installs a temporary URLConf17def custom_urlconf_middleware(get_response):18 def middleware(request):19 request.urlconf = 'template_tests.alternate_urls'20 return get_response(request)21 return middleware22class SimpleTemplateResponseTest(SimpleTestCase):23 def _response(self, template='foo', *args, **kwargs):24 template = engines['django'].from_string(template)25 return SimpleTemplateResponse(template, *args, **kwargs)26 def test_template_resolving(self):27 response = SimpleTemplateResponse('first/test.html')28 response.render()29 self.assertEqual(response.content, b'First template\n')30 templates = ['foo.html', 'second/test.html', 'first/test.html']31 response = SimpleTemplateResponse(templates)32 response.render()33 self.assertEqual(response.content, b'Second template\n')34 response = self._response()35 response.render()36 self.assertEqual(response.content, b'foo')37 def test_explicit_baking(self):38 # explicit baking39 response = self._response()40 self.assertFalse(response.is_rendered)41 response.render()42 self.assertTrue(response.is_rendered)43 def test_render(self):44 # response is not re-rendered without the render call45 response = self._response().render()46 self.assertEqual(response.content, b'foo')47 # rebaking doesn't change the rendered content48 template = engines['django'].from_string('bar{{ baz }}')49 response.template_name = template50 response.render()51 self.assertEqual(response.content, b'foo')52 # but rendered content can be overridden by manually53 # setting content54 response.content = 'bar'55 self.assertEqual(response.content, b'bar')56 def test_iteration_unrendered(self):57 # unrendered response raises an exception on iteration58 response = self._response()59 self.assertFalse(response.is_rendered)60 def iteration():61 list(response)62 msg = 'The response content must be rendered before it can be iterated over.'63 with self.assertRaisesMessage(ContentNotRenderedError, msg):64 iteration()65 self.assertFalse(response.is_rendered)66 def test_iteration_rendered(self):67 # iteration works for rendered responses68 response = self._response().render()69 self.assertEqual(list(response), [b'foo'])70 def test_content_access_unrendered(self):71 # unrendered response raises an exception when content is accessed72 response = self._response()73 self.assertFalse(response.is_rendered)74 with self.assertRaises(ContentNotRenderedError):75 response.content76 self.assertFalse(response.is_rendered)77 def test_content_access_rendered(self):78 # rendered response content can be accessed79 response = self._response().render()80 self.assertEqual(response.content, b'foo')81 def test_set_content(self):82 # content can be overridden83 response = self._response()84 self.assertFalse(response.is_rendered)85 response.content = 'spam'86 self.assertTrue(response.is_rendered)87 self.assertEqual(response.content, b'spam')88 response.content = 'baz'89 self.assertEqual(response.content, b'baz')90 def test_dict_context(self):91 response = self._response('{{ foo }}{{ processors }}',92 {'foo': 'bar'})93 self.assertEqual(response.context_data, {'foo': 'bar'})94 response.render()95 self.assertEqual(response.content, b'bar')96 def test_kwargs(self):97 response = self._response(content_type='application/json', status=504, charset='ascii')98 self.assertEqual(response['content-type'], 'application/json')99 self.assertEqual(response.status_code, 504)100 self.assertEqual(response.charset, 'ascii')101 def test_args(self):102 response = SimpleTemplateResponse('', {}, 'application/json', 504)103 self.assertEqual(response['content-type'], 'application/json')104 self.assertEqual(response.status_code, 504)105 @require_jinja2106 def test_using(self):107 response = SimpleTemplateResponse('template_tests/using.html').render()108 self.assertEqual(response.content, b'DTL\n')109 response = SimpleTemplateResponse('template_tests/using.html', using='django').render()110 self.assertEqual(response.content, b'DTL\n')111 response = SimpleTemplateResponse('template_tests/using.html', using='jinja2').render()112 self.assertEqual(response.content, b'Jinja2\n')113 def test_post_callbacks(self):114 "Rendering a template response triggers the post-render callbacks"115 post = []116 def post1(obj):117 post.append('post1')118 def post2(obj):119 post.append('post2')120 response = SimpleTemplateResponse('first/test.html', {})121 response.add_post_render_callback(post1)122 response.add_post_render_callback(post2)123 # When the content is rendered, all the callbacks are invoked, too.124 response.render()125 self.assertEqual(response.content, b'First template\n')126 self.assertEqual(post, ['post1', 'post2'])127 def test_pickling(self):128 # Create a template response. The context is129 # known to be unpicklable (e.g., a function).130 response = SimpleTemplateResponse('first/test.html', {131 'value': 123,132 'fn': datetime.now,133 })134 with self.assertRaises(ContentNotRenderedError):135 pickle.dumps(response)136 # But if we render the response, we can pickle it.137 response.render()138 pickled_response = pickle.dumps(response)139 unpickled_response = pickle.loads(pickled_response)140 self.assertEqual(unpickled_response.content, response.content)141 self.assertEqual(unpickled_response['content-type'], response['content-type'])142 self.assertEqual(unpickled_response.status_code, response.status_code)143 # ...and the unpickled response doesn't have the144 # template-related attributes, so it can't be re-rendered145 template_attrs = ('template_name', 'context_data', '_post_render_callbacks')146 for attr in template_attrs:147 self.assertFalse(hasattr(unpickled_response, attr))148 # ...and requesting any of those attributes raises an exception149 for attr in template_attrs:150 with self.assertRaises(AttributeError):151 getattr(unpickled_response, attr)152 def test_repickling(self):153 response = SimpleTemplateResponse('first/test.html', {154 'value': 123,155 'fn': datetime.now,156 })157 with self.assertRaises(ContentNotRenderedError):158 pickle.dumps(response)159 response.render()160 pickled_response = pickle.dumps(response)161 unpickled_response = pickle.loads(pickled_response)162 pickle.dumps(unpickled_response)163 def test_pickling_cookie(self):164 response = SimpleTemplateResponse('first/test.html', {165 'value': 123,166 'fn': datetime.now,167 })168 response.cookies['key'] = 'value'169 response.render()170 pickled_response = pickle.dumps(response, pickle.HIGHEST_PROTOCOL)171 unpickled_response = pickle.loads(pickled_response)172 self.assertEqual(unpickled_response.cookies['key'].value, 'value')173@override_settings(TEMPLATES=[{174 'BACKEND': 'django.template.backends.django.DjangoTemplates',175 'DIRS': [TEMPLATE_DIR],176 'OPTIONS': {177 'context_processors': [test_processor_name],178 },179}])180class TemplateResponseTest(SimpleTestCase):181 factory = RequestFactory()182 def _response(self, template='foo', *args, **kwargs):183 self._request = self.factory.get('/')184 template = engines['django'].from_string(template)185 return TemplateResponse(self._request, template, *args, **kwargs)186 def test_render(self):187 response = self._response('{{ foo }}{{ processors }}').render()188 self.assertEqual(response.content, b'yes')189 def test_render_with_requestcontext(self):190 response = self._response('{{ foo }}{{ processors }}',191 {'foo': 'bar'}).render()192 self.assertEqual(response.content, b'baryes')193 def test_context_processor_priority(self):194 # context processors should be overridden by passed-in context195 response = self._response('{{ foo }}{{ processors }}',196 {'processors': 'no'}).render()197 self.assertEqual(response.content, b'no')198 def test_kwargs(self):199 response = self._response(content_type='application/json', status=504)200 self.assertEqual(response['content-type'], 'application/json')201 self.assertEqual(response.status_code, 504)202 def test_args(self):203 response = TemplateResponse(self.factory.get('/'), '', {},204 'application/json', 504)205 self.assertEqual(response['content-type'], 'application/json')206 self.assertEqual(response.status_code, 504)207 @require_jinja2208 def test_using(self):209 request = self.factory.get('/')210 response = TemplateResponse(request, 'template_tests/using.html').render()211 self.assertEqual(response.content, b'DTL\n')212 response = TemplateResponse(request, 'template_tests/using.html', using='django').render()213 self.assertEqual(response.content, b'DTL\n')...
test_views.py
Source:test_views.py
...117 return_value={'count': 0, 'results': []},118 )119 def setUp(self):120 self.user = AppUser.objects.get(id=2)121 def _get_mock_response(self, url):122 """Returns an api response with a mocked version of distillery.find123 Parameters124 ----------125 url : str126 URL to navigate to.127 Returns128 -------129 rest_framework.response.Response130 """131 with self.MOCK_FIND:132 return self.get_api_response(url)133 def _get_empty_mock_response(self, url):134 """Returns an API response with an empty mocked promise.135 Parameters136 ----------137 url : str138 URL to navigate to.139 Returns140 -------141 rest_framework.response.Response142 """143 with self.EMPTY_MOCK_FIND:144 return self.get_api_response(url)145 def _is_valid_response(self, response):146 """Tests that the API response is valid.147 Parameters148 ----------149 response : rest_framework.response.Response150 """151 self.assertEqual(response.status_code, 200)152 def _is_invalid_response(self, response):153 """Tests that the API response is invalid.154 Parameters155 ----------156 response : rest_framework.response.Response157 """158 self.assertEqual(response.status_code, 400)159class SearchViewTestCase(SearchViewBaseTestCase):160 model_url = 'search/'161 def test_valid_query(self):162 """163 Tests that a valid response is returned when hitting the endpoint.164 """165 response = self.get_api_response('?query=something')166 self._is_valid_response(response)167 self.assertEqual(168 response.data['results']['count'],169 1170 )171 def test_invalid_query(self):172 """173 Tests that a 400 error is thrown for an invalid query string.174 """175 response = self.get_api_response('?query=e#4390812@!FE#@GE')176 self._is_invalid_response(response)177 self.assertEqual(178 response.data['query']['unknown'][0]['errors'][0],179 'Parameter type is unknown.',180 )181 response = self.get_api_response('')182 self._is_invalid_response(response)183 self.assertEqual(184 response.data['query']['errors'][0],185 'Search query is empty.'186 )187 def test_query_data(self):188 """189 Tests that a query description is sent with the result data.190 """191 response = self.get_api_response('?query=keyword')192 self._is_valid_response(response)193 self.assertEqual(len(response.data['query']['keywords']), 1)194 def test_alert_data(self):195 """196 Tests that alert data gets grouped into it's own dictionary.197 """198 response = self.get_api_response('?query=keyword')199 self._is_valid_response(response)200 self.assertEqual(response.data['results']['alerts']['count'], 0)201 self.assertEqual(response.data['results']['alerts']['next'], None)202 self.assertEqual(response.data['results']['alerts']['previous'], None)203 self.assertEqual(response.data['results']['alerts']['results'], [])204 def test_distilleries_data(self):205 """206 Tests that distillery data gets grouped into it's own dictionary.207 """208 response = self.get_api_response('?query=keyword')209 self._is_valid_response(response)210 self.assertEqual(211 response.data['results']['distilleries']['count'], 0)212 self.assertEqual(213 response.data['results']['distilleries']['results'], [])214class AlertSearchViewTestCase(SearchViewBaseTestCase):215 """216 """217 fixtures = get_fixtures(218 ['alerts', 'distilleries', 'bottles', 'comments', 'users'],219 )220 model_url = 'search/alerts/'221 def test_field_parameters_ignored(self):222 """223 Tests that field parameters are ignored when searching through224 alerts.225 """226 response = self.get_api_response('?query=ip_address=14')227 self._is_valid_response(response)228 self.assertEqual(response.data['query']['fields'], [])229 def test_400_response(self):230 """231 Tests that a 400 response is returned for an invalid search query.232 """233 response = self.get_api_response('')234 self._is_invalid_response(response)235 self.assertEqual(236 response.data['query']['errors'][0],237 'Search query is empty.',238 )239 def test_results(self):240 """241 Tests that the correct result shape is returned from the endpoint.242 """243 response = self.get_api_response('?query=something')244 self._is_valid_response(response)245 self.assertEqual(response.data['results']['count'], 1)246 self.assertEqual(response.data['results']['next'], None)247 self.assertEqual(response.data['results']['previous'], None)248 self.assertEqual(len(response.data['results']['results']), 1)249class SearchDistilleriesViewTestCase(SearchViewBaseTestCase):250 """251 """252 model_url = 'search/distilleries/'253 def test_results(self):254 """255 Tests that the correct result shape is returned from the endpoint.256 """257 response = self._get_mock_response(258 '?query=%40source%3D%22test_mail%22+something'259 )260 self._is_valid_response(response)261 self.assertEqual(response.data['results']['count'], 1)262 self.assertEqual(len(response.data['results']['results']), 1)263 self.assertEqual(response.data['results']['results'][0], {264 'count': 1,265 'next': None,266 'previous': None,267 'distillery': {268 'id': 6,269 'name': 'elasticsearch.test_index.test_mail',270 'url': 'http://testserver/api/v1/distilleries/6/',271 },272 'results': self.MOCK_RESULTS_LIST273 })274 def test_invalid_response(self):275 """276 Tests that a 400 response with errors is returned from the endpoint.277 """278 response = self._get_mock_response('')279 self._is_invalid_response(response)280 self.assertEqual(281 response.data['query']['errors'][0],282 'Search query is empty.',283 )284class SearchDistilleryViewTestCase(SearchViewBaseTestCase):285 """286 """287 model_url = 'search/distilleries/'288 def test_results(self):289 """290 Tests that the correct result shape is returned from the endpoint.291 """292 response = self._get_mock_response('6/?query=something')293 self._is_valid_response(response)294 self.assertEqual(response.data['results']['count'], 1)295 self.assertEqual(response.data['results']['next'], None)296 self.assertEqual(response.data['results']['previous'], None)297 self.assertEqual(response.data['results']['distillery'], {298 'id': 6,299 'name': 'elasticsearch.test_index.test_mail',300 'url': 'http://testserver/api/v1/distilleries/6/',301 })302 self.assertEqual(303 response.data['results']['results'],304 self.MOCK_RESULTS_LIST,305 )306 def test_ignored_distillery_filter(self):307 """308 Tests that distillery filter parameters are ignored.309 """310 response = self._get_empty_mock_response(311 '2/?query=%40source%3D%22test_mail%22+something',312 )313 self._is_valid_response(response)314 self.assertEqual(response.data['query']['distilleries'], None)315 self.assertEqual(response.data['results']['distillery'], {316 'id': 2,317 'name': 'mongodb.test_database.test_docs',318 'url': 'http://testserver/api/v1/distilleries/2/',319 })320 def test_distillery_not_found(self):321 response = self._get_empty_mock_response('12/?query=woo')322 self.assertEqual(response.status_code, 404)323 self.assertEqual(response.data['detail'], 'Distillery 12 not found.')324 def test_empty_search_query(self):325 response = self._get_empty_mock_response('6/?query=')326 self.assertEqual(response.status_code, 400)327 self.assertEqual(response.data['query']['errors'][0],...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!