How to use serialize_headers method in Playwright Python

Best Python code snippet using playwright-python

response.py

Source:response.py Github

copy

Full Screen

...110 elif self.reason_phrase is None:111 self.reason_phrase = REASON_PHRASES.get(self.status_code,112 'UNKNOWN STATUS CODE')113 self['Content-Type'] = content_type114 def serialize_headers(self):115 """HTTP headers as a bytestring."""116 def to_bytes(val, encoding):117 return val if isinstance(val, bytes) else val.encode(encoding)118 headers = [119 (b': '.join([to_bytes(key, 'ascii'), to_bytes(value, 'latin-1')]))120 for key, value in self._headers.values()121 ]122 return b'\r\n'.join(headers)123 if six.PY3:124 __bytes__ = serialize_headers125 else:126 __str__ = serialize_headers127 def _convert_to_charset(self, value, charset, mime_encode=False):128 """Converts headers key/value to ascii/latin-1 native strings.129 `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and130 `value` value can't be represented in the given charset, MIME-encoding131 is applied.132 """133 if not isinstance(value, (bytes, six.text_type)):134 value = str(value)135 try:136 if six.PY3:137 if isinstance(value, str):138 # Ensure string is valid in given charset139 value.encode(charset)140 else:141 # Convert bytestring using given charset142 value = value.decode(charset)143 else:144 if isinstance(value, str):145 # Ensure string is valid in given charset146 value.decode(charset)147 else:148 # Convert unicode string to given charset149 value = value.encode(charset)150 except UnicodeError as e:151 if mime_encode:152 # Wrapping in str() is a workaround for #12422 under Python 2.153 value = str(Header(value, 'utf-8').encode())154 else:155 e.reason += ', HTTP response headers must be in %s format' % charset156 raise157 if str('\n') in value or str('\r') in value:158 raise BadHeaderError("Header values can't contain newlines (got %r)" % value)159 return value160 def __setitem__(self, header, value):161 header = self._convert_to_charset(header, 'ascii')162 value = self._convert_to_charset(value, 'latin-1', mime_encode=True)163 self._headers[header.lower()] = (header, value)164 def __delitem__(self, header):165 try:166 del self._headers[header.lower()]167 except KeyError:168 pass169 def __getitem__(self, header):170 return self._headers[header.lower()][1]171 def __getstate__(self):172 # SimpleCookie is not pickeable with pickle.HIGHEST_PROTOCOL, so we173 # serialise to a string instead174 state = self.__dict__.copy()175 state['cookies'] = str(state['cookies'])176 return state177 def __setstate__(self, state):178 self.__dict__.update(state)179 self.cookies = SimpleCookie(self.cookies)180 def has_header(self, header):181 """Case-insensitive check for a header."""182 return header.lower() in self._headers183 __contains__ = has_header184 def items(self):185 return self._headers.values()186 def get(self, header, alternate=None):187 return self._headers.get(header.lower(), (None, alternate))[1]188 def set_cookie(self, key, value='', max_age=None, expires=None, path='/',189 domain=None, secure=False, httponly=False):190 """191 Sets a cookie.192 ``expires`` can be:193 - a string in the correct format,194 - a naive ``datetime.datetime`` object in UTC,195 - an aware ``datetime.datetime`` object in any time zone.196 If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.197 """198 self.cookies[key] = value199 if expires is not None:200 if isinstance(expires, datetime.datetime):201 if timezone.is_aware(expires):202 expires = timezone.make_naive(expires, timezone.utc)203 delta = expires - expires.utcnow()204 # Add one second so the date matches exactly (a fraction of205 # time gets lost between converting to a timedelta and206 # then the date string).207 delta = delta + datetime.timedelta(seconds=1)208 # Just set max_age - the max_age logic will set expires.209 expires = None210 max_age = max(0, delta.days * 86400 + delta.seconds)211 else:212 self.cookies[key]['expires'] = expires213 if max_age is not None:214 self.cookies[key]['max-age'] = max_age215 # IE requires expires, so set it if hasn't been already.216 if not expires:217 self.cookies[key]['expires'] = cookie_date(time.time() +218 max_age)219 if path is not None:220 self.cookies[key]['path'] = path221 if domain is not None:222 self.cookies[key]['domain'] = domain223 if secure:224 self.cookies[key]['secure'] = True225 if httponly:226 self.cookies[key]['httponly'] = True227 def set_signed_cookie(self, key, value, salt='', **kwargs):228 value = signing.get_cookie_signer(salt=key + salt).sign(value)229 return self.set_cookie(key, value, **kwargs)230 def delete_cookie(self, key, path='/', domain=None):231 self.set_cookie(key, max_age=0, path=path, domain=domain,232 expires='Thu, 01-Jan-1970 00:00:00 GMT')233 # Common methods used by subclasses234 def make_bytes(self, value):235 """Turn a value into a bytestring encoded in the output charset."""236 # Per PEP 3333, this response body must be bytes. To avoid returning237 # an instance of a subclass, this function returns `bytes(value)`.238 # This doesn't make a copy when `value` already contains bytes.239 # If content is already encoded (eg. gzip), assume bytes.240 if self.has_header('Content-Encoding'):241 return bytes(value)242 # Handle string types -- we can't rely on force_bytes here because:243 # - under Python 3 it attemps str conversion first244 # - when self._charset != 'utf-8' it re-encodes the content245 if isinstance(value, bytes):246 return bytes(value)247 if isinstance(value, six.text_type):248 return bytes(value.encode(self._charset))249 # Handle non-string types (#16494)250 return force_bytes(value, self._charset)251 def __iter__(self):252 return self253 def __next__(self):254 # Subclasses must define self._iterator for this function.255 return self.make_bytes(next(self._iterator))256 # These methods partially implement the file-like object interface.257 # See http://docs.python.org/lib/bltin-file-objects.html258 # The WSGI server must call this method upon completion of the request.259 # See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html260 def close(self):261 for closable in self._closable_objects:262 try:263 closable.close()264 except Exception:265 pass266 signals.request_finished.send(sender=self._handler_class)267 def write(self, content):268 raise Exception("This %s instance is not writable" % self.__class__.__name__)269 def flush(self):270 pass271 def tell(self):272 raise Exception("This %s instance cannot tell its position" % self.__class__.__name__)273class HttpResponse(HttpResponseBase):274 """275 An HTTP response class with a string as content.276 This content that can be read, appended to or replaced.277 """278 streaming = False279 def __init__(self, content=b'', *args, **kwargs):280 super(HttpResponse, self).__init__(*args, **kwargs)281 # Content is a bytestring. See the `content` property methods.282 self.content = content283 def serialize(self):284 """Full HTTP message, including headers, as a bytestring."""285 return self.serialize_headers() + b'\r\n\r\n' + self.content286 if six.PY3:287 __bytes__ = serialize288 else:289 __str__ = serialize290 def _consume_content(self):291 # If the response was instantiated with an iterator, when its content292 # is accessed, the iterator is going be exhausted and the content293 # loaded in memory. At this point, it's better to abandon the original294 # iterator and save the content for later reuse. This is a temporary295 # solution. See the comment in __iter__ below for the long term plan.296 if self._base_content_is_iter:297 self.content = b''.join(self.make_bytes(e) for e in self._container)298 @property299 def content(self):...

Full Screen

Full Screen

response.pyi

Source:response.pyi Github

copy

Full Screen

...51 reason: Optional[str] = ...,52 charset: Optional[str] = ...,53 headers: Optional[Dict[str, str]] = ...,54 ) -> None: ...55 def serialize_headers(self) -> bytes: ...56 __bytes__ = serialize_headers57 def __setitem__(self, header: Union[str, bytes], value: Union[str, bytes, int]) -> None: ...58 def __delitem__(self, header: Union[str, bytes]) -> None: ...59 def __getitem__(self, header: Union[str, bytes]) -> str: ...60 def has_header(self, header: str) -> bool: ...61 def items(self) -> Iterable[Tuple[str, str]]: ...62 @overload63 def get(self, header: Union[str, bytes], alternate: Optional[str]) -> str: ...64 @overload65 def get(self, header: Union[str, bytes]) -> Optional[str]: ...66 def set_cookie(67 self,68 key: str,69 value: str = ...,...

Full Screen

Full Screen

tests.py

Source:tests.py Github

copy

Full Screen

...31 site=get_current_site(request), uses_regex=True)32 redirect.save()33 new_response = self.run_redirect(request)34 self.assertEqual(new_response.status_code, 301)35 self.assertIn(b"somethingelse", new_response.serialize_headers())36 def test_redirect_request_gone(self):37 # Create a redirect38 request = self.factory.get('/test/123/')39 redirect = Redirect(from_url=r'test/(?P<pk>\d+)/', to_url='',40 site=get_current_site(request), uses_regex=True)41 redirect.save()42 new_response = self.run_redirect(request)43 self.assertEqual(new_response.status_code, 410)44 def test_redirect_request_temporary(self):45 # Create a redirect46 request = self.factory.get('/test/123/')47 redirect = Redirect(from_url=r'test/(?P<pk>\d+)/', to_url=r'somethingelse/(?P<pk>\d+)/',48 site=get_current_site(request), http_status=302, uses_regex=True)49 redirect.save()50 new_response = self.run_redirect(request)51 self.assertEqual(new_response.status_code, 302)52 self.assertIn(b"somethingelse", new_response.serialize_headers())53 def test_redirect_request_partial_temporary(self):54 # Create a redirect55 request = self.factory.get('/test/123/')56 redirect = Redirect(from_url='/test/', to_url='/partialtest/', is_partial=True,57 site=get_current_site(request), http_status=302)58 redirect.save()59 new_response = self.run_redirect(request)60 self.assertEqual(new_response.status_code, 302)61 self.assertIn(b"partialtest", new_response.serialize_headers())62 def test_redirect_request_partial_permanent(self):63 # Create a redirect64 request = self.factory.get('/test/123/')65 redirect = Redirect(from_url='/test/', to_url='/partialtest/', is_partial=True,66 site=get_current_site(request), http_status=301)67 redirect.save()68 new_response = self.run_redirect(request)69 self.assertEqual(new_response.status_code, 301)70 self.assertIn(b"partialtest", new_response.serialize_headers())71 def test_redirect_request_two_partial_entries_permanent(self):72 # Create a redirect73 old_route = '/invalidroot/partialtest'74 redirected_route = '/test/partialtest'75 request = self.factory.get(old_route)76 redirect = Redirect(from_url='/invalidroot', to_url=redirected_route, is_partial=True,77 site=get_current_site(request), http_status=301)78 redirect.save()79 redirect2 = Redirect(from_url=old_route, to_url=redirected_route, is_partial=True,80 site=get_current_site(request), http_status=301)81 redirect2.save()82 new_response = self.run_redirect(request)83 self.assertEqual(new_response.status_code, 301)84 self.assertEqual(new_response.url, redirected_route)85 def test_redirect_request_partial_gone(self):86 # Create a redirect87 request = self.factory.get('/test/123/')88 redirect = Redirect(from_url='/test/', to_url='', is_partial=True,89 site=get_current_site(request), http_status=301)90 redirect.save()91 new_response = self.run_redirect(request)92 self.assertEqual(new_response.status_code, 410)93 def test_redirect_request_partial_prepend_slash(self):94 # Create a redirect95 request = self.factory.get('/test/123/')96 redirect = Redirect(from_url='/test/', to_url='partialtest/', is_partial=True,97 site=get_current_site(request), http_status=302)98 redirect.save()99 new_response = self.run_redirect(request)100 self.assertEqual(new_response.status_code, 302)101 self.assertIn(b"/partialtest/123/", new_response.serialize_headers())102 def test_redirect_exclusion(self):103 # Create a redirect104 request = self.factory.get('/api/test/123/')105 settings.ROBUST_REDIRECTS_IGNORED_PREFIXES = '/api'106 redirect = Redirect(from_url='/test/', to_url='partialtest/', is_partial=True,107 site=get_current_site(request), http_status=302)108 redirect.save()109 redirect2 = Redirect(from_url=r'/api/test/(?P<pk>\d+)/', to_url=r'somethingelse/(?P<pk>\d+)/',110 site=get_current_site(request), http_status=302, uses_regex=True)111 redirect2.save()112 new_response = self.run_redirect(request)113 # no redirect should happen...

Full Screen

Full Screen

test_views.py

Source:test_views.py Github

copy

Full Screen

...12 request = factory.get("/some_view")13 response = views.PromptDownloadView.as_view()(request)14 self.assertEqual(response.status_code, 200)15 self.assertIn(16 b"Content-Type: application/pdf", response.serialize_headers().splitlines()17 )18 self.assertIn(19 b'Content-Disposition: attachment; filename="myfile.pdf"',20 response.serialize_headers().splitlines(),21 )22 # Assert that response looks like a PDF23 self.assertTrue(response.content.startswith(b"%PDF-1."))24 def test_dont_prompt_download(self):25 request = factory.get("/some_view")26 response = views.NoPromptDownloadView.as_view()(request)27 self.assertEqual(response.status_code, 200)28 self.assertIn(29 b"Content-Type: application/pdf", response.serialize_headers().splitlines()30 )31 self.assertNotIn(b"Content-Disposition:", response.serialize_headers())32 # Assert that response looks like a PDF33 self.assertTrue(response.content.startswith(b"%PDF-1."))34class ForceHTMLTestCase(TestCase):35 def test_force_html_allowed(self):36 request = factory.get("/some_view?html=true")37 response = views.AllowForceHtmlView.as_view()(request)38 self.assertEqual(response.status_code, 200)39 self.assertEqual(b"Hi!\n", response.content)40 self.assertIn(41 b"Content-Type: text/html; charset=utf-8",42 response.serialize_headers().splitlines(),43 )44 def test_no_force_html_allowed(self):45 request = factory.get("/some_view")46 response = views.AllowForceHtmlView.as_view()(request)47 self.assertEqual(response.status_code, 200)48 self.assertIn(49 b"Content-Type: application/pdf", response.serialize_headers().splitlines()50 )51 # Assert that response looks like a PDF52 self.assertTrue(response.content.startswith(b"%PDF-1."))53 def test_force_html_disallowed(self):54 request = factory.get("/some_view?html=true")55 response = views.DisallowForceHtmlView.as_view()(request)56 self.assertEqual(response.status_code, 200)57 self.assertIn(58 b"Content-Type: application/pdf", response.serialize_headers().splitlines()59 )60 # Assert that response looks like a PDF61 self.assertTrue(response.content.startswith(b"%PDF-1."))62 def test_no_force_html_disallowed(self):63 request = factory.get("/some_view")64 response = views.DisallowForceHtmlView.as_view()(request)65 self.assertEqual(response.status_code, 200)66 self.assertIn(67 b"Content-Type: application/pdf", response.serialize_headers().splitlines()68 )69 # Assert that response looks like a PDF70 self.assertTrue(response.content.startswith(b"%PDF-1."))71class CustomUrlFetcherTestCase(TestCase):72 pass # TODO73class StaticFileResolutionTestCase(TestCase):74 def test_url_fetcher_used(self):75 request = factory.get("/some_view")76 with patch(77 "django_renderpdf.helpers.django_url_fetcher",78 return_value={79 "string": "html { margin: 0; }",80 "mime_type": "text/css",81 },...

Full Screen

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python 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