0

[py] python3.7+ syntax throughout *.py files. ()

* upgrading python to `3.7+` throughout

* additional `f` conversions

* fix `flake8` violations; tidy up formatting

* make python3 changes apply to only `/py`

NOKEYCHECK=True
GitOrigin-RevId: 31cc432099851bc9aa68c443b448ff97d7ad91ca
This commit is contained in:
Simon K
2022-06-13 19:05:38 +01:00
committed by Copybara-Service
parent d3e9104cb5
commit 7a1e6d02a9
45 changed files with 95 additions and 101 deletions

@@ -88,7 +88,7 @@ def driver(request):
pytest.skip("Webkit tests can only run on Linux")
# conditionally mark tests as expected to fail based on driver
marker = request.node.get_closest_marker('xfail_{0}'.format(driver_class.lower()))
marker = request.node.get_closest_marker(f'xfail_{driver_class.lower()}')
if marker is not None:
if "run" in marker.kwargs:
@@ -149,7 +149,7 @@ def get_options(driver_class, config):
if browser_path or browser_args:
if not options:
options = getattr(webdriver, '{}Options'.format(driver_class))()
options = getattr(webdriver, f'{driver_class}Options')()
if driver_class == 'WebKitGTK':
options.overlay_scrollbars_enabled = False
if browser_path is not None:
@@ -213,12 +213,12 @@ def server(request):
try:
urlopen(url)
return 1
except IOError:
except OSError:
time.sleep(0.2)
return 0
_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
url = 'http://{}:{}/status'.format(_host, _port)
url = f'http://{_host}:{_port}/status'
try:
_socket.connect((_host, _port))
print('The remote driver server is already running or something else'
@@ -226,8 +226,8 @@ def server(request):
except Exception:
print('Starting the Selenium server')
process = subprocess.Popen(['java', '-jar', _path, 'standalone', '--port', '4444'])
print('Selenium server running as process: {}'.format(process.pid))
assert wait_for_server(url, 10), 'Timed out waiting for Selenium server at {}'.format(url)
print(f'Selenium server running as process: {process.pid}')
assert wait_for_server(url, 10), f'Timed out waiting for Selenium server at {url}'
print('Selenium server is ready')
yield process
process.terminate()

@@ -15,7 +15,6 @@
# specific language governing permissions and limitations
# under the License.
from __future__ import unicode_literals
import sys
import os

@@ -124,7 +124,7 @@ def inline_doc(description):
return ''
description = escape_backticks(description)
lines = ['#: {}'.format(l) for l in description.split('\n')]
lines = [f'#: {l}' for l in description.split('\n')]
return '\n'.join(lines)
@@ -162,7 +162,7 @@ def ref_to_python(ref):
'''
if '.' in ref:
domain, subtype = ref.split('.')
ref = '{}.{}'.format(snake_case(domain), subtype)
ref = f'{snake_case(domain)}.{subtype}'
return f"{ref}"
@@ -228,7 +228,7 @@ class CdpProperty:
if self.items:
if self.items.ref:
py_ref = ref_to_python(self.items.ref)
ann = "typing.List[{}]".format(py_ref)
ann = f"typing.List[{py_ref}]"
else:
ann = 'typing.List[{}]'.format(
CdpPrimitiveType.get_annotation(self.items.type))
@@ -500,7 +500,7 @@ class CdpParameter(CdpProperty):
py_type = f'typing.List[{nested_type}]'
else:
if self.ref:
py_type = "{}".format(ref_to_python(self.ref))
py_type = f"{ref_to_python(self.ref)}"
else:
py_type = CdpPrimitiveType.get_annotation(
typing.cast(str, self.type))
@@ -939,7 +939,7 @@ def parse(json_path, output_path):
:returns: a list of CDP domain objects
'''
global current_version
with open(json_path, "r") as json_file:
with open(json_path) as json_file:
schema = json.load(json_file)
version = schema['version']
assert (version['major'], version['minor']) == ('1', '3')
@@ -960,7 +960,7 @@ def generate_init(init_path, domains):
with open(init_path, "w") as init_file:
init_file.write(INIT_HEADER)
for domain in domains:
init_file.write('from . import {}\n'.format(domain.module))
init_file.write(f'from . import {domain.module}\n')
init_file.write('from . import util\n\n')

@@ -138,11 +138,11 @@ class UnexpectedAlertPresentException(WebDriverException):
"""
def __init__(self, msg: Optional[str] = None, screen: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None, alert_text: Optional[str] = None) -> None:
super(UnexpectedAlertPresentException, self).__init__(msg, screen, stacktrace)
super().__init__(msg, screen, stacktrace)
self.alert_text = alert_text
def __str__(self) -> str:
return "Alert Text: %s\n%s" % (self.alert_text, super(UnexpectedAlertPresentException, self).__str__())
return f"Alert Text: {self.alert_text}\n{super().__str__()}"
class NoAlertPresentException(WebDriverException):

@@ -39,7 +39,7 @@ class Service(service.ChromiumService):
- service_args : List of args to pass to the chromedriver service
- log_path : Path for the chromedriver service to log to"""
super(Service, self).__init__(
super().__init__(
executable_path,
port,
service_args,

@@ -20,7 +20,6 @@ from .options import Options
from .service import DEFAULT_EXECUTABLE_PATH, Service
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
DEFAULT_PORT = 0
DEFAULT_SERVICE_LOG_PATH = None
DEFAULT_KEEP_ALIVE = None
@@ -67,7 +66,7 @@ class WebDriver(ChromiumDriver):
if not service:
service = Service(executable_path, port, service_args, service_log_path)
super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog",
port, options,
service_args, desired_capabilities,
service_log_path, service, keep_alive)
super().__init__(DesiredCapabilities.CHROME['browserName'], "goog",
port, options,
service_args, desired_capabilities,
service_log_path, service, keep_alive)

@@ -28,7 +28,7 @@ class ChromiumOptions(ArgOptions):
KEY = "goog:chromeOptions"
def __init__(self) -> None:
super(ChromiumOptions, self).__init__()
super().__init__()
self._binary_location = ''
self._extension_files = []
self._extensions = []
@@ -98,7 +98,7 @@ class ChromiumOptions(ArgOptions):
if os.path.exists(extension_to_add):
self._extension_files.append(extension_to_add)
else:
raise IOError("Path to the extension doesn't exist")
raise OSError("Path to the extension doesn't exist")
else:
raise ValueError("argument can not be null")

@@ -27,10 +27,10 @@ class ChromiumRemoteConnection(RemoteConnection):
self._commands["setNetworkConditions"] = ('POST', '/session/$sessionId/chromium/network_conditions')
self._commands["getNetworkConditions"] = ('GET', '/session/$sessionId/chromium/network_conditions')
self._commands["deleteNetworkConditions"] = ('DELETE', '/session/$sessionId/chromium/network_conditions')
self._commands['executeCdpCommand'] = ('POST', '/session/$sessionId/{}/cdp/execute'.format(vendor_prefix))
self._commands['getSinks'] = ('GET', '/session/$sessionId/{}/cast/get_sinks'.format(vendor_prefix))
self._commands['getIssueMessage'] = ('GET', '/session/$sessionId/{}/cast/get_issue_message'.format(vendor_prefix))
self._commands['setSinkToUse'] = ('POST', '/session/$sessionId/{}/cast/set_sink_to_use'.format(vendor_prefix))
self._commands['startDesktopMirroring'] = ('POST', '/session/$sessionId/{}/cast/start_desktop_mirroring'.format(vendor_prefix))
self._commands['startTabMirroring'] = ('POST', '/session/$sessionId/{}/cast/start_tab_mirroring'.format(vendor_prefix))
self._commands['stopCasting'] = ('POST', '/session/$sessionId/{}/cast/stop_casting'.format(vendor_prefix))
self._commands['executeCdpCommand'] = ('POST', f'/session/$sessionId/{vendor_prefix}/cdp/execute')
self._commands['getSinks'] = ('GET', f'/session/$sessionId/{vendor_prefix}/cast/get_sinks')
self._commands['getIssueMessage'] = ('GET', f'/session/$sessionId/{vendor_prefix}/cast/get_issue_message')
self._commands['setSinkToUse'] = ('POST', f'/session/$sessionId/{vendor_prefix}/cast/set_sink_to_use')
self._commands['startDesktopMirroring'] = ('POST', f'/session/$sessionId/{vendor_prefix}/cast/start_desktop_mirroring')
self._commands['startTabMirroring'] = ('POST', f'/session/$sessionId/{vendor_prefix}/cast/start_tab_mirroring')
self._commands['stopCasting'] = ('POST', f'/session/$sessionId/{vendor_prefix}/cast/stop_casting')

@@ -20,13 +20,13 @@ KEY = "key"
POINTER = "pointer"
NONE = "none"
WHEEL = "wheel"
SOURCE_TYPES = set([KEY, POINTER, NONE])
SOURCE_TYPES = {KEY, POINTER, NONE}
POINTER_MOUSE = "mouse"
POINTER_TOUCH = "touch"
POINTER_PEN = "pen"
POINTER_KINDS = set([POINTER_MOUSE, POINTER_TOUCH, POINTER_PEN])
POINTER_KINDS = {POINTER_MOUSE, POINTER_TOUCH, POINTER_PEN}
class Interaction:

@@ -25,7 +25,7 @@ class KeyActions(Interaction):
if not source:
source = KeyInput(KEY)
self.source = source
super(KeyActions, self).__init__(source)
super().__init__(source)
def key_down(self, letter):
return self._key_action("create_key_down", letter)

@@ -23,7 +23,7 @@ from .interaction import (Interaction,
class KeyInput(InputDevice):
def __init__(self, name) -> None:
super(KeyInput, self).__init__()
super().__init__()
self.name = name
self.type = interaction.KEY
@@ -43,7 +43,7 @@ class KeyInput(InputDevice):
class TypingInteraction(Interaction):
def __init__(self, source, type_, key) -> None:
super(TypingInteraction, self).__init__(source)
super().__init__(source)
self.type = type_
self.key = key

@@ -35,7 +35,7 @@ class PointerActions(Interaction):
source = PointerInput(interaction.POINTER_MOUSE, "mouse")
self.source = source
self._duration = duration
super(PointerActions, self).__init__(source)
super().__init__(source)
def pointer_down(self, button=MouseButton.LEFT, width=None, height=None, pressure=None,
tangential_pressure=None, tilt_x=None, tilt_y=None, twist=None,

@@ -26,7 +26,7 @@ class PointerInput(InputDevice):
DEFAULT_MOVE_DURATION = 250
def __init__(self, kind, name):
super(PointerInput, self).__init__()
super().__init__()
if kind not in POINTER_KINDS:
raise InvalidArgumentException("Invalid PointerInput kind '%s'" % kind)
self.type = POINTER

@@ -23,7 +23,7 @@ class WheelActions(Interaction):
def __init__(self, source: WheelInput = None):
if not source:
source = WheelInput("wheel")
super(WheelActions, self).__init__(source)
super().__init__(source)
def pause(self, duration=0):
self.source.create_pause(duration)

@@ -169,7 +169,7 @@ class CdpConnectionClosed(WsConnectionClosed):
def __repr__(self):
''' Return representation. '''
return '{}<{}>'.format(self.__class__.__name__, self.reason)
return f'{self.__class__.__name__}<{self.reason}>'
class InternalError(Exception):

@@ -26,7 +26,7 @@ class BaseOptions(metaclass=ABCMeta):
"""
def __init__(self):
super(BaseOptions, self).__init__()
super().__init__()
self._caps = self.default_capabilities
self.set_capability("pageLoadStrategy", "normal")
self.mobile_options = None
@@ -226,7 +226,7 @@ class BaseOptions(metaclass=ABCMeta):
class ArgOptions(BaseOptions):
def __init__(self):
super(ArgOptions, self).__init__()
super().__init__()
self._arguments = []
self._ignore_local_proxy = False

@@ -79,12 +79,12 @@ class Service:
except OSError as err:
if err.errno == errno.ENOENT:
raise WebDriverException(
"'%s' executable needs to be in PATH. %s" % (
"'{}' executable needs to be in PATH. {}".format(
os.path.basename(self.path), self.start_error_message)
)
elif err.errno == errno.EACCES:
raise WebDriverException(
"'%s' executable may have wrong permissions. %s" % (
"'{}' executable may have wrong permissions. {}".format(
os.path.basename(self.path), self.start_error_message)
)
else:

@@ -23,7 +23,7 @@ class Options(ChromiumOptions):
KEY = "ms:edgeOptions"
def __init__(self):
super(Options, self).__init__()
super().__init__()
self._use_webview = False
@property
@@ -39,7 +39,7 @@ class Options(ChromiumOptions):
Creates a capabilities with all the options that have been set and
:Returns: A dictionary with everything
"""
caps = super(Options, self).to_capabilities()
caps = super().to_capabilities()
if self._use_webview:
caps['browserName'] = 'webview2'

@@ -46,7 +46,7 @@ class Service(service.ChromiumService):
if verbose:
self.service_args.append("--verbose")
super(Service, self).__init__(
super().__init__(
executable_path,
port,
service_args,

@@ -20,7 +20,6 @@ from .options import Options
from .service import DEFAULT_EXECUTABLE_PATH, Service
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
DEFAULT_PORT = 0
DEFAULT_SERVICE_LOG_PATH = None
@@ -59,10 +58,10 @@ class WebDriver(ChromiumDriver):
if not service:
service = Service(executable_path, port, service_args, service_log_path)
super(WebDriver, self).__init__(DesiredCapabilities.EDGE['browserName'], "ms",
port, options,
service_args, capabilities,
service_log_path, service, keep_alive)
super().__init__(DesiredCapabilities.EDGE['browserName'], "ms",
port, options,
service_args, capabilities,
service_log_path, service, keep_alive)
def create_options(self) -> Options:
return Options()

@@ -182,7 +182,7 @@ class FirefoxProfile:
"""
with open(self.userPrefs, "w") as f:
for key, value in user_prefs.items():
f.write('user_pref("%s", %s);\n' % (key, json.dumps(value)))
f.write(f'user_pref("{key}", {json.dumps(value)});\n')
def _read_existing_userjs(self, userjs):
import warnings
@@ -304,7 +304,7 @@ class FirefoxProfile:
}
if not os.path.exists(addon_path):
raise IOError('Add-on path does not exist: %s' % addon_path)
raise OSError('Add-on path does not exist: %s' % addon_path)
try:
if zipfile.is_zipfile(addon_path):
@@ -322,14 +322,14 @@ class FirefoxProfile:
elif os.path.isdir(addon_path):
manifest_json_filename = os.path.join(addon_path, 'manifest.json')
if os.path.exists(manifest_json_filename):
with open(manifest_json_filename, 'r') as f:
with open(manifest_json_filename) as f:
return parse_manifest_json(f.read())
with open(os.path.join(addon_path, 'install.rdf'), 'r') as f:
with open(os.path.join(addon_path, 'install.rdf')) as f:
manifest = f.read()
else:
raise IOError('Add-on path is neither an XPI nor a directory: %s' % addon_path)
except (IOError, KeyError) as e:
raise OSError('Add-on path is neither an XPI nor a directory: %s' % addon_path)
except (OSError, KeyError) as e:
raise AddonFormatError(str(e), sys.exc_info()[2])
try:

@@ -36,7 +36,7 @@ class Options(ArgOptions):
KEY = "moz:firefoxOptions"
def __init__(self):
super(Options, self).__init__()
super().__init__()
self._binary: FirefoxBinary = None
self._preferences: dict = {}
self._profile = None

@@ -295,7 +295,7 @@ class WebDriver(RemoteWebDriver):
try:
with open(filename, 'wb') as f:
f.write(png)
except IOError:
except OSError:
return False
finally:
del png

@@ -49,7 +49,7 @@ class Options(ArgOptions):
EDGE_EXECUTABLE_PATH = 'ie.edgepath'
def __init__(self):
super(Options, self).__init__()
super().__init__()
self._options = {}
self._additional = {}

@@ -228,10 +228,10 @@ class ErrorHandler:
line = self._value_or_default(frame, 'lineNumber', '')
file = self._value_or_default(frame, 'fileName', '<anonymous>')
if line:
file = "%s:%s" % (file, line)
file = f"{file}:{line}"
meth = self._value_or_default(frame, 'methodName', '<anonymous>')
if 'className' in frame:
meth = "%s.%s" % (frame['className'], meth)
meth = "{}.{}".format(frame['className'], meth)
msg = " at %s (%s)"
msg = msg % (meth, file)
stacktrace.append(msg)

@@ -106,13 +106,13 @@ class RemoteConnection:
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
'User-Agent': 'selenium/{} (python {})'.format(__version__, system)
'User-Agent': f'selenium/{__version__} (python {system})'
}
if parsed_url.username:
base64string = b64encode('{0.username}:{0.password}'.format(parsed_url).encode())
headers.update({
'Authorization': 'Basic {}'.format(base64string.decode())
'Authorization': f'Basic {base64string.decode()}'
})
if keep_alive:

@@ -872,7 +872,7 @@ class WebDriver(BaseWebDriver):
if isinstance(by, RelativeBy):
_pkg = '.'.join(__name__.split('.')[:-1])
raw_function = pkgutil.get_data(_pkg, 'findElements.js').decode('utf8')
find_element_js = "return ({}).apply(null, arguments);".format(raw_function)
find_element_js = f"return ({raw_function}).apply(null, arguments);"
return self.execute_script(find_element_js, by.to_dict())
if by == By.ID:
@@ -929,7 +929,7 @@ class WebDriver(BaseWebDriver):
try:
with open(filename, 'wb') as f:
f.write(png)
except IOError:
except OSError:
return False
finally:
del png

@@ -25,7 +25,6 @@ import warnings
import zipfile
from abc import ABCMeta
from io import BytesIO
from typing import Union
from selenium.common.exceptions import WebDriverException, JavascriptException
from selenium.webdriver.common.by import By
@@ -110,7 +109,7 @@ class WebElement(BaseWebElement):
"""Clears the text if it's a text entry element."""
self._execute(Command.CLEAR_ELEMENT)
def get_property(self, name) -> Union[str, bool, WebElement, dict]:
def get_property(self, name) -> str | bool | WebElement | dict:
"""
Gets the given property of the element.
@@ -351,7 +350,7 @@ class WebElement(BaseWebElement):
try:
with open(filename, 'wb') as f:
f.write(png)
except IOError:
except OSError:
return False
finally:
del png

@@ -38,7 +38,7 @@ class Options(ArgOptions):
SAFARI_TECH_PREVIEW = 'Safari Technology Preview'
def __init__(self):
super(Options, self).__init__()
super().__init__()
self._binary_location = None
self._preferences: dict = {}
self.log = Log()

@@ -17,7 +17,7 @@
from __future__ import annotations
import sys
from typing import Any, Optional, Sequence, TYPE_CHECKING
from typing import Any, Sequence, TYPE_CHECKING
if sys.version_info >= (3, 9):
from re import Match
@@ -64,12 +64,12 @@ class Color:
import re
class Matcher:
match_obj: Optional[Match[str]]
match_obj: Match[str] | None
def __init__(self) -> None:
self.match_obj = None
def match(self, pattern: str, str_: str) -> Optional[Match[str]]:
def match(self, pattern: str, str_: str) -> Match[str] | None:
self.match_obj = re.match(pattern, str_)
return self.match_obj
@@ -82,7 +82,7 @@ class Color:
if m.match(RGB_PATTERN, str_):
return cls(*m.groups)
elif m.match(RGB_PCT_PATTERN, str_):
rgb = tuple([float(each) / 100 * 255 for each in m.groups])
rgb = tuple(float(each) / 100 * 255 for each in m.groups)
return cls(*rgb)
elif m.match(RGBA_PATTERN, str_):
return cls(*m.groups)
@@ -91,10 +91,10 @@ class Color:
[float(each) / 100 * 255 for each in m.groups[:3]] + [m.groups[3]]) # type: ignore
return cls(*rgba)
elif m.match(HEX_PATTERN, str_):
rgb = tuple([int(each, 16) for each in m.groups])
rgb = tuple(int(each, 16) for each in m.groups)
return cls(*rgb)
elif m.match(HEX3_PATTERN, str_):
rgb = tuple([int(each * 2, 16) for each in m.groups])
rgb = tuple(int(each * 2, 16) for each in m.groups)
return cls(*rgb)
elif m.match(HSL_PATTERN, str_) or m.match(HSLA_PATTERN, str_):
return cls._from_hsl(*m.groups)
@@ -156,7 +156,7 @@ class Color:
@property
def hex(self) -> str:
return "#%02x%02x%02x" % (self.red, self.green, self.blue)
return f"#{self.red:02x}{self.green:02x}{self.blue:02x}"
def __eq__(self, other: object) -> bool:
if isinstance(other, Color):

@@ -122,7 +122,7 @@ class EventFiringWebDriver:
if isinstance(args, EventFiringWebElement):
return args.wrapped_element
elif isinstance(args, tuple):
return tuple([self._unwrap_element_args(item) for item in args])
return tuple(self._unwrap_element_args(item) for item in args)
elif isinstance(args, list):
return [self._unwrap_element_args(item) for item in args]
else:

@@ -23,7 +23,7 @@ class Options(ArgOptions):
KEY = 'webkitgtk:browserOptions'
def __init__(self):
super(Options, self).__init__()
super().__init__()
self._binary_location = ''
self._overlay_scrollbars_enabled = True

@@ -23,7 +23,7 @@ class Options(ArgOptions):
KEY = 'wpe:browserOptions'
def __init__(self):
super(Options, self).__init__()
super().__init__()
self._binary_location = ''
self._caps = DesiredCapabilities.WPEWEBKIT.copy()

@@ -305,7 +305,7 @@ def test_unexpected_alert_present_exception_contains_alert_text(driver, pages):
with pytest.raises(UnexpectedAlertPresentException) as e:
pages.load("simpleTest.html")
assert value == e.value.alert_text
assert "Alert Text: {}".format(value) in str(e)
assert f"Alert Text: {value}" in str(e)
def _wait_for_alert(driver):

@@ -163,7 +163,7 @@ def test_get_attribute(driver, pages):
driver.get(url)
elem = driver.find_element(By.ID, "id1")
attr = elem.get_attribute("href")
assert '{0}#'.format(url) == attr
assert f'{url}#' == attr
def test_get_implicit_attribute(driver, pages):

@@ -131,14 +131,14 @@ def test_delete_cookie(cookie, driver):
def test_should_get_cookie_by_name(driver):
key = 'key_{}'.format(int(random.random() * 10000000))
key = f'key_{int(random.random() * 10000000)}'
driver.execute_script("document.cookie = arguments[0] + '=set';", key)
cookie = driver.get_cookie(key)
assert 'set' == cookie['value']
def test_should_return_none_when_cookie_does_not_exist(driver):
key = 'key_{}'.format(int(random.random() * 10000000))
key = f'key_{int(random.random() * 10000000)}'
cookie = driver.get_cookie(key)
assert cookie is None
@@ -148,7 +148,7 @@ def test_get_all_cookies(cookie, driver, pages, webserver):
count = len(cookies)
for i in range(2):
cookie['name'] = 'key_{}'.format(int(random.random() * 10000000))
cookie['name'] = f'key_{int(random.random() * 10000000)}'
driver.add_cookie(cookie)
pages.load('simpleTest.html')

@@ -142,7 +142,7 @@ def test_should_detect_page_loads_while_waiting_on_an_async_script_and_return_an
driver.set_script_timeout(0.1)
with pytest.raises(WebDriverException):
url = pages.url("dynamic.html")
driver.execute_async_script("window.location = '{0}';".format(url))
driver.execute_async_script(f"window.location = '{url}';")
def test_should_catch_errors_when_executing_initial_script(driver, pages):

@@ -236,11 +236,11 @@ def test_can_reset_interactions(driver):
actions = ActionChains(driver)
actions.click()
actions.key_down('A')
assert all((len(device.actions) > 0 for device in actions.w3c_actions.devices if device.type != interaction.WHEEL))
assert all(len(device.actions) > 0 for device in actions.w3c_actions.devices if device.type != interaction.WHEEL)
actions.reset_actions()
assert all((len(device.actions) == 0 for device in actions.w3c_actions.devices))
assert all(len(device.actions) == 0 for device in actions.w3c_actions.devices)
def test_can_pause(driver, pages):
@@ -358,7 +358,7 @@ def _get_events(driver):
# test_keys_wdspec.html), so this converts them back into unicode literals.
for e in events:
# example: turn "U+d83d" (6 chars) into u"\ud83d" (1 char)
if "key" in e and e["key"].startswith(u"U+"):
if "key" in e and e["key"].startswith("U+"):
key = e["key"]
hex_suffix = key[key.index("+") + 1:]
e["key"] = chr(int(hex_suffix, 16))

@@ -53,6 +53,6 @@ def get_lan_ip():
try:
ip = get_interface_ip(ifname)
break
except IOError:
except OSError:
pass
return ip

@@ -317,7 +317,7 @@ def _get_events(driver):
# test_keys_wdspec.html), so this converts them back into unicode literals.
for e in events:
# example: turn "U+d83d" (6 chars) into u"\ud83d" (1 char)
if "key" in e and e["key"].startswith(u"U+"):
if "key" in e and e["key"].startswith("U+"):
key = e["key"]
hex_suffix = key[key.index("+") + 1:]
e["key"] = chr(int(hex_suffix, 16))

@@ -21,9 +21,7 @@ import contextlib
import logging
import os
import re
import socket
import threading
from io import open
try:
from urllib import request as urllib_request
except ImportError:
@@ -69,13 +67,13 @@ class HtmlOnlyHandler(BaseHTTPRequestHandler):
</body></html>""".format(page_number=path[5:])
html = html.encode('utf-8')
else:
with open(os.path.join(HTML_ROOT, path), 'r', encoding='latin-1') as f:
with open(os.path.join(HTML_ROOT, path), encoding='latin-1') as f:
html = f.read().encode('utf-8')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(html)
except IOError:
except OSError:
self.send_error(404, f"File Not Found: {path}")
def do_POST(self):
@@ -141,7 +139,7 @@ class SimpleWebServer:
self.host = host
self.port = port
break
except socket.error:
except OSError:
LOGGER.debug(f"port {port} is in use, trying to next one")
port += 1

@@ -127,10 +127,10 @@ def test_should_fire_find_event(driver, log, pages):
class EventListener(AbstractEventListener):
def before_find(self, by, value, driver):
log.write(("before_find by %s %s" % (by, value)).encode())
log.write((f"before_find by {by} {value}").encode())
def after_find(self, by, value, driver):
log.write(("after_find by %s %s" % (by, value)).encode())
log.write((f"after_find by {by} {value}").encode())
ef_driver = EventFiringWebDriver(driver, EventListener())
ef_driver.get(pages.url("simpleTest.html"))

@@ -93,7 +93,7 @@ def test_get_extensions_from_extension_files(options, mocker):
null = 'NUL' if platform.system().lower() == 'windows' else '/dev/null'
mocker.patch(
'selenium.webdriver.chromium.options.open').return_value = open(null)
mocker.patch('base64.b64encode').return_value = 'foo'.encode()
mocker.patch('base64.b64encode').return_value = b'foo'
options._extension_files = ['foo']
assert 'foo' in options.extensions

@@ -57,7 +57,7 @@ def test_works_as_context_manager(mocker):
@pytest.mark.parametrize('browser_name', ['firefox', 'chrome', 'ie', 'opera'])
def test_accepts_firefox_options_to_remote_driver(mocker, browser_name):
options = import_module('selenium.webdriver.{}.options'.format(browser_name))
options = import_module(f'selenium.webdriver.{browser_name}.options')
caps_name = browser_name.upper() if browser_name != 'ie' else 'INTERNETEXPLORER'
mock = mocker.patch('selenium.webdriver.remote.webdriver.WebDriver.start_session')

@@ -43,7 +43,7 @@ def test_webdriver_not_subclassed():
"""A registered subtype of WebDriver should work with isinstance checks."""
class MyWebDriver:
def __init__(self, *args, **kwargs):
super(MyWebDriver, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
# Test that non registered class instance is not instance of Remote WebDriver
my_driver = MyWebDriver()