How to use status_code method in locust

Best Python code snippet using locust

page_load_tests.py

Source:page_load_tests.py Github

copy

Full Screen

1from askbot.search.state_manager import SearchState2from django.test import signals3from django.conf import settings4from django.core.urlresolvers import reverse5from django.core import management6from django.core.cache.backends.dummy import DummyCache7from django.core import cache8import coffin9import coffin.template10from askbot import models11from askbot.utils.slug import slugify12from askbot.deployment import package_utils13from askbot.tests.utils import AskbotTestCase14from askbot.conf import settings as askbot_settings15from askbot.tests.utils import skipIf16def patch_jinja2():17 from jinja2 import Template18 ORIG_JINJA2_RENDERER = Template.render19 def instrumented_render(template_object, *args, **kwargs):20 context = dict(*args, **kwargs)21 signals.template_rendered.send(22 sender=template_object,23 template=template_object,24 context=context25 )26 return ORIG_JINJA2_RENDERER(template_object, *args, **kwargs)27 Template.render = instrumented_render28(CMAJOR, CMINOR, CMICRO) = package_utils.get_coffin_version()29if CMAJOR == 0 and CMINOR == 3 and CMICRO < 4:30 patch_jinja2()31class PageLoadTestCase(AskbotTestCase):32 #############################################33 #34 # INFO: We load test data once for all tests in this class (setUpClass + cleanup in tearDownClass)35 #36 # We also disable (by overriding _fixture_setup/teardown) per-test fixture setup,37 # which by default flushes the database for non-transactional db engines like MySQL+MyISAM.38 # For transactional engines it only messes with transactions, but to keep things uniform39 # for both types of databases we disable it all.40 #41 @classmethod42 def setUpClass(cls):43 management.call_command('flush', verbosity=0, interactive=False)44 management.call_command('askbot_add_test_content', verbosity=0, interactive=False)45 @classmethod46 def tearDownClass(self):47 management.call_command('flush', verbosity=0, interactive=False)48 def _fixture_setup(self):49 pass50 def _fixture_teardown(self):51 pass52 #############################################53 def setUp(self):54 self.old_cache = cache.cache55 #Disable caching (to not interfere with production cache,56 #not sure if that's possible but let's not risk it)57 cache.cache = DummyCache('', {}) 58 def tearDown(self):59 cache.cache = self.old_cache # Restore caching60 def try_url(61 self,62 url_name, status_code=200, template=None,63 kwargs={}, redirect_url=None, follow=False,64 data={}, plain_url_passed=False):65 if plain_url_passed:66 url = url_name67 else:68 url = reverse(url_name, kwargs=kwargs)69 if status_code == 302:70 url_info = 'redirecting to LOGIN_URL in closed_mode: %s' % url71 else:72 url_info = 'getting url %s' % url73 if data:74 url_info += '?' + '&'.join(['%s=%s' % (k, v) for k, v in data.iteritems()])75 print url_info76 # if redirect expected, but we wont' follow77 if status_code == 302 and follow:78 response = self.client.get(url, data=data)79 self.assertTrue(settings.LOGIN_URL in response['Location'])80 return81 r = self.client.get(url, data=data, follow=follow)82 if hasattr(self.client, 'redirect_chain'):83 print 'redirect chain: %s' % ','.join(self.client.redirect_chain)84 self.assertEqual(r.status_code, status_code)85 if template and status_code != 302:86 if isinstance(r.template, coffin.template.Template):87 self.assertEqual(r.template.name, template)88 elif isinstance(r.template, list):89 #asuming that there is more than one template90 template_names = ','.join([t.name for t in r.template])91 print 'templates are %s' % template_names92 # The following code is no longer relevant because we're using93 # additional templates for cached fragments [e.g. thread.get_summary_html()]94# if follow == False:95# self.fail(96# ('Have issue accessing %s. '97# 'This should not have happened, '98# 'since you are not expecting a redirect '99# 'i.e. follow == False, there should be only '100# 'one template') % url101# )102#103# self.assertEqual(r.template[0].name, template)104 self.assertIn(template, [t.name for t in r.template])105 else:106 raise Exception('unexpected error while runnig test')107 def test_index(self):108 #todo: merge this with all reader url tests109 response = self.client.get(reverse('index'), follow=True)110 self.assertEqual(response.status_code, 200)111 self.failUnless(len(response.redirect_chain) == 1)112 self.failUnless(response.redirect_chain[0][0].endswith('/questions/'))113 self.assertTrue(isinstance(response.template, list))114 self.assertIn('main_page.html', [t.name for t in response.template])115 def proto_test_ask_page(self, allow_anonymous, status_code):116 prev_setting = askbot_settings.ALLOW_POSTING_BEFORE_LOGGING_IN117 askbot_settings.update('ALLOW_POSTING_BEFORE_LOGGING_IN', allow_anonymous)118 self.try_url(119 'ask',120 status_code = status_code,121 template = 'ask.html'122 )123 askbot_settings.update('ALLOW_POSTING_BEFORE_LOGGING_IN', prev_setting)124 def test_ask_page_allowed_anonymous(self):125 self.proto_test_ask_page(True, 200)126 def test_ask_page_disallowed_anonymous(self):127 self.proto_test_ask_page(False, 302)128 def proto_test_non_user_urls(self, status_code):129 """test all reader views thoroughly130 on non-crashiness (no correcteness tests here)131 """132 self.try_url('sitemap')133 self.try_url(134 'feeds',135 status_code=status_code,136 kwargs={'url':'rss'})137 self.try_url(138 'feeds',139 kwargs={'url':'rss'},140 data={'tags':'one-tag'},141 status_code=status_code)142 #self.try_url(143 # 'feeds',144 # kwargs={'url':'question'},145 # status_code=status_code)146 self.try_url(147 'about',148 status_code=status_code,149 template='static_page.html')150 self.try_url(151 'privacy',152 status_code=status_code,153 template='static_page.html')154 self.try_url('logout', template='authopenid/logout.html')155 #todo: test different tabs156 self.try_url(157 'tags',158 status_code=status_code,159 template='tags.html')160 self.try_url(161 'tags',162 status_code=status_code,163 data={'sort':'name'}, template='tags.html')164 self.try_url(165 'tags',166 status_code=status_code,167 data={'sort':'used'}, template='tags.html')168 self.try_url(169 'badges',170 status_code=status_code,171 template='badges.html')172 self.try_url(173 'answer_revisions',174 status_code=status_code,175 template='revisions.html',176 kwargs={'id': models.Post.objects.get_answers().order_by('id')[0].id}177 )178 #todo: test different sort methods and scopes179 self.try_url(180 'questions',181 status_code=status_code,182 template='main_page.html'183 )184 self.try_url(185 url_name=reverse('questions') + SearchState.get_empty().change_scope('unanswered').query_string(),186 plain_url_passed=True,187 status_code=status_code,188 template='main_page.html',189 )190 self.try_url(191 url_name=reverse('questions') + SearchState.get_empty().change_scope('favorite').query_string(),192 plain_url_passed=True,193 status_code=status_code,194 template='main_page.html'195 )196 self.try_url(197 url_name=reverse('questions') + SearchState.get_empty().change_scope('unanswered').change_sort('age-desc').query_string(),198 plain_url_passed=True,199 status_code=status_code,200 template='main_page.html'201 )202 self.try_url(203 url_name=reverse('questions') + SearchState.get_empty().change_scope('unanswered').change_sort('age-asc').query_string(),204 plain_url_passed=True,205 status_code=status_code,206 template='main_page.html'207 )208 self.try_url(209 url_name=reverse('questions') + SearchState.get_empty().change_scope('unanswered').change_sort('activity-desc').query_string(),210 plain_url_passed=True,211 status_code=status_code,212 template='main_page.html'213 )214 self.try_url(215 url_name=reverse('questions') + SearchState.get_empty().change_scope('unanswered').change_sort('activity-asc').query_string(),216 plain_url_passed=True,217 status_code=status_code,218 template='main_page.html'219 )220 self.try_url(221 url_name=reverse('questions') + SearchState.get_empty().change_sort('answers-desc').query_string(),222 plain_url_passed=True,223 status_code=status_code,224 template='main_page.html'225 )226 self.try_url(227 url_name=reverse('questions') + SearchState.get_empty().change_sort('answers-asc').query_string(),228 plain_url_passed=True,229 status_code=status_code,230 template='main_page.html'231 )232 self.try_url(233 url_name=reverse('questions') + SearchState.get_empty().change_sort('votes-desc').query_string(),234 plain_url_passed=True,235 status_code=status_code,236 template='main_page.html'237 )238 self.try_url(239 url_name=reverse('questions') + SearchState.get_empty().change_sort('votes-asc').query_string(),240 plain_url_passed=True,241 status_code=status_code,242 template='main_page.html'243 )244 self.try_url(245 'question',246 status_code=status_code,247 kwargs={'id':1}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way248 follow=True,249 template='question.html'250 )251 self.try_url(252 'question',253 status_code=status_code,254 kwargs={'id':2}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way255 follow=True,256 template='question.html'257 )258 self.try_url(259 'question',260 status_code=status_code,261 kwargs={'id':3}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way262 follow=True,263 template='question.html'264 )265 self.try_url(266 'question_revisions',267 status_code=status_code,268 kwargs={'id':40}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way269 template='revisions.html'270 )271 self.try_url('users',272 status_code=status_code,273 template='users.html'274 )275 self.try_url(276 'widget_questions',277 status_code = status_code,278 data={'tags': 'tag-1-0'},279 template='question_widget.html',280 )281 #todo: really odd naming conventions for sort methods282 self.try_url(283 'users',284 status_code=status_code,285 template='users.html',286 data={'sort':'reputation'},287 )288 self.try_url(289 'users',290 status_code=status_code,291 template='users.html',292 data={'sort':'newest'},293 )294 self.try_url(295 'users',296 status_code=status_code,297 template='users.html',298 data={'sort':'last'},299 )300 self.try_url(301 'users',302 status_code=status_code,303 template='users.html',304 data={'sort':'user'},305 )306 self.try_url(307 'users',308 status_code=status_code,309 template='users.html',310 data={'sort':'reputation', 'page':2},311 )312 self.try_url(313 'users',314 status_code=status_code,315 template='users.html',316 data={'sort':'newest', 'page':2},317 )318 self.try_url(319 'users',320 status_code=status_code,321 template='users.html',322 data={'sort':'last', 'page':2},323 )324 self.try_url(325 'users',326 status_code=status_code,327 template='users.html',328 data={'sort':'user', 'page':2},329 )330 self.try_url(331 'users',332 status_code=status_code,333 template='users.html',334 data={'sort':'reputation', 'page':1},335 )336 self.try_url(337 'users',338 status_code=status_code,339 template='users.html',340 data={'sort':'newest', 'page':1},341 )342 self.try_url(343 'users',344 status_code=status_code,345 template='users.html',346 data={'sort':'last', 'page':1},347 )348 self.try_url(349 'users',350 status_code=status_code,351 template='users.html',352 data={'sort':'user', 'page':1},353 )354 self.try_url(355 'edit_user',356 template='authopenid/signin.html',357 kwargs={'id':4}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way358 status_code=status_code,359 follow=True,360 )361 self.try_url(362 'faq',363 template='faq_static.html',364 status_code=status_code,365 )366 def test_non_user_urls(self):367 self.proto_test_non_user_urls(status_code=200)368 @skipIf('askbot.middleware.forum_mode.ForumModeMiddleware' \369 not in settings.MIDDLEWARE_CLASSES,370 'no ForumModeMiddleware set')371 def test_non_user_urls_in_closed_forum_mode(self):372 askbot_settings.ASKBOT_CLOSED_FORUM_MODE = True373 self.proto_test_non_user_urls(status_code=302)374 askbot_settings.ASKBOT_CLOSED_FORUM_MODE = False375 #def test_non_user_urls_logged_in(self):376 #user = User.objects.get(id=1)377 #somehow login this user378 #self.proto_test_non_user_urls()379 def proto_test_user_urls(self, status_code):380 user = models.User.objects.get(id=2) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way381 name_slug = slugify(user.username)382 self.try_url(383 'user_profile',384 kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way385 status_code=status_code,386 data={'sort':'stats'},387 template='user_profile/user_stats.html'388 )389 self.try_url(390 'user_profile',391 kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way392 status_code=status_code,393 data={'sort':'recent'},394 template='user_profile/user_recent.html'395 )396 self.try_url(397 'user_profile',398 kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way399 status_code=status_code,400 data={'sort':'inbox'},401 template='authopenid/signin.html',402 follow=True403 )404 self.try_url(405 'user_profile',406 kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way407 status_code=status_code,408 data={'sort':'reputation'},409 template='user_profile/user_reputation.html'410 )411 self.try_url(412 'user_profile',413 kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way414 status_code=status_code,415 data={'sort':'votes'},416 template='authopenid/signin.html',417 follow = True418 )419 self.try_url(420 'user_profile',421 kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way422 status_code=status_code,423 data={'sort':'favorites'},424 template='user_profile/user_favorites.html'425 )426 self.try_url(427 'user_profile',428 kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way429 status_code=status_code,430 data={'sort':'email_subscriptions'},431 template='authopenid/signin.html',432 follow = True433 )434 def test_user_urls(self):435 self.proto_test_user_urls(status_code=200)436 @skipIf('askbot.middleware.forum_mode.ForumModeMiddleware' \437 not in settings.MIDDLEWARE_CLASSES,438 'no ForumModeMiddleware set')439 def test_user_urls_in_closed_forum_mode(self):440 askbot_settings.ASKBOT_CLOSED_FORUM_MODE = True441 self.proto_test_user_urls(status_code=302)442 askbot_settings.ASKBOT_CLOSED_FORUM_MODE = False443 def test_user_urls_logged_in(self):444 user = models.User.objects.get(id=2) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way445 name_slug = slugify(user.username)446 #works only with builtin django_authopenid447 self.client.login(method = 'force', user_id = 2) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way448 self.try_url(449 'user_subscriptions',450 kwargs = {'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way451 template = 'user_profile/user_email_subscriptions.html'452 )453 self.client.logout()454 def test_inbox_page(self):455 asker = models.User.objects.get(id = 2) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way456 question = asker.post_question(457 title = 'How can this happen?',458 body_text = 'This is the body of my question',459 tags = 'question answer test',460 )461 responder = models.User.objects.get(id = 3) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way462 responder.post_answer(463 question = question,464 body_text = 'this is the answer text'465 )466 self.client.login(method = 'force', user_id = asker.id)467 self.try_url(468 'user_profile',469 kwargs={'id': asker.id, 'slug': slugify(asker.username)},470 data={'sort':'inbox'},471 template='user_profile/user_inbox.html',472 )473class AvatarTests(AskbotTestCase):474 def test_avatar_for_two_word_user_works(self):475 if 'avatar' in settings.INSTALLED_APPS:476 self.user = self.create_user('john doe')477 response = self.client.get(478 'avatar_render_primary',479 kwargs = {'user': 'john doe', 'size': 48}480 )481class QuestionPageRedirectTests(AskbotTestCase):482 def setUp(self):483 self.create_user()484 self.q = self.post_question()485 self.q.old_question_id = 101486 self.q.save()487 self.a = self.post_answer(question=self.q)488 self.a.old_answer_id = 201489 self.a.save()490 self.c = self.post_comment(parent_post=self.a)491 self.c.old_comment_id = 301492 self.c.save()493 def test_show_bare_question(self):494 resp = self.client.get(self.q.get_absolute_url())495 self.assertEqual(200, resp.status_code)496 self.assertEqual(self.q, resp.context['question'])497 url = reverse('question', kwargs={'id': self.q.id})498 resp = self.client.get(url)499 self.assertRedirects(500 resp,501 expected_url=self.q.get_absolute_url()502 )503 url = reverse('question', kwargs={'id': 101})504 resp = self.client.get(url)505 url = reverse('question', kwargs={'id': self.q.id}) + self.q.slug + '/'# redirect uses the new question.id !506 self.assertRedirects(resp, expected_url=url)507 url = reverse('question', kwargs={'id': 101}) + self.q.slug + '/'508 resp = self.client.get(url)509 self.assertEqual(200, resp.status_code)510 self.assertEqual(self.q, resp.context['question'])511 def test_show_answer(self):512 resp = self.client.get(self.a.get_absolute_url())513 self.assertEqual(200, resp.status_code)514 self.assertEqual(self.q, resp.context['question'])515 self.assertEqual(self.a, resp.context['show_post'])516 url = reverse('question', kwargs={'id': self.q.id})517 resp = self.client.get(url, data={'answer': self.a.id})518 url = self.q.get_absolute_url()519 self.assertRedirects(resp, expected_url=url + '?answer=%d' % self.a.id)520 resp = self.client.get(url, data={'answer': self.a.id})521 self.assertEqual(200, resp.status_code)522 self.assertEqual(self.q, resp.context['question'])523 self.assertEqual(self.a, resp.context['show_post'])524 #test redirect from old question525 url = reverse('question', kwargs={'id': 101}) + self.q.slug + '/'526 resp = self.client.get(url, data={'answer': 201})527 self.assertRedirects(resp, expected_url=self.a.get_absolute_url())528 def test_show_comment(self):529 resp = self.client.get(self.c.get_absolute_url())530 self.assertEqual(200, resp.status_code)531 self.assertEqual(self.q, resp.context['question'])532 self.assertEqual(self.a, resp.context['show_post'])533 self.assertEqual(self.c, resp.context['show_comment'])534 url = self.q.get_absolute_url()535 resp = self.client.get(url, data={'comment': self.c.id})536 self.assertEqual(200, resp.status_code)537 resp = self.client.get(url, data={'comment': self.c.id})538 self.assertEqual(200, resp.status_code)539 self.assertEqual(self.q, resp.context['question'])540 self.assertEqual(self.a, resp.context['show_post'])541 self.assertEqual(self.c, resp.context['show_comment'])542 url = self.q.get_absolute_url()543 #point to a non-existing comment544 resp = self.client.get(url, data={'comment': 100301})545 self.assertRedirects(resp, expected_url = self.q.get_absolute_url())546class CommandViewTests(AskbotTestCase):547 def test_get_tag_wiki_text_succeeds(self):548 tag1 = self.create_tag('tag1')549 response = self.client.get(550 reverse('load_tag_wiki_text'),551 data = {'tag_id': tag1.id}552 )553 self.assertEqual(response.status_code, 200)554 def test_get_tag_wiki_text_fails(self):555 tag1 = self.create_tag('tag1')556 response = self.client.get(reverse('load_tag_wiki_text'))557 self.assertEqual(response.status_code, 400)#bad request...

