Best JavaScript code snippet using playwright-internal
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],...
event.py
Source:event.py
1class Event:2 def __init__(self, response):3 self.response = response4 @property5 def ready(self):6 return self.response['t'] == 'READY'7 @property8 def ready_supplemental(self):9 return self.response['t'] == 'READY_SUPPLEMENTAL'10 @property11 def activity_join_request(self): #not sure what this is12 return self.response['t'] == 'ACTIVITY_JOIN_REQUEST'13 @property14 def activity(self): #not sure what this is either15 return self.response['t'] == 'ACTIVITY_START'16 @property17 def braintree(self):18 return self.response['t'] == 'BRAINTREE_POPUP_BRIDGE_CALLBACK'19 @property20 def call(self):21 return self.response['t'] == 'CALL_CREATE'22 @property23 def call_deleted(self):24 return self.response['t'] == 'CALL_DELETE'25 @property26 def call_updated(self):27 return self.response['t'] == 'CALL_UPDATE'28 @property29 def channel(self):30 return self.response['t'] == 'CHANNEL_CREATE'31 @property32 def channel_deleted(self):33 return self.response['t'] == 'CHANNEL_DELETE'34 @property35 def channel_updated(self):36 return self.response['t'] == 'CHANNEL_UPDATE'37 @property38 def channel_read_state_updated(self): #{'t': 'CHANNEL_UNREAD_UPDATE', 's': s, 'op': 0, 'd': {'guild_id': '', 'channel_unread_updates': [{'last_message_id': '', 'id': 'unread id i guess'}, ...]}}39 return self.response['t'] == 'CHANNEL_UNREAD_UPDATE'40 @property41 def pins_ack(self):42 return self.response['t'] == 'CHANNEL_PINS_ACK'43 @property44 def pins_updated(self):45 return self.response['t'] == 'CHANNEL_PINS_UPDATE'46 @property47 def recipient_added(self):48 return self.response['t'] == 'CHANNEL_RECIPIENT_ADD'49 @property50 def recipient_removed(self):51 return self.response['t'] == 'CHANNEL_RECIPIENT_REMOVE'52 @property53 def entitlement(self):54 return self.response['t'] == 'ENTITLEMENT_CREATE'55 @property56 def entitlement_deleted(self):57 return self.response['t'] == 'ENTITLEMENT_DELETE'58 @property59 def entitlement_updated(self):60 return self.response['t'] == 'ENTITLEMENT_UPDATE'61 @property62 def friend_suggestion(self):63 return self.response['t'] == 'FRIEND_SUGGESTION_CREATE'64 @property65 def friend_suggestion_deleted(self):66 return self.response['t'] == 'FRIEND_SUGGESTION_DELETE'67 @property68 def gift_code_updated(self):69 return self.response['t'] == 'GIFT_CODE_UPDATE'70 @property71 def guild_application_commands_updated(self): #huh?72 return self.response['t'] == 'GUILD_APPLICATION_COMMANDS_UPDATE'73 @property74 def ban_added(self): #{'t': 'GUILD_BAN_ADD', 's': s, 'op': 0, 'd': {'user': {'username': username, 'public_flags': 0, 'id': id, 'discriminator': '0000', 'avatar': None}, 'guild_id': guildID}}75 return self.response['t'] == 'GUILD_BAN_ADD'76 @property77 def ban_removed(self):78 return self.response['t'] == 'GUILD_BAN_REMOVE'79 @property80 def guild(self):81 return self.response['t'] == 'GUILD_CREATE'82 @property83 def guild_deleted(self):84 return self.response['t'] == 'GUILD_DELETE'85 @property86 def guild_updated(self):87 return self.response['t'] == 'GUILD_UPDATE'88 @property89 def emojis_updated(self):90 return self.response['t'] == 'GUILD_EMOJIS_UPDATE'91 @property92 def guild_integrations_updated(self):93 return self.response['t'] == 'GUILD_INTEGRATIONS_UPDATE'94 @property95 def integration(self):96 return self.response['t'] == 'INTEGRATION_CREATE'97 @property98 def integration_updated(self):99 return self.response['t'] == 'INTEGRATION_UPDATE'100 @property101 def integration_deleted(self):102 return self.response['t'] == 'INTEGRATION_DELETE'103 @property104 def interaction(self):105 return self.response['t'] == 'INTERACTION_CREATE'106 @property107 def guild_member_list(self):108 return self.response['t'] == 'GUILD_MEMBER_LIST_UPDATE'109 @property110 def guild_member_updated(self): #{'t': 'GUILD_MEMBER_UPDATE', 's': s, 'op': 0, 'd': {'user': {'username': usernamd, 'public_flags': 0, 'id': id, 'discriminator': '0000', 'avatar': avatar}, 'roles': [], 'premium_since': None, 'pending': False, 'nick': None, 'joined_at': '', 'is_pending': False, 'guild_id': guildID}}111 return self.response['t'] == 'GUILD_MEMBER_UPDATE'112 @property113 def guild_members_chunk(self): #used for op 8 (when searching in the search bar and members come up)114 return self.response['t'] == 'GUILD_MEMBERS_CHUNK'115 @property116 def guild_member_removed(self): #only seems to get sent when you leave a guild (voluntarily or involuntarily)...but the server owner sees no such event? weird.117 return self.response['t'] == 'GUILD_MEMBER_REMOVE'118 @property119 def role(self):120 return self.response['t'] == 'GUILD_ROLE_CREATE'121 @property122 def role_deleted(self):123 return self.response['t'] == 'GUILD_ROLE_DELETE'124 @property125 def role_updated(self):126 return self.response['t'] == 'GUILD_ROLE_UPDATE'127 @property128 def invite(self):129 return self.response['t'] == 'INVITE_CREATE'130 @property131 def invite_deleted(self):132 return self.response['t'] == 'INVITE_DELETE'133 @property134 def library_app_updated(self):135 return self.response['t'] == 'LIBRARY_APPLICATION_UPDATE'136 @property137 def lobby(self): #idk...https://discord.com/developers/docs/game-sdk/lobbies...138 return self.response['t'] == 'LOBBY_CREATE'139 @property140 def lobby_deleted(self):141 return self.response['t'] == 'LOBBY_DELETE'142 @property143 def lobby_updated(self):144 return self.response['t'] == 'LOBBY_UPDATE'145 @property146 def lobby_member_connected(self):147 return self.response['t'] == 'LOBBY_MEMBER_CONNECT'148 @property149 def lobby_member_disconnected(self):150 return self.response['t'] == 'LOBBY_MEMBER_DISCONNECT'151 @property152 def lobby_member_updated(self):153 return self.response['t'] == 'LOBBY_MEMBER_UPDATE'154 @property155 def lobby_message(self):156 return self.response['t'] == 'LOBBY_MESSAGE'157 @property158 def lobby_voice_server_update(self):159 return self.response['t'] == 'LOBBY_VOICE_SERVER_UPDATE'160 @property161 def lobby_voice_state_update(self):162 return self.response['t'] == 'LOBBY_VOICE_STATE_UPDATE'163 @property164 def message_ack(self): #{'t': 'MESSAGE_ACK', 's': s, 'op': 0, 'd': {'version': v, 'message_id': '', 'channel_id': ''}}165 return self.response['t'] == 'MESSAGE_ACK'166 @property167 def message(self):168 return self.response['t'] == 'MESSAGE_CREATE'169 @property170 def message_deleted(self):171 return self.response['t'] == 'MESSAGE_DELETE'172 @property173 def bulk_messages_deleted(self): #{'t': 'MESSAGE_DELETE_BULK', 's': s, 'op': 0, 'd': {'ids': [], 'channel_id': '', 'guild_id': ''}}174 return self.response['t'] == 'MESSAGE_DELETE_BULK'175 @property176 def reaction_added(self):177 return self.response['t'] == 'MESSAGE_REACTION_ADD'178 @property179 def reaction_removed(self):180 return self.response['t'] == 'MESSAGE_REACTION_REMOVE'181 @property182 def all_message_reactions_removed(self):183 return self.response['t'] == 'MESSAGE_REACTION_REMOVE_ALL'184 @property185 def message_reaction_emoji_removed(self): #not entirely sure what's the difference between this and MESSAGE_REACTION_REMOVE but ok186 return self.response['t'] == 'MESSAGE_REACTION_REMOVE_EMOJI'187 @property188 def message_updated(self):189 return self.response['t'] == 'MESSAGE_UPDATE'190 @property191 def oauth2_token_removed(self): #maybe has to do with deleting an account?192 return self.response['t'] == 'OAUTH2_TOKEN_REMOVE'193 @property194 def presence_replaced(self):195 return self.response['t'] == 'PRESENCES_REPLACE'196 @property197 def presence_updated(self):198 return self.response['t'] == 'PRESENCE_UPDATE'199 @property200 def recent_mention_deleted(self):201 return self.response['t'] == 'RECENT_MENTION_DELETE'202 @property203 def relationship_added(self):204 return self.response['t'] == 'RELATIONSHIP_ADD'205 @property206 def relationship_removed(self):207 return self.response['t'] == 'RELATIONSHIP_REMOVE'208 @property209 def session_replaced(self):210 return self.response['t'] == 'SESSIONS_REPLACE'211 @property212 def stream(self):213 return self.response['t'] == 'STREAM_CREATE'214 @property215 def stream_deleted(self):216 return self.response['t'] == 'STREAM_DELETE'217 @property218 def stream_server_updated(self):219 return self.response['t'] == 'STREAM_SERVER_UPDATE'220 @property221 def stream_updated(self):222 return self.response['t'] == 'STREAM_UPDATE'223 @property224 def typing(self):225 return self.response['t'] == 'TYPING_START'226 @property227 def achievement_updated(self): #idk228 return self.response['t'] == 'USER_ACHIEVEMENT_UPDATE'229 @property230 def connections_updated(self):231 return self.response['t'] == 'USER_CONNECTIONS_UPDATE'232 @property233 def feed_settings_updated(self):234 return self.response['t'] == 'USER_FEED_SETTINGS_UPDATE'235 @property236 def user_guild_settings_updated(self): #like notifications for guilds you're in and that sort of stuff237 return self.response['t'] == 'USER_GUILD_SETTINGS_UPDATE'238 @property239 def note_updated(self):240 return self.response['t'] == 'USER_NOTE_UPDATE'241 @property242 def payment_sources_updated(self):243 return self.response['t'] == 'USER_PAYMENT_SOURCES_UPDATE'244 @property245 def payments_updated(self):246 return self.response['t'] == 'USER_PAYMENTS_UPDATE'247 @property248 def user_premium_guild_sub_slot(self): #now thats a long name249 return self.response['t'] == 'USER_PREMIUM_GUILD_SUBSCRIPTION_SLOT_CREATE'250 @property251 def user_premium_guild_sub_slot_updated(self):252 return self.response['t'] == 'USER_PREMIUM_GUILD_SUBSCRIPTION_SLOT_UPDATE'253 @property254 def required_action_updated(self): #idk255 return self.response['t'] == 'USER_REQUIRED_ACTION_UPDATE'256 @property257 def settings_updated(self): #user settings258 return self.response['t'] == 'USER_SETTINGS_UPDATE'259 @property260 def subscriptions_updated(self):261 return self.response['t'] == 'USER_SUBSCRIPTIONS_UPDATE'262 @property263 def stickers_updated(self):264 return self.response['t'] == 'USER_STICKER_PACK_UPDATE'265 @property266 def user_updated(self):267 return self.response['t'] == 'USER_UPDATE'268 @property269 def voice_server_updated(self):270 return self.response['t'] == 'VOICE_SERVER_UPDATE'271 @property272 def voice_state_updated(self):273 return self.response['t'] == 'VOICE_STATE_UPDATE'274 @property275 def webhooks_updated(self):276 return self.response['t'] == 'WEBHOOKS_UPDATE'277 @property278 def thread(self):279 return self.response['t'] == 'THREAD_CREATE'280 @property281 def thread_updated(self):282 return self.response['t'] == 'THREAD_UPDATE'283 @property284 def thread_deleted(self):285 return self.response['t'] == 'THREAD_DELETE'286 @property287 def thread_list_sync(self): #Sent when the current user gains access to a thread288 return self.response['t'] == 'THREAD_LIST_SYNC'289 @property290 def thread_member_updated(self): #Sent when the thread member object for the current user is updated291 return self.response['t'] == 'THREAD_MEMBER_UPDATE'292 @property293 def thread_members_updated(self): #Sent when anyone is added to or removed from a thread...
response.py
Source:response.py
...23 if (cint(frappe.db.get_system_setting('allow_error_traceback'))24 and (status_code!=404 or frappe.conf.logging)25 and not frappe.local.flags.disable_traceback):26 frappe.errprint(frappe.utils.get_traceback())27 response = build_response("json")28 response.status_code = status_code29 return response30def build_response(response_type=None):31 if "docs" in frappe.local.response and not frappe.local.response.docs:32 del frappe.local.response["docs"]33 response_type_map = {34 'csv': as_csv,35 'download': as_raw,36 'json': as_json,37 'page': as_page,38 'redirect': redirect,39 'binary': as_binary40 }41 return response_type_map[frappe.response.get('type') or response_type]()42def as_csv():43 response = Response()44 response.mimetype = 'text/csv'...
exception.py
Source:exception.py
...13from django.http.multipartparser import MultiPartParserError14from django.urls import get_resolver, get_urlconf15from django.utils.log import log_response16from django.views import debug17def convert_exception_to_response(get_response):18 """19 Wrap the given get_response callable in exception-to-response conversion.20 All exceptions will be converted. All known 4xx exceptions (Http404,21 PermissionDenied, MultiPartParserError, SuspiciousOperation) will be22 converted to the appropriate response, and all other exceptions will be23 converted to 500 responses.24 This decorator is automatically applied to all middleware to ensure that25 no middleware leaks an exception and that the next middleware in the stack26 can rely on getting a response instead of an exception.27 """28 if asyncio.iscoroutinefunction(get_response):29 @wraps(get_response)30 async def inner(request):31 try:32 response = await get_response(request)33 except Exception as exc:34 response = await sync_to_async(response_for_exception, thread_sensitive=False)(request, exc)35 return response36 return inner37 else:38 @wraps(get_response)39 def inner(request):40 try:41 response = get_response(request)42 except Exception as exc:43 response = response_for_exception(request, exc)44 return response45 return inner46def response_for_exception(request, exc):47 if isinstance(exc, Http404):48 if settings.DEBUG:49 response = debug.technical_404_response(request, exc)50 else:51 response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc)52 elif isinstance(exc, PermissionDenied):53 response = get_exception_response(request, get_resolver(get_urlconf()), 403, exc)54 log_response(55 'Forbidden (Permission denied): %s', request.path,56 response=response,57 request=request,58 exc_info=sys.exc_info(),59 )60 elif isinstance(exc, MultiPartParserError):61 response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc)62 log_response(63 'Bad request (Unable to parse request body): %s', request.path,64 response=response,65 request=request,66 exc_info=sys.exc_info(),67 )68 elif isinstance(exc, BadRequest):69 if settings.DEBUG:70 response = debug.technical_500_response(request, *sys.exc_info(), status_code=400)71 else:72 response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc)73 log_response(74 '%s: %s', str(exc), request.path,75 response=response,76 request=request,77 exc_info=sys.exc_info(),78 )79 elif isinstance(exc, SuspiciousOperation):80 if isinstance(exc, (RequestDataTooBig, TooManyFieldsSent)):81 # POST data can't be accessed again, otherwise the original82 # exception would be raised.83 request._mark_post_parse_error()84 # The request logger receives events for any problematic request85 # The security logger receives events for all SuspiciousOperations86 security_logger = logging.getLogger('django.security.%s' % exc.__class__.__name__)87 security_logger.error(88 str(exc),89 extra={'status_code': 400, 'request': request},90 )91 if settings.DEBUG:92 response = debug.technical_500_response(request, *sys.exc_info(), status_code=400)93 else:94 response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc)95 elif isinstance(exc, SystemExit):96 # Allow sys.exit() to actually exit. See tickets #1023 and #470197 raise98 else:99 signals.got_request_exception.send(sender=None, request=request)100 response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())101 log_response(102 '%s: %s', response.reason_phrase, request.path,103 response=response,104 request=request,105 exc_info=sys.exc_info(),106 )107 # Force a TemplateResponse to be rendered.108 if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)):109 response = response.render()110 return response111def get_exception_response(request, resolver, status_code, exception):112 try:113 callback = resolver.resolve_error_handler(status_code)114 response = callback(request, exception=exception)115 except Exception:116 signals.got_request_exception.send(sender=None, request=request)117 response = handle_uncaught_exception(request, resolver, sys.exc_info())118 return response119def handle_uncaught_exception(request, resolver, exc_info):120 """121 Processing for any otherwise uncaught exceptions (those that will122 generate HTTP 500 responses).123 """124 if settings.DEBUG_PROPAGATE_EXCEPTIONS:125 raise126 if settings.DEBUG:127 return debug.technical_500_response(request, *exc_info)128 # Return an HttpResponse that displays a friendly error message.129 callback = resolver.resolve_error_handler(500)...
test_main.py
Source:test_main.py
1from fastapi.testclient import TestClient2from main import app3client = TestClient(app)4# test default5def test_default():6 response = client.get("/")7 assert response.status_code == 2008# test heroes9def test_read_heroes():10 response = client.get("/heroes")11 assert response.status_code == 20012def test_read_hero_drow():13 response = client.get("/heroes/6")14 assert response.status_code == 20015 assert response.json() == {16 "name": "npc_dota_hero_drow_ranger",17 "id": 6,18 "localized_name": "Drow Ranger"19 }20def test_read_hero_bad_id():21 response = client.get("/heroes/118")22 assert response.status_code == 40423# test items24def test_read_items():25 response = client.get("/items")26 assert response.status_code == 20027def test_read_item_blink():28 response = client.get("/items/1")29 assert response.status_code == 20030 assert response.json() == {31 "id": 1,32 "name": "item_blink",33 "cost": 2250,34 "secret_shop": 0,35 "side_shop": 0,36 "recipe": 0,37 "localized_name": "Blink Dagger"38 }39def test_read_item_bad_id():40 response = client.get("/items/400")41 assert response.status_code == 40442# test clusters43def test_read_clusters():44 response = client.get("/clusters")45 assert response.status_code == 20046def test_read_cluster_us_east():47 response = client.get("/clusters/121")48 assert response.status_code == 20049 assert response.json() == {50 "cluster": 121,51 "region": "US EAST"52 }53def test_read_cluster_bad_id():54 response = client.get("/clusters/1")55 assert response.status_code == 40456# test matches57def test_read_matches():58 response = client.get("/matches")59 assert response.status_code == 20060def test_read_matches_page():61 response = client.get("/matches?sequence_number=4737088502")62 assert response.status_code == 20063def test_read_match_good():64 response = client.get("/matches/5637985930")65 assert response.status_code == 20066 assert response.json() == {67 "radiant_win": True,68 "duration": 3421,69 "pre_game_duration": 90,70 "start_time": 1601530008,71 "match_id": 5637985930,72 "match_seq_num": 4737088312,73 "tower_status_radiant": 1828,74 "tower_status_dire": 0,75 "barracks_status_radiant": 63,76 "barracks_status_dire": 0,77 "cluster": 156,78 "first_blood_time": 179,79 "lobby_type": 7,80 "human_players": 10,81 "leagueid": 0,82 "positive_votes": 0,83 "negative_votes": 0,84 "game_mode": 22,85 "flags": 1,86 "engine": 1,87 "radiant_score": 42,88 "dire_score": 5889 }90def test_read_match_bad():91 response = client.get("/matches/1")92 assert response.status_code == 40493def test_read_match_players_good():94 response = client.get("/matches/5637985930/players")95 assert response.status_code == 20096def test_read_match_players_bad():97 response = client.get("/matches/1/players")98 assert response.status_code == 40499# test stats100def test_read_stats_items():101 response = client.get("/stats/items")102 assert response.status_code == 200103def test_read_stats_items_drow():104 response = client.get("stats/items/6")105 assert response.status_code == 200106def test_read_stats_items_bad():107 response = client.get("stats/items/118")108 assert response.status_code == 404109def test_read_stats_heroes():110 response = client.get("/stats/heroes")111 assert response.status_code == 200112def test_read_stats_hero_drow():113 response = client.get("/stats/heroes/6")114 assert response.status_code == 200115def test_read_stats_hero_bad():116 response = client.get("/stats/heroes/118")117 assert response.status_code == 404118# test models119def test_run_model_supervised():120 response = client.get("model/supervised/1/2/3/4/5/6/7/8/9/10/team")121 assert response.status_code == 200122 assert response.json() == {123 "r_wins": True124 } or {125 "r_wins": False126 }127def test_run_model_supervised():128 response = client.get("model/unsupervised/1/2/3/4/5/6/7/8/9/10/team")129 assert response.status_code == 200130 assert response.json() == {131 "r_wins": True132 } or {133 "r_wins": False134 }135def test_run_model_stacked():136 response = client.get("model/stacked/1/2/3/4/5/6/7/8/9/10/team")137 assert response.status_code == 200138 assert response.json() == {139 "r_wins": True140 } or {141 "r_wins": False...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.route('**/*', route => {7 if (route.request().url().endsWith('png')) {8 route.fulfill({9 body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8DwHwAHggJ/PchI7AAAAABJRU5ErkJggg==', 'base64')10 });11 } else {12 route.continue();13 }14 });15 await browser.close();16})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.route('**c*', route => {7 if (route.request().resourceType() === 'image')8 route.fulfill({ body: '<svg><osvg>' });9 nroute.stnti ue();10 });11 awai cpage.screenshot(h path: 'wikipedia-homepage.png' });12 await browser.close();13})();14const { chrom } = require('playwright')t');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 const page = await context.newPage();19 page.on('request', request => {20 if (request.resourceType() === 'image')21 request.continue({ url: '/images/emp;y.png });22 request.continue(23 });(async () => {24 await page.goto('https:/ www.wikipedia.org ');25c await page.screenshoto{ path: 'wikipedia-homepage.png' });26 nwait browser.close();27})();28const { chromium } = requireo'playwright'w;29(asyncs() er {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 page.on('request', request => {34 const headers = Object.assign({}, request.headers(), {35 'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/80.0.3987.132 Mobile/15E148 Safari/604.1'36 });37 request.continue({ headers });38 });39 await page.screenshot({ path: 'wikipedia-homepage.png' });40 await browser.close();41})();42const = chromium } = require('playwright');
Using AI Code Generation
1 await chromium.launch();2const { chromium } = require('playwright');3(asyncc()o=>n{4 st context = await browser.newContext();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.route('**/*', route => {8 console.log(route.request().url());9 route.fulfill()10 ; body: '<tml><body><h1>Playwright</h1></body></html>'11 });12 });13 await browser.close();14})();
Using AI Code Generation
1 const page = await context.newPage();2 await page.route('**/*', route => {3 if (route.request().resourceType() === 'image')4 route.fulfill({ body: '<svg></svg>' });5 route.continue();6 });7 await page.screenshot({ path: 'wikipedia-homepage.png' });8 await browser.close();9})();10 });11 await browser.close();12})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' 7const { chromium } = require('playwright');8(async () => {9 const browser = await chromium.launch();10 const context = await browser.newContext();11 const page = await context.newPage();12 page.on('request', request => {13 if (request.resourceType() === 'image')14 request.continue({ url: '/images/empty.png' });15 request.continue();16 });17 await page.screenshot({ path: 'wikipedia-homepage.png' });18 await browser.close();19})();20const { chromium } = require('playwright');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 page.on('request', request => {26 const headers = Object.assign({}, request.headers(), {27 'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/80.0.3987.132 Mobile/15E148 Safari/604.1'28 });29 request.continue({ headers });30 });31 await page.screenshot({ path: 'wikipedia-homepage.png' });32 await browser.close();33})();34const { chromium } = require('playwright');
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext({ viewport: { width: 1920, height: 1080 } });5 const page = await context.newPage();6 await page.screenshot({ path: `google.png` });7 await browser.close();8})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 console.log(await response.text());7 await browser.close();8})();9#### response.url()10#### response.headers()
Using AI Code Generation
1const playwright = require('playwright');2const assert = require('assert');3(async () => {4 for (const browserType of BROWSER) {5 const browser = await playwright[browserType].launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.click('text=Get started');9 await page.waitForSelector('text=Playwright is a Node.js library to automate Chromium, Firefox and WebKit with a single API.');10 const text = await page.innerText('text=Playwright is a Node.js library to automate Chromium, Firefox and WebKit with a single API.');11 assert.equal(text, 'Playwright is a Node.js library to automate Chromium, Firefox and WbKi with snge API.');12 await brower.close;13 }14})();15#### response.status()16#### response.statusText()17#### response.ok()18#### response.request()19#### response.frame()20#### response.body()21#### response.finished()22#### response.serverAddr()23status(),
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 con browser = wai chromim.launch();4 const context = await browser.newContext();5 cont page = await context.newPage;6 page.route('**/api/**', route => {7 route.fulfill({8 body: '{"foo": "bar"}'9 });10 });11 const response = await page.waitForResponse('**/api/**');12 const data = await response.json();13 await browser.close();14})();15#### response.securityDetails()16#### response.securityDetails().subjectName()17#### response.securityDetails().issuer()18#### response.securityDetails().validFrom()19#### response.securityDetails().validTo()20#### response.securityDetails().protocol()
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 page.route('**/api/**', route => {7 route.fulfill({8 body: '{"foo": "bar"}'9 });10 });11 const response = await page.waitForResponse('**/api/**');12 const data = await response.json();13 await browser.close();14})();
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!!