Skip to content

Commit

Permalink
[py] Change formatted strings to f-strings (#11087)
Browse files Browse the repository at this point in the history
Change formatted strings to f-strings

Co-authored-by: Diego Molina <[email protected]>
  • Loading branch information
kianelbo and diemol authored Dec 7, 2022
1 parent aa8d6cf commit d8b45c8
Show file tree
Hide file tree
Showing 15 changed files with 57 additions and 62 deletions.
2 changes: 1 addition & 1 deletion py/selenium/webdriver/common/action_chains.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ def scroll_from_origin(self, scroll_origin: ScrollOrigin, delta_x: int, delta_y:
"""

if not isinstance(scroll_origin, ScrollOrigin):
raise TypeError("Expected object of type ScrollOrigin, got: " "{}".format(type(scroll_origin)))
raise TypeError(f"Expected object of type ScrollOrigin, got: {type(scroll_origin)}")

self.w3c_actions.wheel_action.scroll(
origin=scroll_origin.origin,
Expand Down
2 changes: 1 addition & 1 deletion py/selenium/webdriver/common/actions/pointer_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class PointerInput(InputDevice):
def __init__(self, kind, name):
super().__init__()
if kind not in POINTER_KINDS:
raise InvalidArgumentException("Invalid PointerInput kind '%s'" % kind)
raise InvalidArgumentException(f"Invalid PointerInput kind '{kind}'")
self.type = POINTER
self.kind = kind
self.name = name
Expand Down
6 changes: 3 additions & 3 deletions py/selenium/webdriver/common/bidi/cdp.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def __init__(self, obj):
self.detail = obj.get("data")

def __str__(self):
return "BrowserError<code={} message={}> {}".format(self.code, self.message, self.detail)
return f"BrowserError<code={self.code} message={self.message}> {self.detail}"


class CdpConnectionClosed(WsConnectionClosed):
Expand Down Expand Up @@ -261,7 +261,7 @@ def _handle_cmd_response(self, data):
try:
cmd, event = self.inflight_cmd.pop(cmd_id)
except KeyError:
logger.warning("Got a message with a command ID that does" " not exist: {}".format(data))
logger.warning(f"Got a message with a command ID that does not exist: {data}")
return
if "error" in data:
# If the server reported an error, convert it to an exception and do
Expand Down Expand Up @@ -440,7 +440,7 @@ async def _reader_task(self):
try:
session = self.sessions[session_id]
except KeyError:
raise BrowserError("Browser sent a message for an invalid " "session: {!r}".format(session_id))
raise BrowserError(f"Browser sent a message for an invalid session: {session_id!r}")
session._handle_data(data)
else:
self._handle_data(data)
Expand Down
6 changes: 3 additions & 3 deletions py/selenium/webdriver/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ def join_host_port(host: str, port: int) -> str:
"""
if ":" in host and not host.startswith("["):
return "[%s]:%d" % (host, port)
return "%s:%d" % (host, port)
return f"[{host}]:{port}"
return f"{host}:{port}"


def is_connectable(port: int, host: Optional[str] = "localhost") -> bool:
Expand Down Expand Up @@ -127,7 +127,7 @@ def is_url_connectable(port: Union[int, str]) -> bool:
from urllib import request as url_request

try:
res = url_request.urlopen("http://127.0.0.1:%s/status" % port)
res = url_request.urlopen(f"http://127.0.0.1:{port}/status")
return res.getcode() == 200
except Exception:
return False
Expand Down
4 changes: 2 additions & 2 deletions py/selenium/webdriver/firefox/extension_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __init__(self, host, firefox_profile, firefox_binary=None, timeout=30):
self.profile.add_extension()

self.binary.launch_browser(self.profile, timeout=timeout)
_URL = "http://%s:%d/hub" % (HOST, PORT)
_URL = f"http://{HOST}:{PORT}/hub"
super().__init__(_URL, keep_alive=True)

def quit(self, sessionId=None):
Expand All @@ -66,7 +66,7 @@ def connect(self):
@classmethod
def connect_and_quit(cls):
"""Connects to an running browser and quit immediately."""
cls._request("%s/extensions/firefox/quit" % _URL)
cls._request(f"{_URL}/extensions/firefox/quit")

@classmethod
def is_connectable(cls):
Expand Down
4 changes: 2 additions & 2 deletions py/selenium/webdriver/firefox/firefox_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ def _wait_until_connectable(self, timeout=30):
raise WebDriverException(
"Can't load the profile. Possible firefox version mismatch. "
"You must use GeckoDriver instead for Firefox 48+. Profile "
"Dir: %s If you specified a log_file in the "
"FirefoxBinary constructor, check it for details." % (self.profile.path)
f"Dir: {self.profile.path} If you specified a log_file in the "
"FirefoxBinary constructor, check it for details."
)
count += 1
time.sleep(1)
Expand Down
9 changes: 4 additions & 5 deletions py/selenium/webdriver/firefox/firefox_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,7 @@ def _read_existing_userjs(self, userjs):
self.default_preferences[matches.group(1)] = json.loads(matches.group(2))
except Exception:
warnings.warn(
"(skipping) failed to json.loads existing preference: %s" % matches.group(1)
+ matches.group(2)
f"(skipping) failed to json.loads existing preference: {matches.group(1) + matches.group(2)}"
)
except Exception:
# The profile given hasn't had any changes made, i.e no users.js
Expand Down Expand Up @@ -233,7 +232,7 @@ def _install_extension(self, addon, unpack=True):
# determine the addon id
addon_details = self._addon_details(addon)
addon_id = addon_details.get("id")
assert addon_id, "The addon id could not be found: %s" % addon
assert addon_id, f"The addon id could not be found: {addon}"

# copy the addon to the profile
addon_path = os.path.join(self.extensionsDir, addon_id)
Expand Down Expand Up @@ -300,7 +299,7 @@ def parse_manifest_json(content):
}

if not os.path.exists(addon_path):
raise OSError("Add-on path does not exist: %s" % addon_path)
raise OSError(f"Add-on path does not exist: {addon_path}")

try:
if zipfile.is_zipfile(addon_path):
Expand All @@ -324,7 +323,7 @@ def parse_manifest_json(content):
with open(os.path.join(addon_path, "install.rdf"), encoding="utf-8") as f:
manifest = f.read()
else:
raise OSError("Add-on path is neither an XPI nor a directory: %s" % addon_path)
raise OSError(f"Add-on path is neither an XPI nor a directory: {addon_path}")
except (OSError, KeyError) as e:
raise AddonFormatError(str(e), sys.exc_info()[2])

Expand Down
2 changes: 1 addition & 1 deletion py/selenium/webdriver/remote/errorhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ def check_response(self, response: Dict[str, Any]) -> None:
file = f"{file}:{line}"
meth = frame.get("methodName", "<anonymous>")
if "className" in frame:
meth = "{}.{}".format(frame["className"], meth)
meth = f"{frame['className']}.{meth}"
msg = " at %s (%s)"
msg = msg % (meth, file)
stacktrace.append(msg)
Expand Down
4 changes: 2 additions & 2 deletions py/selenium/webdriver/remote/remote_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def get_remote_connection_headers(cls, parsed_url, keep_alive=False):
}