Full Screen

Full Screen

web_exceptions.py

Source:web_exceptions.py Github

copy

Full Screen

1import warnings2from typing import Any, Dict, Iterable, List, Optional, Set # noqa3from yarl import URL4from .typedefs import LooseHeaders, StrOrURL5from .web_response import Response6__all__ = (7 "HTTPException",8 "HTTPError",9 "HTTPRedirection",10 "HTTPSuccessful",11 "HTTPOk",12 "HTTPCreated",13 "HTTPAccepted",14 "HTTPNonAuthoritativeInformation",15 "HTTPNoContent",16 "HTTPResetContent",17 "HTTPPartialContent",18 "HTTPMultipleChoices",19 "HTTPMovedPermanently",20 "HTTPFound",21 "HTTPSeeOther",22 "HTTPNotModified",23 "HTTPUseProxy",24 "HTTPTemporaryRedirect",25 "HTTPPermanentRedirect",26 "HTTPClientError",27 "HTTPBadRequest",28 "HTTPUnauthorized",29 "HTTPPaymentRequired",30 "HTTPForbidden",31 "HTTPNotFound",32 "HTTPMethodNotAllowed",33 "HTTPNotAcceptable",34 "HTTPProxyAuthenticationRequired",35 "HTTPRequestTimeout",36 "HTTPConflict",37 "HTTPGone",38 "HTTPLengthRequired",39 "HTTPPreconditionFailed",40 "HTTPRequestEntityTooLarge",41 "HTTPRequestURITooLong",42 "HTTPUnsupportedMediaType",43 "HTTPRequestRangeNotSatisfiable",44 "HTTPExpectationFailed",45 "HTTPMisdirectedRequest",46 "HTTPUnprocessableEntity",47 "HTTPFailedDependency",48 "HTTPUpgradeRequired",49 "HTTPPreconditionRequired",50 "HTTPTooManyRequests",51 "HTTPRequestHeaderFieldsTooLarge",52 "HTTPUnavailableForLegalReasons",53 "HTTPServerError",54 "HTTPInternalServerError",55 "HTTPNotImplemented",56 "HTTPBadGateway",57 "HTTPServiceUnavailable",58 "HTTPGatewayTimeout",59 "HTTPVersionNotSupported",60 "HTTPVariantAlsoNegotiates",61 "HTTPInsufficientStorage",62 "HTTPNotExtended",63 "HTTPNetworkAuthenticationRequired",64)65############################################################66# HTTP Exceptions67############################################################68class HTTPException(Response, Exception):69 # You should set in subclasses:70 # status = 20071 status_code = -172 empty_body = False73 __http_exception__ = True74 def __init__(75 self,76 *,77 headers: Optional[LooseHeaders] = None,78 reason: Optional[str] = None,79 body: Any = None,80 text: Optional[str] = None,81 content_type: Optional[str] = None,82 ) -> None:83 if body is not None:84 warnings.warn(85 "body argument is deprecated for http web exceptions",86 DeprecationWarning,87 )88 Response.__init__(89 self,90 status=self.status_code,91 headers=headers,92 reason=reason,93 body=body,94 text=text,95 content_type=content_type,96 )97 Exception.__init__(self, self.reason)98 if self.body is None and not self.empty_body:99 self.text = f"{self.status}: {self.reason}"100 def __bool__(self) -> bool:101 return True102class HTTPError(HTTPException):103 """Base class for exceptions with status codes in the 400s and 500s."""104class HTTPRedirection(HTTPException):105 """Base class for exceptions with status codes in the 300s."""106class HTTPSuccessful(HTTPException):107 """Base class for exceptions with status codes in the 200s."""108class HTTPOk(HTTPSuccessful):109 status_code = 200110class HTTPCreated(HTTPSuccessful):111 status_code = 201112class HTTPAccepted(HTTPSuccessful):113 status_code = 202114class HTTPNonAuthoritativeInformation(HTTPSuccessful):115 status_code = 203116class HTTPNoContent(HTTPSuccessful):117 status_code = 204118 empty_body = True119class HTTPResetContent(HTTPSuccessful):120 status_code = 205121 empty_body = True122class HTTPPartialContent(HTTPSuccessful):123 status_code = 206124############################################################125# 3xx redirection126############################################################127class _HTTPMove(HTTPRedirection):128 def __init__(129 self,130 location: StrOrURL,131 *,132 headers: Optional[LooseHeaders] = None,133 reason: Optional[str] = None,134 body: Any = None,135 text: Optional[str] = None,136 content_type: Optional[str] = None,137 ) -> None:138 if not location:139 raise ValueError("HTTP redirects need a location to redirect to.")140 super().__init__(141 headers=headers,142 reason=reason,143 body=body,144 text=text,145 content_type=content_type,146 )147 self.headers["Location"] = str(URL(location))148 self.location = location149class HTTPMultipleChoices(_HTTPMove):150 status_code = 300151class HTTPMovedPermanently(_HTTPMove):152 status_code = 301153class HTTPFound(_HTTPMove):154 status_code = 302155# This one is safe after a POST (the redirected location will be156# retrieved with GET):157class HTTPSeeOther(_HTTPMove):158 status_code = 303159class HTTPNotModified(HTTPRedirection):160 # FIXME: this should include a date or etag header161 status_code = 304162 empty_body = True163class HTTPUseProxy(_HTTPMove):164 # Not a move, but looks a little like one165 status_code = 305166class HTTPTemporaryRedirect(_HTTPMove):167 status_code = 307168class HTTPPermanentRedirect(_HTTPMove):169 status_code = 308170############################################################171# 4xx client error172############################################################173class HTTPClientError(HTTPError):174 pass175class HTTPBadRequest(HTTPClientError):176 status_code = 400177class HTTPUnauthorized(HTTPClientError):178 status_code = 401179class HTTPPaymentRequired(HTTPClientError):180 status_code = 402181class HTTPForbidden(HTTPClientError):182 status_code = 403183class HTTPNotFound(HTTPClientError):184 status_code = 404185class HTTPMethodNotAllowed(HTTPClientError):186 status_code = 405187 def __init__(188 self,189 method: str,190 allowed_methods: Iterable[str],191 *,192 headers: Optional[LooseHeaders] = None,193 reason: Optional[str] = None,194 body: Any = None,195 text: Optional[str] = None,196 content_type: Optional[str] = None,197 ) -> None:198 allow = ",".join(sorted(allowed_methods))199 super().__init__(200 headers=headers,201 reason=reason,202 body=body,203 text=text,204 content_type=content_type,205 )206 self.headers["Allow"] = allow207 self.allowed_methods = set(allowed_methods) # type: Set[str]208 self.method = method.upper()209class HTTPNotAcceptable(HTTPClientError):210 status_code = 406211class HTTPProxyAuthenticationRequired(HTTPClientError):212 status_code = 407213class HTTPRequestTimeout(HTTPClientError):214 status_code = 408215class HTTPConflict(HTTPClientError):216 status_code = 409217class HTTPGone(HTTPClientError):218 status_code = 410219class HTTPLengthRequired(HTTPClientError):220 status_code = 411221class HTTPPreconditionFailed(HTTPClientError):222 status_code = 412223class HTTPRequestEntityTooLarge(HTTPClientError):224 status_code = 413225 def __init__(self, max_size: float, actual_size: float, **kwargs: Any) -> None:226 kwargs.setdefault(227 "text",228 "Maximum request body size {} exceeded, "229 "actual body size {}".format(max_size, actual_size),230 )231 super().__init__(**kwargs)232class HTTPRequestURITooLong(HTTPClientError):233 status_code = 414234class HTTPUnsupportedMediaType(HTTPClientError):235 status_code = 415236class HTTPRequestRangeNotSatisfiable(HTTPClientError):237 status_code = 416238class HTTPExpectationFailed(HTTPClientError):239 status_code = 417240class HTTPMisdirectedRequest(HTTPClientError):241 status_code = 421242class HTTPUnprocessableEntity(HTTPClientError):243 status_code = 422244class HTTPFailedDependency(HTTPClientError):245 status_code = 424246class HTTPUpgradeRequired(HTTPClientError):247 status_code = 426248class HTTPPreconditionRequired(HTTPClientError):249 status_code = 428250class HTTPTooManyRequests(HTTPClientError):251 status_code = 429252class HTTPRequestHeaderFieldsTooLarge(HTTPClientError):253 status_code = 431254class HTTPUnavailableForLegalReasons(HTTPClientError):255 status_code = 451256 def __init__(257 self,258 link: str,259 *,260 headers: Optional[LooseHeaders] = None,261 reason: Optional[str] = None,262 body: Any = None,263 text: Optional[str] = None,264 content_type: Optional[str] = None,265 ) -> None:266 super().__init__(267 headers=headers,268 reason=reason,269 body=body,270 text=text,271 content_type=content_type,272 )273 self.headers["Link"] = '<%s>; rel="blocked-by"' % link274 self.link = link275############################################################276# 5xx Server Error277############################################################278# Response status codes beginning with the digit "5" indicate cases in279# which the server is aware that it has erred or is incapable of280# performing the request. Except when responding to a HEAD request, the281# server SHOULD include an entity containing an explanation of the error282# situation, and whether it is a temporary or permanent condition. User283# agents SHOULD display any included entity to the user. These response284# codes are applicable to any request method.285class HTTPServerError(HTTPError):286 pass287class HTTPInternalServerError(HTTPServerError):288 status_code = 500289class HTTPNotImplemented(HTTPServerError):290 status_code = 501291class HTTPBadGateway(HTTPServerError):292 status_code = 502293class HTTPServiceUnavailable(HTTPServerError):294 status_code = 503295class HTTPGatewayTimeout(HTTPServerError):296 status_code = 504297class HTTPVersionNotSupported(HTTPServerError):298 status_code = 505299class HTTPVariantAlsoNegotiates(HTTPServerError):300 status_code = 506301class HTTPInsufficientStorage(HTTPServerError):302 status_code = 507303class HTTPNotExtended(HTTPServerError):304 status_code = 510305class HTTPNetworkAuthenticationRequired(HTTPServerError):...

