diff --git a/py/pyproject.toml b/py/pyproject.toml index 3e9d15fc728b2..2d74986b8b19b 100644 --- a/py/pyproject.toml +++ b/py/pyproject.toml @@ -146,7 +146,6 @@ target-version = "py39" [tool.ruff.lint] extend-select = ["D", "E4", "E7", "E9", "F", "I", "E501", "RUF022", "TID252"] fixable = ["ALL"] -# remove these as we cleanup docstrings extend-ignore = [ "D100", # Missing docstring in public module "D101", # Missing docstring in public class @@ -157,7 +156,6 @@ extend-ignore = [ "D107", # Missing docstring in `__init__` "D205", # 1 blank line required between summary line and description "D212", # Multi-line docstring summary should start at the first line - "D415", # First line should end with a period, question mark, or exclamation point ] [tool.ruff.format] diff --git a/py/selenium/webdriver/chromium/webdriver.py b/py/selenium/webdriver/chromium/webdriver.py index ba4c141ec941a..dee917f7598e2 100644 --- a/py/selenium/webdriver/chromium/webdriver.py +++ b/py/selenium/webdriver/chromium/webdriver.py @@ -105,7 +105,7 @@ def set_network_conditions(self, **network_conditions) -> None: upload_throughput=500 * 1024, ) # maximal throughput - Note: 'throughput' can be used to set both (for download and upload). + Note: `throughput` can be used to set both (for download and upload). """ self.execute("setNetworkConditions", {"network_conditions": network_conditions}) @@ -126,17 +126,19 @@ def set_permissions(self, name: str, value: str) -> None: self.execute("setPermissions", {"descriptor": {"name": name}, "state": value}) def execute_cdp_cmd(self, cmd: str, cmd_args: dict): - """Execute Chrome Devtools Protocol command and get returned result The - command and command args should follow chrome devtools protocol - domains/commands, refer to link - https://chromedevtools.github.io/devtools-protocol/ + """Execute Chrome Devtools Protocol command and get returned result. + + The command and command args should follow chrome devtools protocol domains/commands + + See: + - https://chromedevtools.github.io/devtools-protocol/ Args: cmd: A str, command name cmd_args: A dict, command args. empty dict {} if there is no command args Example: - driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId}) + `driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId})` Returns: A dict, empty dict {} if there is no result to return. diff --git a/py/selenium/webdriver/common/options.py b/py/selenium/webdriver/common/options.py index 35426b23b059e..4eb323c66c5b1 100644 --- a/py/selenium/webdriver/common/options.py +++ b/py/selenium/webdriver/common/options.py @@ -65,8 +65,10 @@ def __set__(self, obj, value): class _PageLoadStrategyDescriptor: - """Determines the point at which a navigation command is returned: - https://w3c.github.io/webdriver/#dfn-table-of-page-load-strategies. + """Determines the point at which a navigation command is returned. + + See: + - https://w3c.github.io/webdriver/#dfn-table-of-page-load-strategies. Args: strategy: the strategy corresponding to a document readiness state @@ -86,9 +88,10 @@ def __set__(self, obj, value): class _UnHandledPromptBehaviorDescriptor: - """How the driver should respond when an alert is present and the: - command sent is not handling the alert: - https://w3c.github.io/webdriver/#dfn-table-of-page-load-strategies: + """How the driver should respond when an alert is present and the command sent is not handling the alert. + + See: + - https://w3c.github.io/webdriver/#dfn-table-of-page-load-strategies: Args: behavior: behavior to use when an alert is encountered @@ -114,8 +117,10 @@ def __set__(self, obj, value): class _TimeoutsDescriptor: - """How long the driver should wait for actions to complete before: - returning an error https://w3c.github.io/webdriver/#timeouts: + """How long the driver should wait for actions to complete before returning an error. + + See: + - https://w3c.github.io/webdriver/#timeouts Args: timeouts: values in milliseconds for implicit wait, page load and script timeout diff --git a/py/selenium/webdriver/remote/webdriver.py b/py/selenium/webdriver/remote/webdriver.py index 2b04e15a5709b..0a603f5fa307d 100644 --- a/py/selenium/webdriver/remote/webdriver.py +++ b/py/selenium/webdriver/remote/webdriver.py @@ -299,8 +299,10 @@ class is instantiated with args and kwargs and used as a file **kwargs: Keyword arguments, passed the same way as args. Example: - >>> with webdriver.file_detector_context(UselessFileDetector): - >>> someinput.send_keys('/etc/hosts') + ``` + with webdriver.file_detector_context(UselessFileDetector): + someinput.send_keys("/etc/hosts") + ```` """ last_detector = None if not isinstance(self.file_detector, file_detector_class): @@ -318,11 +320,7 @@ def mobile(self) -> Mobile: @property def name(self) -> str: - """Returns the name of the underlying browser for this instance. - - Example: - >>> name = driver.name - """ + """Returns the name of the underlying browser for this instance.""" if "browserName" in self.caps: return self.caps["browserName"] raise KeyError("browserName not specified in session capabilities") @@ -390,10 +388,10 @@ def _unwrap_value(self, value): return value def execute_cdp_cmd(self, cmd: str, cmd_args: dict): - """Execute Chrome Devtools Protocol command and get returned result The - command and command args should follow chrome devtools protocol - domains/commands, refer to link - https://chromedevtools.github.io/devtools-protocol/ + """Execute Chrome Devtools Protocol command and get returned result. + + The command and command args should follow chrome devtools protocol domains/commands: + - https://chromedevtools.github.io/devtools-protocol/ Args: cmd: Command name. @@ -405,7 +403,7 @@ def execute_cdp_cmd(self, cmd: str, cmd_args: dict): string'} Example: - >>> driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": requestId}) + `driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": requestId})` """ return self.execute("executeCdpCommand", {"cmd": cmd, "params": cmd_args})["value"] @@ -449,8 +447,7 @@ def get(self, url: str) -> None: (e.g., http://, https://). Example: - >>> driver = webdriver.Chrome() - >>> driver.get("https://example.com") + `driver.get("https://example.com")` """ self.execute(Command.GET, {"url": url}) @@ -459,8 +456,10 @@ def title(self) -> str: """Returns the title of the current page. Example: - >>> element = driver.find_element(By.ID, "foo") - >>> print(element.title()) + ``` + element = driver.find_element(By.ID, "foo") + print(element.title()) + ``` """ return self.execute(Command.GET_TITLE).get("value", "") @@ -469,7 +468,7 @@ def pin_script(self, script: str, script_key=None) -> ScriptKey: hashable ID. Example: - >>> script = "return document.getElementById('foo').value" + `script = "return document.getElementById('foo').value"` """ script_key_instance = ScriptKey(script_key) self.pinned_scripts[script_key_instance.id] = script @@ -479,7 +478,7 @@ def unpin(self, script_key: ScriptKey) -> None: """Remove a pinned script from storage. Example: - >>> driver.unpin(script_key) + `driver.unpin(script_key)` """ try: self.pinned_scripts.pop(script_key.id) @@ -490,7 +489,7 @@ def get_pinned_scripts(self) -> list[str]: """Return a list of all pinned scripts. Example: - >>> pinned_scripts = driver.get_pinned_scripts() + `pinned_scripts = driver.get_pinned_scripts()` """ return list(self.pinned_scripts) @@ -502,9 +501,11 @@ def execute_script(self, script: str, *args): *args: Any applicable arguments for your JavaScript. Example: - >>> id = "username" - >>> value = "test_user" - >>> driver.execute_script("document.getElementById(arguments[0]).value = arguments[1];", id, value) + ``` + id = "username" + value = "test_user" + driver.execute_script("document.getElementById(arguments[0]).value = arguments[1];", id, value) + ``` """ if isinstance(script, ScriptKey): try: @@ -525,9 +526,11 @@ def execute_async_script(self, script: str, *args): *args: Any applicable arguments for your JavaScript. Example: - >>> script = "var callback = arguments[arguments.length - 1]; " - ... "window.setTimeout(function(){ callback('timeout') }, 3000);" - >>> driver.execute_async_script(script) + ``` + script = "var callback = arguments[arguments.length - 1]; " + "window.setTimeout(function(){ callback('timeout') }, 3000);" + driver.execute_async_script(script) + ``` """ converted_args = list(args) command = Command.W3C_EXECUTE_SCRIPT_ASYNC @@ -536,36 +539,20 @@ def execute_async_script(self, script: str, *args): @property def current_url(self) -> str: - """Gets the URL of the current page. - - Example: - >>> print(driver.current_url) - """ + """Gets the URL of the current page.""" return self.execute(Command.GET_CURRENT_URL)["value"] @property def page_source(self) -> str: - """Gets the source of the current page. - - Example: - >>> print(driver.page_source) - """ + """Gets the source of the current page.""" return self.execute(Command.GET_PAGE_SOURCE)["value"] def close(self) -> None: - """Closes the current window. - - Example: - >>> driver.close() - """ + """Closes the current window.""" self.execute(Command.CLOSE) def quit(self) -> None: - """Quits the driver and closes every associated window. - - Example: - >>> driver.quit() - """ + """Quits the driver and closes every associated window.""" try: self.execute(Command.QUIT) finally: @@ -575,37 +562,21 @@ def quit(self) -> None: @property def current_window_handle(self) -> str: - """Returns the handle of the current window. - - Example: - >>> print(driver.current_window_handle) - """ + """Returns the handle of the current window.""" return self.execute(Command.W3C_GET_CURRENT_WINDOW_HANDLE)["value"] @property def window_handles(self) -> list[str]: - """Returns the handles of all windows within the current session. - - Example: - >>> print(driver.window_handles) - """ + """Returns the handles of all windows within the current session.""" return self.execute(Command.W3C_GET_WINDOW_HANDLES)["value"] def maximize_window(self) -> None: - """Maximizes the current window that webdriver is using. - - Example: - >>> driver.maximize_window() - """ + """Maximizes the current window that webdriver is using.""" command = Command.W3C_MAXIMIZE_WINDOW self.execute(command, None) def fullscreen_window(self) -> None: - """Invokes the window manager-specific 'full screen' operation. - - Example: - >>> driver.fullscreen_window() - """ + """Invokes the window manager-specific 'full screen' operation.""" self.execute(Command.FULLSCREEN_WINDOW) def minimize_window(self) -> None: @@ -617,9 +588,6 @@ def print_page(self, print_options: Optional[PrintOptions] = None) -> str: The driver makes a best effort to return a PDF based on the provided parameters. - - Example: - >>> driver.print_page() """ options: Union[dict[str, Any], Any] = {} if print_options: @@ -635,43 +603,30 @@ def switch_to(self) -> SwitchTo: An object containing all options to switch focus into. Examples: - >>> element = driver.switch_to.active_element - >>> alert = driver.switch_to.alert - >>> driver.switch_to.default_content() - >>> driver.switch_to.frame("frame_name") - >>> driver.switch_to.frame(1) - >>> driver.switch_to.frame(driver.find_elements(By.TAG_NAME, "iframe")[0]) - >>> driver.switch_to.parent_frame() - >>> driver.switch_to.window("main") + `element = driver.switch_to.active_element` + `alert = driver.switch_to.alert` + `driver.switch_to.default_content()` + `driver.switch_to.frame("frame_name")` + `driver.switch_to.frame(1)` + `driver.switch_to.frame(driver.find_elements(By.TAG_NAME, "iframe")[0])` + `driver.switch_to.parent_frame()` + `driver.switch_to.window("main")` """ return self._switch_to # Navigation def back(self) -> None: - """Goes one step backward in the browser history. - - Example: - >>> driver.back() - """ + """Goes one step backward in the browser history.""" self.execute(Command.GO_BACK) def forward(self) -> None: - """Goes one step forward in the browser history. - - Example: - >>> driver.forward() - """ + """Goes one step forward in the browser history.""" self.execute(Command.GO_FORWARD) def refresh(self) -> None: - """Refreshes the current page. - - Example: - >>> driver.refresh() - """ + """Refreshes the current page.""" self.execute(Command.REFRESH) - # Options def get_cookies(self) -> list[dict]: """Returns a set of dictionaries, corresponding to cookies visible in the current session. @@ -679,9 +634,6 @@ def get_cookies(self) -> list[dict]: Returns: A list of dictionaries, corresponding to cookies visible in the current session. - - Example: - >>> cookies = driver.get_cookies() """ return self.execute(Command.GET_ALL_COOKIES)["value"] @@ -690,7 +642,7 @@ def get_cookie(self, name) -> Optional[dict]: or whitespace. Returns the cookie if found, None if not. Example: - >>> cookie = driver.get_cookie("my_cookie") + `cookie = driver.get_cookie("my_cookie")` """ if not name or name.isspace(): raise ValueError("Cookie name cannot be empty") @@ -705,20 +657,16 @@ def delete_cookie(self, name) -> None: the name is empty or whitespace. Example: - >>> driver.delete_cookie("my_cookie") + `driver.delete_cookie("my_cookie")` """ - # firefox deletes all cookies when "" is passed as name + # Firefox deletes all cookies when "" is passed as name if not name or name.isspace(): raise ValueError("Cookie name cannot be empty") self.execute(Command.DELETE_COOKIE, {"name": name}) def delete_all_cookies(self) -> None: - """Delete all cookies in the scope of the session. - - Example: - >>> driver.delete_all_cookies() - """ + """Delete all cookies in the scope of the session.""" self.execute(Command.DELETE_ALL_COOKIES) def add_cookie(self, cookie_dict) -> None: @@ -730,10 +678,10 @@ def add_cookie(self, cookie_dict) -> None: "expiry", "sameSite". Examples: - >>> driver.add_cookie({"name": "foo", "value": "bar"}) - >>> driver.add_cookie({"name": "foo", "value": "bar", "path": "/"}) - >>> driver.add_cookie({"name": "foo", "value": "bar", "path": "/", "secure": True}) - >>> driver.add_cookie({"name": "foo", "value": "bar", "sameSite": "Strict"}) + `driver.add_cookie({"name": "foo", "value": "bar"})` + `driver.add_cookie({"name": "foo", "value": "bar", "path": "/"})` + `driver.add_cookie({"name": "foo", "value": "bar", "path": "/", "secure": True})` + `driver.add_cookie({"name": "foo", "value": "bar", "sameSite": "Strict"})` """ if "sameSite" in cookie_dict: assert cookie_dict["sameSite"] in ["Strict", "Lax", "None"] @@ -752,7 +700,7 @@ def implicitly_wait(self, time_to_wait: float) -> None: time_to_wait: Amount of time to wait (in seconds). Example: - >>> driver.implicitly_wait(30) + `driver.implicitly_wait(30)` """ self.execute(Command.SET_TIMEOUTS, {"implicit": int(float(time_to_wait) * 1000)}) @@ -764,7 +712,7 @@ def set_script_timeout(self, time_to_wait: float) -> None: time_to_wait: The amount of time to wait (in seconds). Example: - >>> driver.set_script_timeout(30) + `driver.set_script_timeout(30)` """ self.execute(Command.SET_TIMEOUTS, {"script": int(float(time_to_wait) * 1000)}) @@ -776,7 +724,7 @@ def set_page_load_timeout(self, time_to_wait: float) -> None: time_to_wait: The amount of time to wait (in seconds). Example: - >>> driver.set_page_load_timeout(30) + `driver.set_page_load_timeout(30)` """ try: self.execute(Command.SET_TIMEOUTS, {"pageLoad": int(float(time_to_wait) * 1000)}) @@ -789,12 +737,12 @@ def timeouts(self) -> Timeouts: Returns: A named tuple with the following fields: - - implicit_wait: The time to wait for elements to be found. - - page_load: The time to wait for a page to load. - - script: The time to wait for scripts to execute. + - implicit_wait: The time to wait for elements to be found. + - page_load: The time to wait for a page to load. + - script: The time to wait for scripts to execute. Example: - >>> driver.timeouts + `driver.timeouts` """ timeouts = self.execute(Command.GET_TIMEOUTS)["value"] timeouts["implicit_wait"] = timeouts.pop("implicit") / 1000 @@ -808,9 +756,11 @@ def timeouts(self, timeouts) -> None: set timeouts. Example: - >>> my_timeouts = Timeouts() - >>> my_timeouts.implicit_wait = 10 - >>> driver.timeouts = my_timeouts + ``` + my_timeouts = Timeouts() + my_timeouts.implicit_wait = 10 + driver.timeouts = my_timeouts + ``` """ _ = self.execute(Command.SET_TIMEOUTS, timeouts._to_json())["value"] @@ -828,7 +778,7 @@ def find_element(self, by=By.ID, value: Optional[str] = None) -> WebElement: The first matching WebElement found on the page. Example: - element = driver.find_element(By.ID, 'foo') + `element = driver.find_element(By.ID, 'foo')` """ by, value = self.locator_converter.convert(by, value) @@ -854,7 +804,7 @@ def find_elements(self, by=By.ID, value: Optional[str] = None) -> list[WebElemen List of WebElements matching locator strategy found on the page. Example: - element = driver.find_elements(By.ID, 'foo') + `element = driver.find_elements(By.ID, 'foo')` """ by, value = self.locator_converter.convert(by, value) @@ -873,11 +823,7 @@ def find_elements(self, by=By.ID, value: Optional[str] = None) -> list[WebElemen @property def capabilities(self) -> dict: - """Returns the drivers current capabilities being used. - - Example: - >>> print(driver.capabilities) - """ + """Returns the drivers current capabilities being used.""" return self.caps def get_screenshot_as_file(self, filename) -> bool: @@ -890,7 +836,7 @@ def get_screenshot_as_file(self, filename) -> bool: should end with a `.png` extension. Example: - >>> driver.get_screenshot_as_file("/Screenshots/foo.png") + `driver.get_screenshot_as_file("./screenshots/foo.png")` """ if not str(filename).lower().endswith(".png"): warnings.warn( @@ -918,7 +864,7 @@ def save_screenshot(self, filename) -> bool: should end with a `.png` extension. Example: - >>> driver.save_screenshot("/Screenshots/foo.png") + `driver.save_screenshot("./screenshots/foo.png")` """ return self.get_screenshot_as_file(filename) @@ -926,7 +872,7 @@ def get_screenshot_as_png(self) -> bytes: """Gets the screenshot of the current window as a binary data. Example: - >>> driver.get_screenshot_as_png() + `driver.get_screenshot_as_png()` """ return b64decode(self.get_screenshot_as_base64().encode("ascii")) @@ -935,12 +881,12 @@ def get_screenshot_as_base64(self) -> str: which is useful in embedded images in HTML. Example: - >>> driver.get_screenshot_as_base64() + `driver.get_screenshot_as_base64()` """ return self.execute(Command.SCREENSHOT)["value"] def set_window_size(self, width, height, windowHandle: str = "current") -> None: - """Sets the width and height of the current window. (window.resizeTo) + """Sets the width and height of the current window. Args: width: The width in pixels to set the window to. @@ -948,7 +894,7 @@ def set_window_size(self, width, height, windowHandle: str = "current") -> None: windowHandle: The handle of the window to resize. Default is "current". Example: - >>> driver.set_window_size(800, 600) + `driver.set_window_size(800, 600)` """ self._check_if_window_handle_is_current(windowHandle) self.set_window_rect(width=int(width), height=int(height)) @@ -957,7 +903,7 @@ def get_window_size(self, windowHandle: str = "current") -> dict: """Gets the width and height of the current window. Example: - >>> driver.get_window_size() + `driver.get_window_size()` """ self._check_if_window_handle_is_current(windowHandle) size = self.get_window_rect() @@ -968,7 +914,7 @@ def get_window_size(self, windowHandle: str = "current") -> dict: return {k: size[k] for k in ("width", "height")} def set_window_position(self, x: float, y: float, windowHandle: str = "current") -> dict: - """Sets the x,y position of the current window. (window.moveTo) + """Sets the x,y position of the current window. Args: x: The x-coordinate in pixels to set the window position. @@ -976,7 +922,7 @@ def set_window_position(self, x: float, y: float, windowHandle: str = "current") windowHandle: The handle of the window to reposition. Default is "current". Example: - >>> driver.set_window_position(0, 0) + `driver.set_window_position(0, 0)` """ self._check_if_window_handle_is_current(windowHandle) return self.set_window_rect(x=int(x), y=int(y)) @@ -985,7 +931,7 @@ def get_window_position(self, windowHandle="current") -> dict: """Gets the x,y position of the current window. Example: - >>> driver.get_window_position() + `driver.get_window_position()` """ self._check_if_window_handle_is_current(windowHandle) position = self.get_window_rect() @@ -1002,7 +948,7 @@ def get_window_rect(self) -> dict: of the current window. Example: - >>> driver.get_window_rect() + `driver.get_window_rect()` """ return self.execute(Command.GET_WINDOW_RECT)["value"] @@ -1013,9 +959,9 @@ def set_window_rect(self, x=None, y=None, width=None, height=None) -> dict: `set_window_size`. Example: - >>> driver.set_window_rect(x=10, y=10) - >>> driver.set_window_rect(width=100, height=200) - >>> driver.set_window_rect(x=10, y=10, width=100, height=200) + `driver.set_window_rect(x=10, y=10)` + `driver.set_window_rect(width=100, height=200)` + `driver.set_window_rect(x=10, y=10, width=100, height=200)` """ if (x is None and y is None) and (not height and not width): raise InvalidArgumentException("x and y or height and width need values") @@ -1047,7 +993,7 @@ def orientation(self): """Gets the current orientation of the device. Example: - >>> orientation = driver.orientation + `orientation = driver.orientation` """ return self.execute(Command.GET_SCREEN_ORIENTATION)["value"] @@ -1059,7 +1005,7 @@ def orientation(self, value) -> None: value: Orientation to set it to. Example: - >>> driver.orientation = "landscape" + `driver.orientation = "landscape"` """ allowed_values = ["LANDSCAPE", "PORTRAIT"] if value.upper() in allowed_values: @@ -1161,10 +1107,10 @@ def browser(self): An object containing access to BiDi browser commands. Examples: - >>> user_context = driver.browser.create_user_context() - >>> user_contexts = driver.browser.get_user_contexts() - >>> client_windows = driver.browser.get_client_windows() - >>> driver.browser.remove_user_context(user_context) + `user_context = driver.browser.create_user_context()` + `user_contexts = driver.browser.get_user_contexts()` + `client_windows = driver.browser.get_client_windows()` + `driver.browser.remove_user_context(user_context)` """ if not self._websocket_connection: self._start_bidi() @@ -1196,10 +1142,10 @@ def browsing_context(self): An object containing access to BiDi browsing context commands. Examples: - >>> context_id = driver.browsing_context.create(type="tab") - >>> driver.browsing_context.navigate(context=context_id, url="https://www.selenium.dev") - >>> driver.browsing_context.capture_screenshot(context=context_id) - >>> driver.browsing_context.close(context_id) + `context_id = driver.browsing_context.create(type="tab")` + `driver.browsing_context.navigate(context=context_id, url="https://www.selenium.dev")` + `driver.browsing_context.capture_screenshot(context=context_id)` + `driver.browsing_context.close(context_id)` """ if not self._websocket_connection: self._start_bidi() @@ -1217,12 +1163,14 @@ def storage(self): An object containing access to BiDi storage commands. Examples: - >>> cookie_filter = CookieFilter(name="example") - >>> result = driver.storage.get_cookies(filter=cookie_filter) - >>> driver.storage.set_cookie(cookie=PartialCookie( - "name", BytesValue(BytesValue.TYPE_STRING, "value"), "domain") - ) - >>> driver.storage.delete_cookies(filter=CookieFilter(name="example")) + ``` + cookie_filter = CookieFilter(name="example") + result = driver.storage.get_cookies(filter=cookie_filter) + cookie=PartialCookie("name", BytesValue(BytesValue.TYPE_STRING, "value") + driver.storage.set_cookie(cookie=cookie, "domain")) + cookie_filter=CookieFilter(name="example") + driver.storage.delete_cookies(filter=cookie_filter) + ``` """ if not self._websocket_connection: self._start_bidi() @@ -1240,9 +1188,12 @@ def permissions(self): An object containing access to BiDi permissions commands. Examples: - >>> from selenium.webdriver.common.bidi.permissions import PermissionDescriptor, PermissionState - >>> descriptor = PermissionDescriptor("geolocation") - >>> driver.permissions.set_permission(descriptor, PermissionState.GRANTED, "https://example.com") + ``` + from selenium.webdriver.common.bidi.permissions import PermissionDescriptor, PermissionState + + descriptor = PermissionDescriptor("geolocation") + driver.permissions.set_permission(descriptor, PermissionState.GRANTED, "https://example.com") + ``` """ if not self._websocket_connection: self._start_bidi() @@ -1260,9 +1211,9 @@ def webextension(self): An object containing access to BiDi webextension commands. Examples: - >>> extension_path = "/path/to/extension" - >>> extension_result = driver.webextension.install(path=extension_path) - >>> driver.webextension.uninstall(extension_result) + `extension_path = "/path/to/extension"` + `extension_result = driver.webextension.install(path=extension_path)` + `driver.webextension.uninstall(extension_result)` """ if not self._websocket_connection: self._start_bidi() @@ -1280,9 +1231,12 @@ def emulation(self): An object containing access to BiDi emulation commands. Examples: - >>> from selenium.webdriver.common.bidi.emulation import GeolocationCoordinates - >>> coordinates = GeolocationCoordinates(37.7749, -122.4194) - >>> driver.emulation.set_geolocation_override(coordinates=coordinates, contexts=[context_id]) + ``` + from selenium.webdriver.common.bidi.emulation import GeolocationCoordinates + + coordinates = GeolocationCoordinates(37.7749, -122.4194) + driver.emulation.set_geolocation_override(coordinates=coordinates, contexts=[context_id]) + ``` """ if not self._websocket_connection: self._start_bidi() @@ -1300,10 +1254,13 @@ def input(self): An object containing access to BiDi input commands. Examples: - >>> from selenium.webdriver.common.bidi.input import KeySourceActions, KeyDownAction, KeyUpAction - >>> actions = KeySourceActions(id="keyboard", actions=[KeyDownAction(value="a"), KeyUpAction(value="a")]) - >>> driver.input.perform_actions(driver.current_window_handle, [actions]) - >>> driver.input.release_actions(driver.current_window_handle) + ``` + from selenium.webdriver.common.bidi.input import KeySourceActions, KeyDownAction, KeyUpAction + + actions = KeySourceActions(id="keyboard", actions=[KeyDownAction(value="a"), KeyUpAction(value="a")]) + driver.input.perform_actions(driver.current_window_handle, [actions]) + driver.input.release_actions(driver.current_window_handle) + ``` """ if not self._websocket_connection: self._start_bidi() @@ -1344,19 +1301,18 @@ def add_virtual_authenticator(self, options: VirtualAuthenticatorOptions) -> Non """Adds a virtual authenticator with the given options. Example: - >>> from selenium.webdriver.common.virtual_authenticator import VirtualAuthenticatorOptions - >>> options = VirtualAuthenticatorOptions(protocol="u2f", transport="usb", device_id="myDevice123") - >>> driver.add_virtual_authenticator(options) + ``` + from selenium.webdriver.common.virtual_authenticator import VirtualAuthenticatorOptions + + options = VirtualAuthenticatorOptions(protocol="u2f", transport="usb", device_id="myDevice123") + driver.add_virtual_authenticator(options) + ``` """ self._authenticator_id = self.execute(Command.ADD_VIRTUAL_AUTHENTICATOR, options.to_dict())["value"] @property def virtual_authenticator_id(self) -> Optional[str]: - """Returns the id of the virtual authenticator. - - Example: - >>> print(driver.virtual_authenticator_id) - """ + """Returns the id of the virtual authenticator.""" return self._authenticator_id @required_virtual_authenticator @@ -1365,9 +1321,6 @@ def remove_virtual_authenticator(self) -> None: The authenticator is no longer valid after removal, so no methods may be called. - - Example: - >>> driver.remove_virtual_authenticator() """ self.execute(Command.REMOVE_VIRTUAL_AUTHENTICATOR, {"authenticatorId": self._authenticator_id}) self._authenticator_id = None @@ -1377,19 +1330,18 @@ def add_credential(self, credential: Credential) -> None: """Injects a credential into the authenticator. Example: - >>> from selenium.webdriver.common.credential import Credential - >>> credential = Credential(id="user@example.com", password="aPassword") - >>> driver.add_credential(credential) + ``` + from selenium.webdriver.common.credential import Credential + + credential = Credential(id="user@example.com", password="aPassword") + driver.add_credential(credential) + ``` """ self.execute(Command.ADD_CREDENTIAL, {**credential.to_dict(), "authenticatorId": self._authenticator_id}) @required_virtual_authenticator def get_credentials(self) -> list[Credential]: - """Returns the list of credentials owned by the authenticator. - - Example: - >>> credentials = driver.get_credentials() - """ + """Returns the list of credentials owned by the authenticator.""" credential_data = self.execute(Command.GET_CREDENTIALS, {"authenticatorId": self._authenticator_id}) return [Credential.from_dict(credential) for credential in credential_data["value"]] @@ -1398,8 +1350,8 @@ def remove_credential(self, credential_id: Union[str, bytearray]) -> None: """Removes a credential from the authenticator. Example: - >>> credential_id = "user@example.com" - >>> driver.remove_credential(credential_id) + `credential_id = "user@example.com"` + `driver.remove_credential(credential_id)` """ # Check if the credential is bytearray converted to b64 string if isinstance(credential_id, bytearray): @@ -1411,11 +1363,7 @@ def remove_credential(self, credential_id: Union[str, bytearray]) -> None: @required_virtual_authenticator def remove_all_credentials(self) -> None: - """Removes all credentials from the authenticator. - - Example: - >>> driver.remove_all_credentials() - """ + """Removes all credentials from the authenticator.""" self.execute(Command.REMOVE_ALL_CREDENTIALS, {"authenticatorId": self._authenticator_id}) @required_virtual_authenticator @@ -1428,16 +1376,12 @@ def set_user_verified(self, verified: bool) -> None: False otherwise. Example: - >>> driver.set_user_verified(True) + `driver.set_user_verified(True)` """ self.execute(Command.SET_USER_VERIFIED, {"authenticatorId": self._authenticator_id, "isUserVerified": verified}) def get_downloadable_files(self) -> list: - """Retrieves the downloadable files as a list of file names. - - Example: - >>> files = driver.get_downloadable_files() - """ + """Retrieves the downloadable files as a list of file names.""" if "se:downloadsEnabled" not in self.capabilities: raise WebDriverException("You must enable downloads in order to work with downloadable files.") @@ -1453,7 +1397,7 @@ def download_file(self, file_name: str, target_directory: str) -> None: file. Example: - >>> driver.download_file("example.zip", "/path/to/directory") + `driver.download_file("example.zip", "/path/to/directory")` """ if "se:downloadsEnabled" not in self.capabilities: raise WebDriverException("You must enable downloads in order to work with downloadable files.") @@ -1472,11 +1416,7 @@ def download_file(self, file_name: str, target_directory: str) -> None: zip_ref.extractall(target_directory) def delete_downloadable_files(self) -> None: - """Deletes all downloadable files. - - Example: - >>> driver.delete_downloadable_files() - """ + """Deletes all downloadable files.""" if "se:downloadsEnabled" not in self.capabilities: raise WebDriverException("You must enable downloads in order to work with downloadable files.") @@ -1492,26 +1432,22 @@ def fedcm(self) -> FedCM: (FedCM) dialog commands. Examples: - >>> title = driver.fedcm.title - >>> subtitle = driver.fedcm.subtitle - >>> dialog_type = driver.fedcm.dialog_type - >>> accounts = driver.fedcm.account_list - >>> driver.fedcm.select_account(0) - >>> driver.fedcm.accept() - >>> driver.fedcm.dismiss() - >>> driver.fedcm.enable_delay() - >>> driver.fedcm.disable_delay() - >>> driver.fedcm.reset_cooldown() + `driver.fedcm.title` + `driver.fedcm.subtitle` + `driver.fedcm.dialog_type` + `driver.fedcm.account_list` + `driver.fedcm.select_account(0)` + `driver.fedcm.accept()` + `driver.fedcm.dismiss()` + `driver.fedcm.enable_delay()` + `driver.fedcm.disable_delay()` + `driver.fedcm.reset_cooldown()` """ return self._fedcm @property def supports_fedcm(self) -> bool: - """Returns whether the browser supports FedCM capabilities. - - Example: - >>> print(driver.supports_fedcm) - """ + """Returns whether the browser supports FedCM capabilities.""" return self.capabilities.get(ArgOptions.FEDCM_CAPABILITY, False) def _require_fedcm_support(self): @@ -1524,11 +1460,7 @@ def _require_fedcm_support(self): @property def dialog(self): - """Returns the FedCM dialog object for interaction. - - Example: - >>> dialog = driver.dialog - """ + """Returns the FedCM dialog object for interaction.""" self._require_fedcm_support() return Dialog(self) diff --git a/py/selenium/webdriver/safari/options.py b/py/selenium/webdriver/safari/options.py index 87e63f8947177..d9265ed5f624d 100644 --- a/py/selenium/webdriver/safari/options.py +++ b/py/selenium/webdriver/safari/options.py @@ -20,27 +20,24 @@ class _SafariOptionsDescriptor: - """_SafariOptionsDescriptor is an implementation of Descriptor protocol: + """_SafariOptionsDescriptor is an implementation of Descriptor protocol. - : Any look-up or assignment to the below attributes in `Options` class will be intercepted - by `__get__` and `__set__` method respectively. + Any look-up or assignment to the below attributes in `Options` class will be intercepted + by `__get__` and `__set__` method respectively when an attribute lookup happens: - - `automatic_inspection` - - `automatic_profiling` - - `use_technology_preview` - - : When an attribute lookup happens, + - `automatic_inspection` + - `automatic_profiling` + - `use_technology_preview` Example: `self.automatic_inspection` - `__get__` method does a dictionary look up in the dictionary `_caps` of `Options` class - and returns the value of key `safari:automaticInspection` - : When an attribute assignment happens, + (`__get__` method does a dictionary look up in the dictionary `_caps` of `Options` class + and returns the value of key `safari:automaticInspection`) Example: `self.automatic_inspection` = True - `__set__` method sets/updates the value of the key `safari:automaticInspection` in `_caps` - dictionary in `Options` class. + (`__set__` method sets/updates the value of the key `safari:automaticInspection` in `_caps` + dictionary in `Options` class) """ def __init__(self, name, expected_type): diff --git a/py/selenium/webdriver/support/select.py b/py/selenium/webdriver/support/select.py index 9453d05080fe5..dde724b954350 100644 --- a/py/selenium/webdriver/support/select.py +++ b/py/selenium/webdriver/support/select.py @@ -54,7 +54,7 @@ def all_selected_options(self) -> list[WebElement]: @property def first_selected_option(self) -> WebElement: """The first selected option in this select tag (or the currently - selected option in a normal select) + selected option in a normal select). """ for opt in self.options: if opt.is_selected(): @@ -62,10 +62,12 @@ def first_selected_option(self) -> WebElement: raise NoSuchElementException("No options are selected") def select_by_value(self, value: str) -> None: - """Select all options that have a value matching the argument. That is, - when given "foo" this would select an option like: + """Select all options that have a value matching the argument. - + Example: + When given "foo" this would select an option like: + + `` Args: value: The value to match against @@ -102,10 +104,12 @@ def select_by_index(self, index: int) -> None: raise NoSuchElementException(f"Could not locate element with index {index}") def select_by_visible_text(self, text: str) -> None: - """Select all options that display text matching the argument. That is, - when given "Bar" this would select an option like: + """Select all options that display text matching the argument. + + Example: + When given "Bar" this would select an option like: - + `` Args: text: The visible text to match against @@ -156,10 +160,12 @@ def deselect_all(self) -> None: self._unset_selected(opt) def deselect_by_value(self, value: str) -> None: - """Deselect all options that have a value matching the argument. That - is, when given "foo" this would deselect an option like: + """Deselect all options that have a value matching the argument. - + Example: + When given "foo" this would deselect an option like: + + `` Args: value: The value to match against @@ -197,10 +203,12 @@ def deselect_by_index(self, index: int) -> None: raise NoSuchElementException(f"Could not locate element with index {index}") def deselect_by_visible_text(self, text: str) -> None: - """Deselect all options that display text matching the argument. That - is, when given "Bar" this would deselect an option like: + """Deselect all options that display text matching the argument. + + Example: + when given "Bar" this would deselect an option like: - + `` Args: text: The visible text to match against diff --git a/py/test/selenium/webdriver/common/webserver.py b/py/test/selenium/webdriver/common/webserver.py index 31805c5acdcdb..8969e759f16f7 100644 --- a/py/test/selenium/webdriver/common/webserver.py +++ b/py/test/selenium/webdriver/common/webserver.py @@ -132,7 +132,7 @@ def do_POST(self): self.send_error(500, f"Error found: {e}") def log_message(self, format, *args): - """Override default to avoid trashing stderr""" + """Override default to avoid trashing stderr.""" pass diff --git a/py/test/selenium/webdriver/remote/remote_connection_tests.py b/py/test/selenium/webdriver/remote/remote_connection_tests.py index 4a3c155881047..6e313ce2e58b8 100644 --- a/py/test/selenium/webdriver/remote/remote_connection_tests.py +++ b/py/test/selenium/webdriver/remote/remote_connection_tests.py @@ -28,7 +28,7 @@ def test_browser_specific_method(firefox_options, webserver): - """This only works on Firefox""" + """This only works on Firefox.""" server_addr = f"http://{webserver.host}:{webserver.port}" with webdriver.Remote(options=firefox_options) as driver: driver.get(f"{server_addr}/simpleTest.html")