if parsed_url.username:
base64string = b64encode("{0.username}:{0.password}".format(parsed_url).encode())
base64string = b64encode(f"{parsed_url.username}:{parsed_url.password}".encode())
headers.update({"Authorization": f"Basic {base64string.decode()}"})

if keep_alive:
Expand Down Expand Up @@ -285,7 +285,7 @@ def execute(self, command, params):
its JSON payload.
"""
command_info = self._commands[command]
assert command_info is not None, "Unrecognised command %s" % command
assert command_info is not None, f"Unrecognised command {command}"
path = string.Template(command_info[1]).substitute(params)
if isinstance(params, dict) and "sessionId" in params:
del params["sessionId"]
Expand Down
12 changes: 6 additions & 6 deletions py/selenium/webdriver/remote/shadowroot.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,26 +43,26 @@ def __repr__(self) -> str:
def find_element(self, by: str = By.ID, value: str = None):
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
value = f'[id="{value}"]'
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
value = f".{value}"
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
value = f'[name="{value}"]'

return self._execute(Command.FIND_ELEMENT_FROM_SHADOW_ROOT, {"using": by, "value": value})["value"]

def find_elements(self, by: str = By.ID, value: str = None):
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
value = f'[id="{value}"]'
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
value = f".{value}"
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
value = f'[name="{value}"]'

return self._execute(Command.FIND_ELEMENTS_FROM_SHADOW_ROOT, {"using": by, "value": value})["value"]

Expand Down
14 changes: 7 additions & 7 deletions py/selenium/webdriver/remote/webdriver.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ def __init__(
self.start_session(capabilities, browser_profile)

def __repr__(self):
return '<{0.__module__}.{0.__name__} (session="{1}")>'.format(type(self), self.session_id)
return f'<{type(self).__module__}.{type(self).__name__} (session="{self.session_id}")>'

def __enter__(self):
return self
Expand Down Expand Up @@ -850,13 +850,13 @@ def find_element(self, by=By.ID, value: Optional[str] = None) -> WebElement:

if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
value = f'[id="{value}"]'
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
value = f".{value}"
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
value = f'[name="{value}"]'

return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]

Expand All @@ -879,13 +879,13 @@ def find_elements(self, by=By.ID, value: Optional[str] = None) -> List[WebElemen

if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
value = f'[id="{value}"]'
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
value = f".{value}"
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
value = f'[name="{value}"]'

# Return empty list if driver returns null
# See https://github.com/SeleniumHQ/selenium/issues/4555
Expand Down
16 changes: 6 additions & 10 deletions py/selenium/webdriver/remote/webelement.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,7 @@ def __init__(self, parent, id_):
self._id = id_

def __repr__(self):
return '<{0.__module__}.{0.__name__} (session="{1}", element="{2}")>'.format(
type(self), self._parent.session_id, self._id
)
return f'<{type(self).__module__}.{type(self).__name__} (session="{self._parent.session_id}", element="{self._id}")>'

@property
def tag_name(self) -> str:
Expand Down Expand Up @@ -176,9 +174,7 @@ def get_attribute(self, name) -> str:
"""
if getAttribute_js is None:
_load_js()
attribute_value = self.parent.execute_script(
"return (%s).apply(null, arguments);" % getAttribute_js, self, name
)
attribute_value = self.parent.execute_script(f"return ({getAttribute_js}).apply(null, arguments);", self, name)
return attribute_value

def is_selected(self) -> bool:
Expand Down Expand Up @@ -261,7 +257,7 @@ def is_displayed(self) -> bool:
# Only go into this conditional for browsers that don't use the atom themselves
if isDisplayed_js is None:
_load_js()
return self.parent.execute_script("return (%s).apply(null, arguments);" % isDisplayed_js, self)
return self.parent.execute_script(f"return ({isDisplayed_js}).apply(null, arguments);", self)

@property
def location_once_scrolled_into_view(self) -> dict:
Expand Down Expand Up @@ -422,13 +418,13 @@ def find_element(self, by=By.ID, value=None) -> WebElement:
"""
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
value = f'[id="{value}"]'
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
value = f".{value}"
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
value = f'[name="{value}"]'

return self._execute(Command.FIND_CHILD_ELEMENT, {"using": by, "value": value})["value"]

Expand Down
6 changes: 3 additions & 3 deletions py/selenium/webdriver/support/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,11 @@ def __init__(self, red: ParseableInt, green: ParseableInt, blue: ParseableInt, a

@property
def rgb(self) -> str:
return "rgb(%d, %d, %d)" % (self.red, self.green, self.blue)
return f"rgb({self.red}, {self.green}, {self.blue})"

@property
def rgba(self) -> str:
return "rgba(%d, %d, %d, %s)" % (self.red, self.green, self.blue, self.alpha)
return f"rgba({self.red}, {self.green}, {self.blue}, {self.alpha})"

@property
def hex(self) -> str:
Expand All @@ -175,7 +175,7 @@ def __hash__(self) -> int:
return hash((self.red, self.green, self.blue, self.alpha))

def __repr__(self) -> str:
return "Color(red=%d, green=%d, blue=%d, alpha=%s)" % (self.red, self.green, self.blue, self.alpha)
return f"Color(red={self.red}, green={self.green}, blue={self.blue}, alpha={self.alpha})"

def __str__(self) -> str:
return f"Color: {self.rgba}"
Expand Down
Loading

0 comments on commit d8b45c8

Please sign in to comment.