Full Screen

Full Screen

test_client.py

Source:test_client.py Github

copy

Full Screen

1import os.path2import pytest3import sys4def setup_module(module):5 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))6class TestClient(object):7 def setup_method(self, method):8 from browsermobproxy.client import Client9 self.client = Client("localhost:9090")10 def teardown_method(self, method):11 self.client.close()12 def test_headers_type(self):13 """14 /proxy/:port/headers needs to take a dictionary15 """16 with pytest.raises(TypeError):17 self.client.headers(['foo'])18 def test_headers_content(self):19 """20 /proxy/:port/headers needs to take a dictionary21 and returns 200 when its successful22 """23 s = self.client.headers({'User-Agent': 'rubber ducks floating in a row'})24 assert(s == 200)25 def test_new_har(self):26 """27 /proxy/:port/har28 and returns 204 when creating a har with a particular name the first time29 and returns 200 and the previous har when creating one with the same name30 """31 status_code, har = self.client.new_har()32 assert(status_code == 204)33 assert(har is None)34 status_code, har = self.client.new_har()35 assert(status_code == 200)36 assert('log' in har)37 def test_new_har(self):38 """39 /proxy/:port/har40 and returns 204 when creating a har with a particular name the first time41 and returns 200 and the previous har when creating one with the same name42 """43 status_code, har = self.client.new_har("elephants")44 assert(status_code == 204)45 assert(har is None)46 status_code, har = self.client.new_har("elephants")47 assert(status_code == 200)48 assert('elephants' == har["log"]["pages"][0]['id'])49 def test_new_page_defaults(self):50 """51 /proxy/:port/pageRef52 adds a new page of 'Page N' when no page name is given53 """54 self.client.new_har()55 self.client.new_page()56 har = self.client.har57 assert(len(har["log"]["pages"]) == 2)58 assert(har["log"]["pages"][1]["id"] == "Page 2")59 def test_new_named_page(self):60 """61 /proxy/:port/pageRef62 adds a new page of 'buttress'63 """64 self.client.new_har()65 self.client.new_page('buttress')66 har = self.client.har67 assert(len(har["log"]["pages"]) == 2)68 assert(har["log"]["pages"][1]["id"] == "buttress")69 def test_single_whitelist(self):70 """71 /proxy/:port/whitelist72 adds a whitelist73 """74 status_code = self.client.whitelist("http://www\\.facebook\\.com/.*", 200)75 assert(status_code == 200)76 def test_multiple_whitelists(self):77 """78 /proxy/:port/whitelist79 adds a whitelist80 """81 status_code = self.client.whitelist("http://www\\.facebook\\.com/.*,http://cdn\\.twitter\\.com", 200)82 assert(status_code == 200)83 def test_blacklist(self):84 """85 /proxy/:port/blacklist86 adds a blacklist87 """88 status_code = self.client.blacklist("http://www\\.facebook\\.com/.*", 200)89 assert(status_code == 200)90 def test_basic_authentication(self):91 """92 /proxy/:port/auth/basic93 adds automatic basic authentication94 """95 status_code = self.client.basic_authentication("www.example.com", "myUsername", "myPassword")96 assert(status_code == 200)97 def test_limits_invalid_key(self):98 """99 /proxy/:port/limits100 pre-sending checking that the parameter is correct101 """102 with pytest.raises(KeyError):103 self.client.limits({"hurray": "explosions"})104 def test_limits_key_no_value(self):105 """106 /proxy/:port/limits107 pre-sending checking that a parameter exists108 """109 with pytest.raises(KeyError):110 self.client.limits({})111 def test_limits_all_key_values(self):112 """113 /proxy/:port/limits114 can send all 3 at once based on the proxy implementation115 """116 limits = {"upstream_kbps": 320, "downstream_kbps": 560, "latency": 30}117 status_code = self.client.limits(limits)118 assert(status_code == 200)119 def test_rewrite(self):120 """121 /proxy/:port/rewrite122 """123 match = "/foo"124 replace = "/bar"125 status_code = self.client.rewrite_url(match, replace)126 assert(status_code == 200)127 def test_close(self):128 """129 /proxy/:port130 close the proxy port131 """132 status_code = self.client.close()133 assert(status_code == 200)134 status_code = self.client.close()135 assert(status_code == 404)136 def test_response_interceptor_with_parsing_js(self):137 """138 /proxy/:port/interceptor/response139 """140 js = 'alert("foo")'141 status_code = self.client.response_interceptor(js)142 assert(status_code == 200)143 def test_response_interceptor_with_invalid_js(self):144 """145 /proxy/:port/interceptor/response146 """147 js = 'alert("foo"'148 status_code = self.client.response_interceptor(js)149 assert(status_code == 500)150 def test_request_interceptor_with_parsing_js(self):151 """152 /proxy/:port/interceptor/request153 """154 js = 'alert("foo")'155 status_code = self.client.request_interceptor(js)156 assert(status_code == 200)157 def test_request_interceptor_with_invalid_js(self):158 """159 /proxy/:port/interceptor/request160 """161 js = 'alert("foo"'162 status_code = self.client.request_interceptor(js)163 assert(status_code == 500)164 def test_timeouts_invalid_timeouts(self):165 """166 /proxy/:port/timeout167 pre-sending checking that the parameter is correct168 """169 with pytest.raises(KeyError):170 self.client.timeouts({"hurray": "explosions"})171 def test_timeouts_key_no_value(self):172 """173 /proxy/:port/timeout174 pre-sending checking that a parameter exists175 """176 with pytest.raises(KeyError):177 self.client.timeouts({})178 def test_timeouts_all_key_values(self):179 """180 /proxy/:port/timeout181 can send all 3 at once based on the proxy implementation182 """183 timeouts = {"request": 2, "read": 2, "connection": 2, "dns": 3}184 status_code = self.client.timeouts(timeouts)185 assert(status_code == 200)186 def test_remap_hosts(self):187 """188 /proxy/:port/hosts189 """190 status_code = self.client.remap_hosts("example.com", "1.2.3.4")191 assert(status_code == 200)192 def test_wait_for_traffic_to_stop(self):193 """194 /proxy/:port/wait195 """196 status_code = self.client.wait_for_traffic_to_stop(2000, 10000)197 assert(status_code == 200)198 def test_clear_dns_cache(self):199 """200 /proxy/:port/dns/cache201 """202 status_code = self.client.clear_dns_cache()203 assert(status_code == 200)204 def test_rewrite_url(self):205 """206 /proxy/:port/rewrite207 """208 status_code = self.client.rewrite_url('http://www.facebook\.com', 'http://microsoft.com')209 assert(status_code == 200)210 def test_retry(self):211 """212 /proxy/:port/retry213 """214 status_code = self.client.retry(4)...

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run locust automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful