How to use process_response method in autotest

Best Python code snippet using autotest_python

tests.py

Source:tests.py Github

copy

Full Screen

...32 """33 request = self.rf.get('/slash/')34 self.assertIsNone(CommonMiddleware().process_request(request))35 response = HttpResponseNotFound()36 self.assertEqual(CommonMiddleware().process_response(request, response), response)37 @override_settings(APPEND_SLASH=True)38 def test_append_slash_slashless_resource(self):39 """40 Matches to explicit slashless URLs should go unmolested.41 """42 request = self.rf.get('/noslash')43 self.assertIsNone(CommonMiddleware().process_request(request))44 response = HttpResponse("Here's the text of the Web page.")45 self.assertEqual(CommonMiddleware().process_response(request, response), response)46 @override_settings(APPEND_SLASH=True)47 def test_append_slash_slashless_unknown(self):48 """49 APPEND_SLASH should not redirect to unknown resources.50 """51 request = self.rf.get('/unknown')52 response = HttpResponseNotFound()53 self.assertEqual(CommonMiddleware().process_response(request, response), response)54 @override_settings(APPEND_SLASH=True)55 def test_append_slash_redirect(self):56 """57 APPEND_SLASH should redirect slashless URLs to a valid pattern.58 """59 request = self.rf.get('/slash')60 r = CommonMiddleware().process_request(request)61 self.assertEqual(r.status_code, 301)62 @override_settings(APPEND_SLASH=True)63 def test_append_slash_redirect_querystring(self):64 """65 APPEND_SLASH should preserve querystrings when redirecting.66 """67 request = self.rf.get('/slash?test=1')68 response = HttpResponseNotFound()69 r = CommonMiddleware().process_response(request, response)70 self.assertEqual(r.url, '/slash/?test=1')71 @override_settings(APPEND_SLASH=True)72 def test_append_slash_redirect_querystring_have_slash(self):73 """74 APPEND_SLASH should append slash to path when redirecting a request75 with a querystring ending with slash.76 """77 request = self.rf.get('/slash?test=slash/')78 response = HttpResponseNotFound()79 r = CommonMiddleware().process_response(request, response)80 self.assertIsInstance(r, HttpResponsePermanentRedirect)81 self.assertEqual(r.url, '/slash/?test=slash/')82 @override_settings(APPEND_SLASH=True, DEBUG=True)83 def test_append_slash_no_redirect_on_POST_in_DEBUG(self):84 """85 While in debug mode, an exception is raised with a warning86 when a failed attempt is made to POST, PUT, or PATCH to an URL which87 would normally be redirected to a slashed version.88 """89 msg = "maintaining %s data. Change your form to point to testserver/slash/"90 request = self.rf.get('/slash')91 request.method = 'POST'92 response = HttpResponseNotFound()93 with self.assertRaisesMessage(RuntimeError, msg % request.method):94 CommonMiddleware().process_response(request, response)95 request = self.rf.get('/slash')96 request.method = 'PUT'97 with self.assertRaisesMessage(RuntimeError, msg % request.method):98 CommonMiddleware().process_response(request, response)99 request = self.rf.get('/slash')100 request.method = 'PATCH'101 with self.assertRaisesMessage(RuntimeError, msg % request.method):102 CommonMiddleware().process_response(request, response)103 @override_settings(APPEND_SLASH=False)104 def test_append_slash_disabled(self):105 """106 Disabling append slash functionality should leave slashless URLs alone.107 """108 request = self.rf.get('/slash')109 response = HttpResponseNotFound()110 self.assertEqual(CommonMiddleware().process_response(request, response), response)111 @override_settings(APPEND_SLASH=True)112 def test_append_slash_quoted(self):113 """114 URLs which require quoting should be redirected to their slash version.115 """116 request = self.rf.get(quote('/needsquoting#'))117 response = HttpResponseNotFound()118 r = CommonMiddleware().process_response(request, response)119 self.assertEqual(r.status_code, 301)120 self.assertEqual(r.url, '/needsquoting%23/')121 @override_settings(APPEND_SLASH=False, PREPEND_WWW=True)122 def test_prepend_www(self):123 request = self.rf.get('/path/')124 r = CommonMiddleware().process_request(request)125 self.assertEqual(r.status_code, 301)126 self.assertEqual(r.url, 'http://www.testserver/path/')127 @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)128 def test_prepend_www_append_slash_have_slash(self):129 request = self.rf.get('/slash/')130 r = CommonMiddleware().process_request(request)131 self.assertEqual(r.status_code, 301)132 self.assertEqual(r.url, 'http://www.testserver/slash/')133 @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)134 def test_prepend_www_append_slash_slashless(self):135 request = self.rf.get('/slash')136 r = CommonMiddleware().process_request(request)137 self.assertEqual(r.status_code, 301)138 self.assertEqual(r.url, 'http://www.testserver/slash/')139 # The following tests examine expected behavior given a custom URLconf that140 # overrides the default one through the request object.141 @override_settings(APPEND_SLASH=True)142 def test_append_slash_have_slash_custom_urlconf(self):143 """144 URLs with slashes should go unmolested.145 """146 request = self.rf.get('/customurlconf/slash/')147 request.urlconf = 'middleware.extra_urls'148 self.assertIsNone(CommonMiddleware().process_request(request))149 response = HttpResponseNotFound()150 self.assertEqual(CommonMiddleware().process_response(request, response), response)151 @override_settings(APPEND_SLASH=True)152 def test_append_slash_slashless_resource_custom_urlconf(self):153 """154 Matches to explicit slashless URLs should go unmolested.155 """156 request = self.rf.get('/customurlconf/noslash')157 request.urlconf = 'middleware.extra_urls'158 self.assertIsNone(CommonMiddleware().process_request(request))159 response = HttpResponse("Here's the text of the Web page.")160 self.assertEqual(CommonMiddleware().process_response(request, response), response)161 @override_settings(APPEND_SLASH=True)162 def test_append_slash_slashless_unknown_custom_urlconf(self):163 """164 APPEND_SLASH should not redirect to unknown resources.165 """166 request = self.rf.get('/customurlconf/unknown')167 request.urlconf = 'middleware.extra_urls'168 self.assertIsNone(CommonMiddleware().process_request(request))169 response = HttpResponseNotFound()170 self.assertEqual(CommonMiddleware().process_response(request, response), response)171 @override_settings(APPEND_SLASH=True)172 def test_append_slash_redirect_custom_urlconf(self):173 """174 APPEND_SLASH should redirect slashless URLs to a valid pattern.175 """176 request = self.rf.get('/customurlconf/slash')177 request.urlconf = 'middleware.extra_urls'178 response = HttpResponseNotFound()179 r = CommonMiddleware().process_response(request, response)180 self.assertIsNotNone(r, "CommonMiddleware failed to return APPEND_SLASH redirect using request.urlconf")181 self.assertEqual(r.status_code, 301)182 self.assertEqual(r.url, '/customurlconf/slash/')183 @override_settings(APPEND_SLASH=True, DEBUG=True)184 def test_append_slash_no_redirect_on_POST_in_DEBUG_custom_urlconf(self):185 """186 While in debug mode, an exception is raised with a warning187 when a failed attempt is made to POST to an URL which would normally be188 redirected to a slashed version.189 """190 request = self.rf.get('/customurlconf/slash')191 request.urlconf = 'middleware.extra_urls'192 request.method = 'POST'193 response = HttpResponseNotFound()194 with self.assertRaisesMessage(RuntimeError, 'end in a slash'):195 CommonMiddleware().process_response(request, response)196 @override_settings(APPEND_SLASH=False)197 def test_append_slash_disabled_custom_urlconf(self):198 """199 Disabling append slash functionality should leave slashless URLs alone.200 """201 request = self.rf.get('/customurlconf/slash')202 request.urlconf = 'middleware.extra_urls'203 self.assertIsNone(CommonMiddleware().process_request(request))204 response = HttpResponseNotFound()205 self.assertEqual(CommonMiddleware().process_response(request, response), response)206 @override_settings(APPEND_SLASH=True)207 def test_append_slash_quoted_custom_urlconf(self):208 """209 URLs which require quoting should be redirected to their slash version.210 """211 request = self.rf.get(quote('/customurlconf/needsquoting#'))212 request.urlconf = 'middleware.extra_urls'213 response = HttpResponseNotFound()214 r = CommonMiddleware().process_response(request, response)215 self.assertIsNotNone(r, "CommonMiddleware failed to return APPEND_SLASH redirect using request.urlconf")216 self.assertEqual(r.status_code, 301)217 self.assertEqual(r.url, '/customurlconf/needsquoting%23/')218 @override_settings(APPEND_SLASH=False, PREPEND_WWW=True)219 def test_prepend_www_custom_urlconf(self):220 request = self.rf.get('/customurlconf/path/')221 request.urlconf = 'middleware.extra_urls'222 r = CommonMiddleware().process_request(request)223 self.assertEqual(r.status_code, 301)224 self.assertEqual(r.url, 'http://www.testserver/customurlconf/path/')225 @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)226 def test_prepend_www_append_slash_have_slash_custom_urlconf(self):227 request = self.rf.get('/customurlconf/slash/')228 request.urlconf = 'middleware.extra_urls'229 r = CommonMiddleware().process_request(request)230 self.assertEqual(r.status_code, 301)231 self.assertEqual(r.url, 'http://www.testserver/customurlconf/slash/')232 @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)233 def test_prepend_www_append_slash_slashless_custom_urlconf(self):234 request = self.rf.get('/customurlconf/slash')235 request.urlconf = 'middleware.extra_urls'236 r = CommonMiddleware().process_request(request)237 self.assertEqual(r.status_code, 301)238 self.assertEqual(r.url, 'http://www.testserver/customurlconf/slash/')239 # ETag + If-Not-Modified support tests240 @ignore_warnings(category=RemovedInDjango21Warning)241 @override_settings(USE_ETAGS=True)242 def test_etag(self):243 req = HttpRequest()244 res = HttpResponse('content')245 self.assertTrue(CommonMiddleware().process_response(req, res).has_header('ETag'))246 @ignore_warnings(category=RemovedInDjango21Warning)247 @override_settings(USE_ETAGS=True)248 def test_etag_streaming_response(self):249 req = HttpRequest()250 res = StreamingHttpResponse(['content'])251 res['ETag'] = 'tomatoes'252 self.assertEqual(CommonMiddleware().process_response(req, res).get('ETag'), 'tomatoes')253 @ignore_warnings(category=RemovedInDjango21Warning)254 @override_settings(USE_ETAGS=True)255 def test_no_etag_streaming_response(self):256 req = HttpRequest()257 res = StreamingHttpResponse(['content'])258 self.assertFalse(CommonMiddleware().process_response(req, res).has_header('ETag'))259 @ignore_warnings(category=RemovedInDjango21Warning)260 @override_settings(USE_ETAGS=True)261 def test_no_etag_no_store_cache(self):262 req = HttpRequest()263 res = HttpResponse('content')264 res['Cache-Control'] = 'No-Cache, No-Store, Max-age=0'265 self.assertFalse(CommonMiddleware().process_response(req, res).has_header('ETag'))266 @ignore_warnings(category=RemovedInDjango21Warning)267 @override_settings(USE_ETAGS=True)268 def test_etag_extended_cache_control(self):269 req = HttpRequest()270 res = HttpResponse('content')271 res['Cache-Control'] = 'my-directive="my-no-store"'272 self.assertTrue(CommonMiddleware().process_response(req, res).has_header('ETag'))273 @ignore_warnings(category=RemovedInDjango21Warning)274 @override_settings(USE_ETAGS=True)275 def test_if_none_match(self):276 first_req = HttpRequest()277 first_res = CommonMiddleware().process_response(first_req, HttpResponse('content'))278 second_req = HttpRequest()279 second_req.method = 'GET'280 second_req.META['HTTP_IF_NONE_MATCH'] = first_res['ETag']281 second_res = CommonMiddleware().process_response(second_req, HttpResponse('content'))282 self.assertEqual(second_res.status_code, 304)283 # Tests for the Content-Length header284 def test_content_length_header_added(self):285 response = HttpResponse('content')286 self.assertNotIn('Content-Length', response)287 response = CommonMiddleware().process_response(HttpRequest(), response)288 self.assertEqual(int(response['Content-Length']), len(response.content))289 def test_content_length_header_not_added_for_streaming_response(self):290 response = StreamingHttpResponse('content')291 self.assertNotIn('Content-Length', response)292 response = CommonMiddleware().process_response(HttpRequest(), response)293 self.assertNotIn('Content-Length', response)294 def test_content_length_header_not_changed(self):295 response = HttpResponse()296 bad_content_length = len(response.content) + 10297 response['Content-Length'] = bad_content_length298 response = CommonMiddleware().process_response(HttpRequest(), response)299 self.assertEqual(int(response['Content-Length']), bad_content_length)300 # Other tests301 @override_settings(DISALLOWED_USER_AGENTS=[re.compile(r'foo')])302 def test_disallowed_user_agents(self):303 request = self.rf.get('/slash')304 request.META['HTTP_USER_AGENT'] = 'foo'305 with self.assertRaisesMessage(PermissionDenied, 'Forbidden user agent'):306 CommonMiddleware().process_request(request)307 def test_non_ascii_query_string_does_not_crash(self):308 """Regression test for #15152"""309 request = self.rf.get('/slash')310 request.META['QUERY_STRING'] = 'drink=café'311 r = CommonMiddleware().process_request(request)312 self.assertEqual(r.status_code, 301)313 def test_response_redirect_class(self):314 request = self.rf.get('/slash')315 response = HttpResponseNotFound()316 r = CommonMiddleware().process_response(request, response)317 self.assertEqual(r.status_code, 301)318 self.assertEqual(r.url, '/slash/')319 self.assertIsInstance(r, HttpResponsePermanentRedirect)320 def test_response_redirect_class_subclass(self):321 class MyCommonMiddleware(CommonMiddleware):322 response_redirect_class = HttpResponseRedirect323 request = self.rf.get('/slash')324 response = HttpResponseNotFound()325 r = MyCommonMiddleware().process_response(request, response)326 self.assertEqual(r.status_code, 302)327 self.assertEqual(r.url, '/slash/')328 self.assertIsInstance(r, HttpResponseRedirect)329@override_settings(330 IGNORABLE_404_URLS=[re.compile(r'foo')],331 MANAGERS=['PHB@dilbert.com'],332)333class BrokenLinkEmailsMiddlewareTest(SimpleTestCase):334 rf = RequestFactory()335 def setUp(self):336 self.req = self.rf.get('/regular_url/that/does/not/exist')337 self.resp = self.client.get(self.req.path)338 def test_404_error_reporting(self):339 self.req.META['HTTP_REFERER'] = '/another/url/'340 BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)341 self.assertEqual(len(mail.outbox), 1)342 self.assertIn('Broken', mail.outbox[0].subject)343 def test_404_error_reporting_no_referer(self):344 BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)345 self.assertEqual(len(mail.outbox), 0)346 def test_404_error_reporting_ignored_url(self):347 self.req.path = self.req.path_info = 'foo_url/that/does/not/exist'348 BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)349 self.assertEqual(len(mail.outbox), 0)350 def test_custom_request_checker(self):351 class SubclassedMiddleware(BrokenLinkEmailsMiddleware):352 ignored_user_agent_patterns = (re.compile(r'Spider.*'), re.compile(r'Robot.*'))353 def is_ignorable_request(self, request, uri, domain, referer):354 '''Check user-agent in addition to normal checks.'''355 if super().is_ignorable_request(request, uri, domain, referer):356 return True357 user_agent = request.META['HTTP_USER_AGENT']358 return any(pattern.search(user_agent) for pattern in self.ignored_user_agent_patterns)359 self.req.META['HTTP_REFERER'] = '/another/url/'360 self.req.META['HTTP_USER_AGENT'] = 'Spider machine 3.4'361 SubclassedMiddleware().process_response(self.req, self.resp)362 self.assertEqual(len(mail.outbox), 0)363 self.req.META['HTTP_USER_AGENT'] = 'My user agent'364 SubclassedMiddleware().process_response(self.req, self.resp)365 self.assertEqual(len(mail.outbox), 1)366 def test_referer_equal_to_requested_url(self):367 """368 Some bots set the referer to the current URL to avoid being blocked by369 an referer check (#25302).370 """371 self.req.META['HTTP_REFERER'] = self.req.path372 BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)373 self.assertEqual(len(mail.outbox), 0)374 # URL with scheme and domain should also be ignored375 self.req.META['HTTP_REFERER'] = 'http://testserver%s' % self.req.path376 BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)377 self.assertEqual(len(mail.outbox), 0)378 # URL with a different scheme should be ignored as well because bots379 # tend to use http:// in referers even when browsing HTTPS websites.380 self.req.META['HTTP_X_PROTO'] = 'https'381 self.req.META['SERVER_PORT'] = 443382 with self.settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_PROTO', 'https')):383 BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)384 self.assertEqual(len(mail.outbox), 0)385 def test_referer_equal_to_requested_url_on_another_domain(self):386 self.req.META['HTTP_REFERER'] = 'http://anotherserver%s' % self.req.path387 BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)388 self.assertEqual(len(mail.outbox), 1)389 @override_settings(APPEND_SLASH=True)390 def test_referer_equal_to_requested_url_without_trailing_slash_when_append_slash_is_set(self):391 self.req.path = self.req.path_info = '/regular_url/that/does/not/exist/'392 self.req.META['HTTP_REFERER'] = self.req.path_info[:-1]393 BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)394 self.assertEqual(len(mail.outbox), 0)395 @override_settings(APPEND_SLASH=False)396 def test_referer_equal_to_requested_url_without_trailing_slash_when_append_slash_is_unset(self):397 self.req.path = self.req.path_info = '/regular_url/that/does/not/exist/'398 self.req.META['HTTP_REFERER'] = self.req.path_info[:-1]399 BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)400 self.assertEqual(len(mail.outbox), 1)401@override_settings(ROOT_URLCONF='middleware.cond_get_urls')402class ConditionalGetMiddlewareTest(SimpleTestCase):403 def setUp(self):404 self.req = RequestFactory().get('/')405 self.resp = self.client.get(self.req.path_info)406 # Tests for the ETag header407 def test_middleware_calculates_etag(self):408 self.assertNotIn('ETag', self.resp)409 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)410 self.assertEqual(self.resp.status_code, 200)411 self.assertNotEqual('', self.resp['ETag'])412 def test_middleware_wont_overwrite_etag(self):413 self.resp['ETag'] = 'eggs'414 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)415 self.assertEqual(self.resp.status_code, 200)416 self.assertEqual('eggs', self.resp['ETag'])417 def test_no_etag_streaming_response(self):418 res = StreamingHttpResponse(['content'])419 self.assertFalse(ConditionalGetMiddleware().process_response(self.req, res).has_header('ETag'))420 def test_no_etag_no_store_cache(self):421 self.resp['Cache-Control'] = 'No-Cache, No-Store, Max-age=0'422 self.assertFalse(ConditionalGetMiddleware().process_response(self.req, self.resp).has_header('ETag'))423 def test_etag_extended_cache_control(self):424 self.resp['Cache-Control'] = 'my-directive="my-no-store"'425 self.assertTrue(ConditionalGetMiddleware().process_response(self.req, self.resp).has_header('ETag'))426 def test_if_none_match_and_no_etag(self):427 self.req.META['HTTP_IF_NONE_MATCH'] = 'spam'428 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)429 self.assertEqual(self.resp.status_code, 200)430 def test_no_if_none_match_and_etag(self):431 self.resp['ETag'] = 'eggs'432 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)433 self.assertEqual(self.resp.status_code, 200)434 def test_if_none_match_and_same_etag(self):435 self.req.META['HTTP_IF_NONE_MATCH'] = self.resp['ETag'] = '"spam"'436 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)437 self.assertEqual(self.resp.status_code, 304)438 def test_if_none_match_and_different_etag(self):439 self.req.META['HTTP_IF_NONE_MATCH'] = 'spam'440 self.resp['ETag'] = 'eggs'441 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)442 self.assertEqual(self.resp.status_code, 200)443 def test_if_none_match_and_redirect(self):444 self.req.META['HTTP_IF_NONE_MATCH'] = self.resp['ETag'] = 'spam'445 self.resp['Location'] = '/'446 self.resp.status_code = 301447 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)448 self.assertEqual(self.resp.status_code, 301)449 def test_if_none_match_and_client_error(self):450 self.req.META['HTTP_IF_NONE_MATCH'] = self.resp['ETag'] = 'spam'451 self.resp.status_code = 400452 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)453 self.assertEqual(self.resp.status_code, 400)454 # Tests for the Last-Modified header455 def test_if_modified_since_and_no_last_modified(self):456 self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'457 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)458 self.assertEqual(self.resp.status_code, 200)459 def test_no_if_modified_since_and_last_modified(self):460 self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:38:44 GMT'461 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)462 self.assertEqual(self.resp.status_code, 200)463 def test_if_modified_since_and_same_last_modified(self):464 self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'465 self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:38:44 GMT'466 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)467 self.assertEqual(self.resp.status_code, 304)468 def test_if_modified_since_and_last_modified_in_the_past(self):469 self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'470 self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:35:44 GMT'471 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)472 self.assertEqual(self.resp.status_code, 304)473 def test_if_modified_since_and_last_modified_in_the_future(self):474 self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'475 self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:41:44 GMT'476 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)477 self.assertEqual(self.resp.status_code, 200)478 def test_if_modified_since_and_redirect(self):479 self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'480 self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:35:44 GMT'481 self.resp['Location'] = '/'482 self.resp.status_code = 301483 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)484 self.assertEqual(self.resp.status_code, 301)485 def test_if_modified_since_and_client_error(self):486 self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'487 self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:35:44 GMT'488 self.resp.status_code = 400489 self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)490 self.assertEqual(self.resp.status_code, 400)491 def test_not_modified_headers(self):492 """493 The 304 Not Modified response should include only the headers required494 by section 4.1 of RFC 7232, Last-Modified, and the cookies.495 """496 self.req.META['HTTP_IF_NONE_MATCH'] = self.resp['ETag'] = '"spam"'497 self.resp['Date'] = 'Sat, 12 Feb 2011 17:35:44 GMT'498 self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:35:44 GMT'499 self.resp['Expires'] = 'Sun, 13 Feb 2011 17:35:44 GMT'500 self.resp['Vary'] = 'Cookie'501 self.resp['Cache-Control'] = 'public'502 self.resp['Content-Location'] = '/alt'503 self.resp['Content-Language'] = 'en' # shouldn't be preserved504 self.resp.set_cookie('key', 'value')505 new_response = ConditionalGetMiddleware().process_response(self.req, self.resp)506 self.assertEqual(new_response.status_code, 304)507 for header in ('Cache-Control', 'Content-Location', 'Date', 'ETag', 'Expires', 'Last-Modified', 'Vary'):508 self.assertEqual(new_response[header], self.resp[header])509 self.assertEqual(new_response.cookies, self.resp.cookies)510 self.assertNotIn('Content-Language', new_response)511 def test_no_unsafe(self):512 """513 ConditionalGetMiddleware shouldn't return a conditional response on an514 unsafe request. A response has already been generated by the time515 ConditionalGetMiddleware is called, so it's too late to return a 412516 Precondition Failed.517 """518 get_response = ConditionalGetMiddleware().process_response(self.req, self.resp)519 etag = get_response['ETag']520 put_request = RequestFactory().put('/', HTTP_IF_MATCH=etag)521 put_response = HttpResponse(status=200)522 conditional_get_response = ConditionalGetMiddleware().process_response(put_request, put_response)523 self.assertEqual(conditional_get_response.status_code, 200) # should never be a 412524 def test_no_head(self):525 """526 ConditionalGetMiddleware shouldn't compute and return an ETag on a527 HEAD request since it can't do so accurately without access to the528 response body of the corresponding GET.529 """530 request = RequestFactory().head('/')531 response = HttpResponse(status=200)532 conditional_get_response = ConditionalGetMiddleware().process_response(request, response)533 self.assertNotIn('ETag', conditional_get_response)534class XFrameOptionsMiddlewareTest(SimpleTestCase):535 """536 Tests for the X-Frame-Options clickjacking prevention middleware.537 """538 def test_same_origin(self):539 """540 The X_FRAME_OPTIONS setting can be set to SAMEORIGIN to have the541 middleware use that value for the HTTP header.542 """543 with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):544 r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())545 self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')546 with override_settings(X_FRAME_OPTIONS='sameorigin'):547 r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())548 self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')549 def test_deny(self):550 """551 The X_FRAME_OPTIONS setting can be set to DENY to have the middleware552 use that value for the HTTP header.553 """554 with override_settings(X_FRAME_OPTIONS='DENY'):555 r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())556 self.assertEqual(r['X-Frame-Options'], 'DENY')557 with override_settings(X_FRAME_OPTIONS='deny'):558 r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())559 self.assertEqual(r['X-Frame-Options'], 'DENY')560 def test_defaults_sameorigin(self):561 """562 If the X_FRAME_OPTIONS setting is not set then it defaults to563 SAMEORIGIN.564 """565 with override_settings(X_FRAME_OPTIONS=None):566 del settings.X_FRAME_OPTIONS # restored by override_settings567 r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())568 self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')569 def test_dont_set_if_set(self):570 """571 If the X-Frame-Options header is already set then the middleware does572 not attempt to override it.573 """574 with override_settings(X_FRAME_OPTIONS='DENY'):575 response = HttpResponse()576 response['X-Frame-Options'] = 'SAMEORIGIN'577 r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)578 self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')579 with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):580 response = HttpResponse()581 response['X-Frame-Options'] = 'DENY'582 r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)583 self.assertEqual(r['X-Frame-Options'], 'DENY')584 def test_response_exempt(self):585 """586 If the response has an xframe_options_exempt attribute set to False587 then it still sets the header, but if it's set to True then it doesn't.588 """589 with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):590 response = HttpResponse()591 response.xframe_options_exempt = False592 r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)593 self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')594 response = HttpResponse()595 response.xframe_options_exempt = True596 r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)597 self.assertIsNone(r.get('X-Frame-Options'))598 def test_is_extendable(self):599 """600 The XFrameOptionsMiddleware method that determines the X-Frame-Options601 header value can be overridden based on something in the request or602 response.603 """604 class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware):605 # This is just an example for testing purposes...606 def get_xframe_options_value(self, request, response):607 if getattr(request, 'sameorigin', False):608 return 'SAMEORIGIN'609 if getattr(response, 'sameorigin', False):610 return 'SAMEORIGIN'611 return 'DENY'612 with override_settings(X_FRAME_OPTIONS='DENY'):613 response = HttpResponse()614 response.sameorigin = True615 r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), response)616 self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')617 request = HttpRequest()618 request.sameorigin = True619 r = OtherXFrameOptionsMiddleware().process_response(request, HttpResponse())620 self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')621 with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):622 r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())623 self.assertEqual(r['X-Frame-Options'], 'DENY')624class GZipMiddlewareTest(SimpleTestCase):625 """626 Tests the GZipMiddleware.627 """628 short_string = b"This string is too short to be worth compressing."629 compressible_string = b'a' * 500630 incompressible_string = b''.join(int2byte(random.randint(0, 255)) for _ in range(500))631 sequence = [b'a' * 500, b'b' * 200, b'a' * 300]632 sequence_unicode = ['a' * 500, 'é' * 200, 'a' * 300]633 def setUp(self):634 self.req = RequestFactory().get('/')635 self.req.META['HTTP_ACCEPT_ENCODING'] = 'gzip, deflate'636 self.req.META['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1'637 self.resp = HttpResponse()638 self.resp.status_code = 200639 self.resp.content = self.compressible_string640 self.resp['Content-Type'] = 'text/html; charset=UTF-8'641 self.stream_resp = StreamingHttpResponse(self.sequence)642 self.stream_resp['Content-Type'] = 'text/html; charset=UTF-8'643 self.stream_resp_unicode = StreamingHttpResponse(self.sequence_unicode)644 self.stream_resp_unicode['Content-Type'] = 'text/html; charset=UTF-8'645 @staticmethod646 def decompress(gzipped_string):647 with gzip.GzipFile(mode='rb', fileobj=BytesIO(gzipped_string)) as f:648 return f.read()649 @staticmethod650 def get_mtime(gzipped_string):651 with gzip.GzipFile(mode='rb', fileobj=BytesIO(gzipped_string)) as f:652 f.read() # must read the data before accessing the header653 return f.mtime654 def test_compress_response(self):655 """656 Compression is performed on responses with compressible content.657 """658 r = GZipMiddleware().process_response(self.req, self.resp)659 self.assertEqual(self.decompress(r.content), self.compressible_string)660 self.assertEqual(r.get('Content-Encoding'), 'gzip')661 self.assertEqual(r.get('Content-Length'), str(len(r.content)))662 def test_compress_streaming_response(self):663 """664 Compression is performed on responses with streaming content.665 """666 r = GZipMiddleware().process_response(self.req, self.stream_resp)667 self.assertEqual(self.decompress(b''.join(r)), b''.join(self.sequence))668 self.assertEqual(r.get('Content-Encoding'), 'gzip')669 self.assertFalse(r.has_header('Content-Length'))670 def test_compress_streaming_response_unicode(self):671 """672 Compression is performed on responses with streaming Unicode content.673 """674 r = GZipMiddleware().process_response(self.req, self.stream_resp_unicode)675 self.assertEqual(676 self.decompress(b''.join(r)),677 b''.join(x.encode() for x in self.sequence_unicode)678 )679 self.assertEqual(r.get('Content-Encoding'), 'gzip')680 self.assertFalse(r.has_header('Content-Length'))681 def test_compress_file_response(self):682 """683 Compression is performed on FileResponse.684 """685 with open(__file__, 'rb') as file1:686 file_resp = FileResponse(file1)687 file_resp['Content-Type'] = 'text/html; charset=UTF-8'688 r = GZipMiddleware().process_response(self.req, file_resp)689 with open(__file__, 'rb') as file2:690 self.assertEqual(self.decompress(b''.join(r)), file2.read())691 self.assertEqual(r.get('Content-Encoding'), 'gzip')692 self.assertIsNot(r.file_to_stream, file1)693 def test_compress_non_200_response(self):694 """695 Compression is performed on responses with a status other than 200696 (#10762).697 """698 self.resp.status_code = 404699 r = GZipMiddleware().process_response(self.req, self.resp)700 self.assertEqual(self.decompress(r.content), self.compressible_string)701 self.assertEqual(r.get('Content-Encoding'), 'gzip')702 def test_no_compress_short_response(self):703 """704 Compression isn't performed on responses with short content.705 """706 self.resp.content = self.short_string707 r = GZipMiddleware().process_response(self.req, self.resp)708 self.assertEqual(r.content, self.short_string)709 self.assertIsNone(r.get('Content-Encoding'))710 def test_no_compress_compressed_response(self):711 """712 Compression isn't performed on responses that are already compressed.713 """714 self.resp['Content-Encoding'] = 'deflate'715 r = GZipMiddleware().process_response(self.req, self.resp)716 self.assertEqual(r.content, self.compressible_string)717 self.assertEqual(r.get('Content-Encoding'), 'deflate')718 def test_no_compress_incompressible_response(self):719 """720 Compression isn't performed on responses with incompressible content.721 """722 self.resp.content = self.incompressible_string723 r = GZipMiddleware().process_response(self.req, self.resp)724 self.assertEqual(r.content, self.incompressible_string)725 self.assertIsNone(r.get('Content-Encoding'))726 def test_compress_deterministic(self):727 """728 Compression results are the same for the same content and don't729 include a modification time (since that would make the results730 of compression non-deterministic and prevent731 ConditionalGetMiddleware from recognizing conditional matches732 on gzipped content).733 """734 r1 = GZipMiddleware().process_response(self.req, self.resp)735 r2 = GZipMiddleware().process_response(self.req, self.resp)736 self.assertEqual(r1.content, r2.content)737 self.assertEqual(self.get_mtime(r1.content), 0)738 self.assertEqual(self.get_mtime(r2.content), 0)739@ignore_warnings(category=RemovedInDjango21Warning)740@override_settings(USE_ETAGS=True)741class ETagGZipMiddlewareTest(SimpleTestCase):742 """743 ETags are handled properly by GZipMiddleware.744 """745 rf = RequestFactory()746 compressible_string = b'a' * 500747 def test_strong_etag_modified(self):748 """749 GZipMiddleware makes a strong ETag weak.750 """751 request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate')752 response = HttpResponse(self.compressible_string)753 response['ETag'] = '"eggs"'754 gzip_response = GZipMiddleware().process_response(request, response)755 self.assertEqual(gzip_response['ETag'], 'W/"eggs"')756 def test_weak_etag_not_modified(self):757 """758 GZipMiddleware doesn't modify a weak ETag.759 """760 request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate')761 response = HttpResponse(self.compressible_string)762 response['ETag'] = 'W/"eggs"'763 gzip_response = GZipMiddleware().process_response(request, response)764 self.assertEqual(gzip_response['ETag'], 'W/"eggs"')765 def test_etag_match(self):766 """767 GZipMiddleware allows 304 Not Modified responses.768 """769 request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate')770 response = GZipMiddleware().process_response(771 request,772 ConditionalGetMiddleware().process_response(request, HttpResponse(self.compressible_string))773 )774 gzip_etag = response['ETag']775 next_request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate', HTTP_IF_NONE_MATCH=gzip_etag)776 next_response = ConditionalGetMiddleware().process_response(777 next_request,778 HttpResponse(self.compressible_string)779 )...

Full Screen

Full Screen

text.py

Source:text.py Github

copy

Full Screen

...21 def _concat_result(self, first, second):22 return first + second23 def handle_text(self, client_context, text):24 if self._client:25 self._client.process_response(client_context, text['text'])26 return text['text']27 def handle_url_button(self, client_context, button):28 rendered = "%s, click %s" % (button['text'], button['url'])29 if self._client:30 self._client.process_response(client_context, rendered)31 return rendered32 def handle_postback_button(self, client_context, button):33 if self._client:34 self._client.process_response(client_context, button['postback'])35 return button['postback']36 def handle_link(self, client_context, link):37 rendered = "Open in browser, click %s" % link['url']38 if self._client:39 self._client.process_response(client_context, rendered)40 return rendered41 def handle_image(self, client_context, image):42 rendered = "To see the image, click %s" % image['url']43 if self._client:44 self._client.process_response(client_context, rendered)45 return rendered46 def handle_video(self, client_context, video):47 rendered = "To see the video, click %s" % video['url']48 if self._client:49 self._client.process_response(client_context, rendered)50 return rendered51 def _format_card(self, client_context, card):52 del client_context53 rendered = "Image: %s\nTitle: %s\nSubtitle: %s\n" % (card['image'], card['title'], card['subtitle'])54 for button in card['buttons']:55 rendered += "---------------------------------------\n"56 if button['url'] is not None:57 rendered += "%s : %s" % (button['text'], button['url'])58 else:59 rendered += "%s : %s" % (button['text'], button['postback'])60 rendered += "\n---------------------------------------\n"61 return rendered62 def handle_card(self, client_context, card):63 rendered = self._format_card(client_context, card)64 if self._client:65 self._client.process_response(client_context, rendered)66 return rendered67 def handle_carousel(self, client_context, carousel):68 rendered = ""69 for card in carousel['cards']:70 rendered += "=========================================\n"71 rendered += self._format_card(client_context, card)72 rendered += "=========================================\n"73 self._client.process_response(client_context, rendered)74 def handle_reply(self, client_context, reply):75 if reply['postback'] is not None:76 if self._client:77 self._client.process_response(client_context, reply['postback'])78 return reply['postback']79 else:80 if self._client:81 self._client.process_response(client_context, reply['text'])82 return reply['text']83 def handle_delay(self, client_context, delay):84 rendered = "..."85 if self._client:86 self._client.process_response(client_context, rendered)87 delay = int(delay['seconds'])88 time.sleep(delay)89 return rendered90 def handle_split(self, client_context, split):91 self._client.process_response(client_context, "\n")92 return "\n"93 def handle_list(self, client_context, lst):94 rendered = ""95 for item in lst.get('items', []):96 rendered += "> %s\n" % item['text']97 self._client.process_response(client_context, rendered)98 def handle_ordered_list(self, client_context, lst):99 rendered = ""100 count = 1101 for item in lst.get('items', []):102 rendered += "%d. %s\n" % (count, item['text'])103 count += 1104 if self._client:105 self._client.process_response(client_context, rendered)106 return rendered107 def handle_location(self, client_context, location):108 del location109 rendered = ""110 if self._client:111 self._client.process_response(client_context, rendered)112 return rendered113 def handle_tts(self, client_context, tts):114 del client_context115 del tts...

