Best Python code snippet using playwright-python
response.py
Source: response.py
...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):...
response.pyi
Source: response.pyi
...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 = ...,...
tests.py
Source: tests.py
...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...
test_views.py
Source: test_views.py
...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 },...
Playwright error connection refused in docker
playwright-python advanced setup
How to select an input according to a parent sibling label
Error when installing Microsoft Playwright
Trouble waiting for changes to complete that are triggered by Python Playwright `select_option`
Capturing and Storing Request Data Using Playwright for Python
Can Playwright be used to launch a browser instance
Trouble in Clicking on Log in Google Button of Pop Up Menu Playwright Python
Scrapy Playwright get date by clicking button
React locator example
I solved my problem. In fact my docker container (frontend) is called "app" which is also domain name of fronend application. My application is running locally on http. Chromium and geko drivers force httpS connection for some domain names one of which is "app". So i have to change name for my docker container wich contains frontend application.
Check out the latest blogs from LambdaTest on this topic:
The sky’s the limit (and even beyond that) when you want to run test automation. Technology has developed so much that you can reduce time and stay more productive than you used to 10 years ago. You needn’t put up with the limitations brought to you by Selenium if that’s your go-to automation testing tool. Instead, you can pick from various test automation frameworks and tools to write effective test cases and run them successfully.
When it comes to web automation testing, there are a number of frameworks like Selenium, Cypress, PlayWright, Puppeteer, etc., that make it to the ‘preferred list’ of frameworks. The choice of test automation framework depends on a range of parameters like type, complexity, scale, along with the framework expertise available within the team. However, it’s no surprise that Selenium is still the most preferred framework among developers and QAs.
Playwright is a framework that I’ve always heard great things about but never had a chance to pick up until earlier this year. And since then, it’s become one of my favorite test automation frameworks to use when building a new automation project. It’s easy to set up, feature-packed, and one of the fastest, most reliable frameworks I’ve worked with.
The speed at which tests are executed and the “dearth of smartness” in testing are the two major problems developers and testers encounter.
With the rapidly evolving technology due to its ever-increasing demand in today’s world, Digital Security has become a major concern for the Software Industry. There are various ways through which Digital Security can be achieved, Captcha being one of them.Captcha is easy for humans to solve but hard for “bots” and other malicious software to figure out. However, Captcha has always been tricky for the testers to automate, as many of them don’t know how to handle captcha in Selenium or using any other test automation framework.
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!