Best Python code snippet using playwright-python
documentation_provider.py
Source:documentation_provider.py
...152 del args[name]153 if not doc_value:154 self.errors.add(f"Parameter not documented: {fqname}({name}=)")155 else:156 code_type = self.serialize_python_type(value)157 print(f"{indent}{to_snake_case(original_name)} : {code_type}")158 if doc_value.get("comment"):159 print(160 f"{indent} {self.indent_paragraph(self.render_links(doc_value['comment']), f'{indent} ')}"161 )162 self.compare_types(code_type, doc_value, f"{fqname}({name}=)", "in")163 if (164 signature165 and "return" in signature166 and str(signature["return"]) != "<class 'NoneType'>"167 ):168 value = signature["return"]169 doc_value = method170 self.compare_types(value, doc_value, f"{fqname}(return=)", "out")171 print("")172 print(" Returns")173 print(" -------")174 print(f" {self.serialize_python_type(value)}")175 print(f'{indent}"""')176 for name in args:177 if args[name].get("deprecated"):178 continue179 self.errors.add(180 f"Parameter not implemented: {class_name}.{method_name}({name}=)"181 )182 def indent_paragraph(self, p: str, indent: str) -> str:183 lines = p.split("\n")184 result = [lines[0]]185 for line in lines[1:]:186 result.append(indent + line)187 return "\n".join(result)188 def beautify_method_comment(self, comment: str, indent: str) -> str:189 comment = comment.replace("\\", "\\\\")190 comment = comment.replace('"', '\\"')191 lines = comment.split("\n")192 result = []193 skip_example = False194 last_was_blank = True195 for line in lines:196 if not line.strip():197 last_was_blank = True198 continue199 match = re.match(r"\s*```(.+)", line)200 if match:201 lang = match[1]202 if lang in ["html", "yml", "sh", "py", "python"]:203 skip_example = False204 elif lang == "python " + ("async" if self.is_async else "sync"):205 skip_example = False206 line = "```py"207 else:208 skip_example = True209 if not skip_example:210 if last_was_blank:211 last_was_blank = False212 result.append("")213 result.append(self.render_links(line))214 if skip_example and line.strip() == "```":215 skip_example = False216 return self.indent_paragraph("\n".join(result), indent)217 def render_links(self, comment: str) -> str:218 for [old, new] in self.links.items():219 comment = comment.replace(old, new)220 return comment221 def make_optional(self, text: str) -> str:222 if text.startswith("Union["):223 if text.endswith("NoneType]"):224 return text225 return text[:-1] + ", NoneType]"226 return f"Union[{text}, NoneType]"227 def compare_types(228 self, value: Any, doc_value: Any, fqname: str, direction: str229 ) -> None:230 if "(arg=)" in fqname or "(pageFunction=)" in fqname:231 return232 code_type = self.serialize_python_type(value)233 doc_type = self.serialize_doc_type(doc_value["type"], direction)234 if not doc_value["required"]:235 doc_type = self.make_optional(doc_type)236 if doc_type != code_type:237 self.errors.add(238 f"Parameter type mismatch in {fqname}: documented as {doc_type}, code has {code_type}"239 )240 def serialize_python_type(self, value: Any) -> str:241 str_value = str(value)242 if isinstance(value, list):243 return f"[{', '.join(list(map(lambda a: self.serialize_python_type(a), value)))}]"244 if str_value == "<class 'playwright._impl._types.Error'>":245 return "Error"246 match = re.match(r"^<class '((?:pathlib\.)?\w+)'>$", str_value)247 if match:248 return match.group(1)249 match = re.match(250 r"playwright._impl._event_context_manager.EventContextManagerImpl\[playwright._impl.[^.]+.(.*)\]",251 str_value,252 )253 if match:254 return "EventContextManager[" + match.group(1) + "]"255 match = re.match(r"^<class 'playwright\._impl\.[\w_]+\.([^']+)'>$", str_value)256 if (257 match258 and "_api_structures" not in str_value259 and "_api_types" not in str_value260 ):261 if match.group(1) == "EventContextManagerImpl":262 return "EventContextManager"263 return match.group(1)264 match = re.match(r"^typing\.(\w+)$", str_value)265 if match:266 return match.group(1)267 origin = get_origin(value)268 args = get_args(value)269 hints = None270 try:271 hints = get_type_hints(value)272 except Exception:273 pass274 if hints:275 signature: List[str] = []276 for [name, value] in hints.items():277 signature.append(f"{name}: {self.serialize_python_type(value)}")278 return f"{{{', '.join(signature)}}}"279 if origin == Union:280 args = get_args(value)281 if len(args) == 2 and str(args[1]) == "<class 'NoneType'>":282 return self.make_optional(self.serialize_python_type(args[0]))283 ll = list(map(lambda a: self.serialize_python_type(a), args))284 ll.sort(key=lambda item: "}" if item == "NoneType" else item)285 return f"Union[{', '.join(ll)}]"286 if str(origin) == "<class 'dict'>":287 args = get_args(value)288 return f"Dict[{', '.join(list(map(lambda a: self.serialize_python_type(a), args)))}]"289 if str(origin) == "<class 'list'>":290 args = get_args(value)291 return f"List[{', '.join(list(map(lambda a: self.serialize_python_type(a), args)))}]"292 if str(origin) == "<class 'collections.abc.Callable'>":293 args = get_args(value)294 return f"Callable[{', '.join(list(map(lambda a: self.serialize_python_type(a), args)))}]"295 if str(origin) == "typing.Literal":296 args = get_args(value)297 if len(args) == 1:298 return '"' + self.serialize_python_type(args[0]) + '"'299 body = ", ".join(300 list(map(lambda a: '"' + self.serialize_python_type(a) + '"', args))301 )302 return f"Union[{body}]"303 return str_value304 def serialize_doc_type(self, type: Any, direction: str) -> str:305 result = self.inner_serialize_doc_type(type, direction)306 return result307 def inner_serialize_doc_type(self, type: Any, direction: str) -> str:308 if type["name"] == "Promise":309 type = type["templates"][0]310 if "union" in type:311 ll = [self.serialize_doc_type(t, direction) for t in type["union"]]312 ll.sort(key=lambda item: "}" if item == "NoneType" else item)313 for i in range(len(ll)):314 if ll[i].startswith("Union["):...
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!!