Full Screen

Full Screen

json.py

Source:json.py Github

copy

Full Screen

...20 def _concat_result(self, first, second):21 return dict(first, **second)22 def handle_text(self, client_context, text):23 if self._client:24 return self._client.process_response(client_context, text)25 return text26 def handle_url_button(self, client_context, button):27 if self._client:28 self._client.process_response(client_context, button)29 return button30 def handle_postback_button(self, client_context, button):31 if self._client:32 self._client.process_response(client_context, button)33 return button34 def handle_link(self, client_context, link):35 if self._client:36 self._client.process_response(client_context, link)37 return link38 def handle_image(self, client_context, image):39 if self._client:40 self._client.process_response(client_context, image)41 return image42 def handle_video(self, client_context, video):43 if self._client:44 self._client.process_response(client_context, video)45 return video46 def handle_card(self, client_context, card):47 if self._client:48 self._client.process_response(client_context, card)49 return card50 def handle_carousel(self, client_context, carousel):51 if self._client:52 self._client.process_response(client_context, carousel)53 return carousel54 def handle_reply(self, client_context, reply):55 if self._client:56 self._client.process_response(client_context, reply)57 return reply58 def handle_delay(self, client_context, delay):59 if self._client:60 self._client.process_response(client_context, delay)61 return delay62 def handle_split(self, client_context, split):63 if self._client:64 self._client.process_response(client_context, split)65 return split66 def handle_list(self, client_context, lst):67 if self._client:68 self._client.process_response(client_context, lst)69 return lst70 def handle_ordered_list(self, client_context, lst):71 if self._client:72 self._client.process_response(client_context, lst)73 return lst74 def handle_location(self, client_context, location):75 if self._client:76 self._client.process_response(client_context, location)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

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

Run autotest automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful