From afcfa15ae2720d6e42398185ac5fa861f0ba46b6 Mon Sep 17 00:00:00 2001 From: Mark Mayo Date: Wed, 2 Nov 2022 12:50:19 +1300 Subject: [PATCH] pylint fixes Tidying up of a bunch of pylint issues --- py/generate.py | 54 +++++++++---------- py/selenium/webdriver/chromium/webdriver.py | 2 +- py/selenium/webdriver/common/bidi/cdp.py | 6 +-- py/selenium/webdriver/common/service.py | 5 +- py/selenium/webdriver/remote/webdriver.py | 2 +- py/selenium/webdriver/remote/webelement.py | 2 +- py/test/runner/run_pytest.py | 2 +- .../selenium/webdriver/chrome/proxy_tests.py | 2 +- .../executing_async_javascript_tests.py | 10 ++-- .../common/executing_javascript_tests.py | 12 ++--- .../webdriver/marionette/mn_options_tests.py | 4 +- .../remote/remote_connection_tests.py | 22 ++++---- .../selenium/webdriver/support/color_tests.py | 2 +- 13 files changed, 60 insertions(+), 65 deletions(-) diff --git a/py/generate.py b/py/generate.py index 7b7689dd85c4b..4ebd69b600649 100644 --- a/py/generate.py +++ b/py/generate.py @@ -106,12 +106,11 @@ def escape_backticks(docstr): def replace_one(match): if match.group(2) == 's': return f"``{match.group(1)}``'s" - elif match.group(2): + if match.group(2): # This case (some trailer other than "s") doesn't currently exist # in the CDP definitions, but it's here just to be safe. return f'``{match.group(1)}`` {match.group(2)}' - else: - return f'``{match.group(1)}``' + return f'``{match.group(1)}``' # Sometimes pipes are used where backticks should have been used. docstr = docstr.replace('|', '`') @@ -179,17 +178,15 @@ def get_annotation(cls, cdp_type): ''' Return a type annotation for the CDP type. ''' if cdp_type == 'any': return 'typing.Any' - else: - return cls[cdp_type].value + return cls[cdp_type].value @classmethod def get_constructor(cls, cdp_type, val): ''' Return the code to construct a value for a given CDP type. ''' if cdp_type == 'any': return val - else: - cons = cls[cdp_type].value - return f'{cons}({val})' + cons = cls[cdp_type].value + return f'{cons}({val})' @dataclass @@ -333,7 +330,7 @@ def from_json(cls, type_): type_['type'], CdpItems.from_json(type_['items']) if 'items' in type_ else None, type_.get('enum'), - [CdpProperty.from_json(p) for p in type_.get('properties', list())], + [CdpProperty.from_json(p) for p in type_.get('properties', [])], ) def generate_code(self): @@ -341,10 +338,9 @@ def generate_code(self): logger.debug('Generating type %s: %s', self.id, self.type) if self.enum: return self.generate_enum_code() - elif self.properties: + if self.properties: return self.generate_class_code() - else: - return self.generate_primitive_code() + return self.generate_primitive_code() def generate_primitive_code(self): ''' Generate code for a primitive type. ''' @@ -395,7 +391,7 @@ def generate_enum_code(self): def to_json(self): return self.value''') - def_from_json = dedent(f'''\ + def_from_json = dedent('''\ @classmethod def from_json(cls, json): return cls(json)''') @@ -449,12 +445,12 @@ def to_json(self): # Emit from_json() method. The properties are sorted in the same order # as above for readability. - def_from_json = dedent(f'''\ + def_from_json = dedent('''\ @classmethod def from_json(cls, json): return cls( ''') - from_jsons = list() + from_jsons = [] for p in props: from_json = p.generate_from_json(dict_='json') from_jsons.append(f'{p.py_name}={from_json},') @@ -526,10 +522,10 @@ def generate_doc(self): doc = f':param {self.py_name}:' if self.experimental: - doc += f' **(EXPERIMENTAL)**' + doc += ' **(EXPERIMENTAL)**' if self.optional: - doc += f' *(Optional)*' + doc += ' *(Optional)*' if self.description: desc = self.description.replace('`', '``').replace('\n', ' ') @@ -600,8 +596,8 @@ def py_name(self): @classmethod def from_json(cls, command, domain) -> 'CdpCommand': ''' Instantiate a CDP command from a JSON object. ''' - parameters = command.get('parameters', list()) - returns = command.get('returns', list()) + parameters = command.get('parameters', []) + returns = command.get('returns', []) return cls( command['name'], @@ -653,7 +649,7 @@ def generate_code(self): if self.description: doc = self.description if self.experimental: - doc += f'\n\n**EXPERIMENTAL**' + doc += '\n\n**EXPERIMENTAL**' if self.parameters and doc: doc += '\n\n' elif not self.parameters and self.returns: @@ -735,7 +731,7 @@ def from_json(cls, json: dict, domain: str): json.get('deprecated', False), json.get('experimental', False), [typing.cast(CdpParameter, CdpParameter.from_json(p)) - for p in json.get('parameters', list())], + for p in json.get('parameters', [])], domain ) @@ -804,16 +800,16 @@ def module(self): @classmethod def from_json(cls, domain: dict): ''' Instantiate a CDP domain from a JSON object. ''' - types = domain.get('types', list()) - commands = domain.get('commands', list()) - events = domain.get('events', list()) + types = domain.get('types', []) + commands = domain.get('commands', []) + events = domain.get('events', []) domain_name = domain['domain'] return cls( domain_name, domain.get('description'), domain.get('experimental', False), - domain.get('dependencies', list()), + domain.get('dependencies', []), [CdpType.from_json(type) for type in types], [CdpCommand.from_json(command, domain_name) for command in commands], @@ -939,12 +935,12 @@ def parse(json_path, output_path): :returns: a list of CDP domain objects ''' global current_version - with open(json_path) as json_file: + with open(json_path, encoding="utf-8") as json_file: schema = json.load(json_file) version = schema['version'] assert (version['major'], version['minor']) == ('1', '3') current_version = f'{version["major"]}.{version["minor"]}' - domains = list() + domains = [] for domain in schema['domains']: domains.append(CdpDomain.from_json(domain)) return domains @@ -957,7 +953,7 @@ def generate_init(init_path, domains): :param list[tuple] modules: a list of modules each represented as tuples of (name, list_of_exported_symbols) ''' - with open(init_path, "w") as init_file: + with open(init_path, "w", encoding="utf-8") as init_file: init_file.write(INIT_HEADER) for domain in domains: init_file.write(f'from . import {domain.module}\n') @@ -1001,7 +997,7 @@ def main(browser_protocol_path, js_protocol_path, output_path): subpath.unlink() # Parse domains - domains = list() + domains = [] for json_path in json_paths: logger.info('Parsing JSON file %s', json_path) domains.extend(parse(json_path, output_path)) diff --git a/py/selenium/webdriver/chromium/webdriver.py b/py/selenium/webdriver/chromium/webdriver.py index 6ab6c447a64e6..a65e4ecdcd4e5 100644 --- a/py/selenium/webdriver/chromium/webdriver.py +++ b/py/selenium/webdriver/chromium/webdriver.py @@ -76,7 +76,7 @@ def __init__( DeprecationWarning, stacklevel=2, ) - if keep_alive != DEFAULT_KEEP_ALIVE and type(self) == __class__: + if keep_alive != DEFAULT_KEEP_ALIVE and isinstance(self, __class__): warnings.warn( "keep_alive has been deprecated, please pass in a Service object", DeprecationWarning, stacklevel=2 ) diff --git a/py/selenium/webdriver/common/bidi/cdp.py b/py/selenium/webdriver/common/bidi/cdp.py index 4c71763bea670..ece4f7b3ebb8b 100644 --- a/py/selenium/webdriver/common/bidi/cdp.py +++ b/py/selenium/webdriver/common/bidi/cdp.py @@ -190,8 +190,8 @@ def __init__(self, ws, session_id, target_id): self.target_id = target_id self.channels = defaultdict(set) self.id_iter = itertools.count() - self.inflight_cmd = dict() - self.inflight_result = dict() + self.inflight_cmd = {} + self.inflight_result = {} async def execute(self, cmd: typing.Generator[dict, T, typing.Any]) -> T: """ @@ -380,7 +380,7 @@ def __init__(self, ws): :param trio_websocket.WebSocketConnection ws: """ super().__init__(ws, session_id=None, target_id=None) - self.sessions = dict() + self.sessions = {} async def aclose(self): """ diff --git a/py/selenium/webdriver/common/service.py b/py/selenium/webdriver/common/service.py index 57961ea93e432..d9cd20e9969a3 100644 --- a/py/selenium/webdriver/common/service.py +++ b/py/selenium/webdriver/common/service.py @@ -203,12 +203,11 @@ def _start_process(self, path: str) -> None: raise WebDriverException( f"'{os.path.basename(self.path)}' executable needs to be in PATH. {self.start_error_message}" ) - elif err.errno == errno.EACCES: + if err.errno == errno.EACCES: raise WebDriverException( f"'{os.path.basename(self.path)}' executable may have wrong permissions. {self.start_error_message}" ) - else: - raise + raise except Exception as e: raise WebDriverException( f"The executable {os.path.basename(self.path)} needs to be available in the path. {self.start_error_message}\n{str(e)}" diff --git a/py/selenium/webdriver/remote/webdriver.py b/py/selenium/webdriver/remote/webdriver.py index 369c35b510d01..bf34e5734ff8a 100644 --- a/py/selenium/webdriver/remote/webdriver.py +++ b/py/selenium/webdriver/remote/webdriver.py @@ -1260,7 +1260,7 @@ def remove_credential(self, credential_id: Union[str, bytearray]) -> None: Removes a credential from the authenticator. """ # Check if the credential is bytearray converted to b64 string - if type(credential_id) is bytearray: + if isinstance(credential_id, bytearray): credential_id = urlsafe_b64encode(credential_id).decode() self.execute( diff --git a/py/selenium/webdriver/remote/webelement.py b/py/selenium/webdriver/remote/webelement.py index 8be11050d6d1b..4c406e7d30029 100644 --- a/py/selenium/webdriver/remote/webelement.py +++ b/py/selenium/webdriver/remote/webelement.py @@ -251,7 +251,7 @@ def shadow_root(self) -> ShadowRoot: "safari", ], "This only currently works in Chromium based browsers" assert ( - not browser_main_version <= 95 + browser_main_version > 95 ), f"Please use Chromium based browsers with version 96 or later. Version used {self._parent.caps['browserVersion']}" return self._execute(Command.GET_SHADOW_ROOT)["value"] diff --git a/py/test/runner/run_pytest.py b/py/test/runner/run_pytest.py index 2911e03ee2b98..64d17c3e0e187 100644 --- a/py/test/runner/run_pytest.py +++ b/py/test/runner/run_pytest.py @@ -17,7 +17,7 @@ import pytest -with open("pytest.ini", "w") as ini_file: +with open("pytest.ini", "w", encoding="utf-8") as ini_file: ini_file.write("[pytest]\n") ini_file.write("addopts = -r=a\n") ini_file.write("rootdir = py\n") diff --git a/py/test/selenium/webdriver/chrome/proxy_tests.py b/py/test/selenium/webdriver/chrome/proxy_tests.py index bdf8d463f5a3f..c1372fe6e970d 100644 --- a/py/test/selenium/webdriver/chrome/proxy_tests.py +++ b/py/test/selenium/webdriver/chrome/proxy_tests.py @@ -36,7 +36,7 @@ def test_bad_proxy_doesnt_interfere(): assert hasattr(driver, "command_executor") assert hasattr(driver.command_executor, "_proxy_url") - assert type(driver.command_executor._conn) == urllib3.PoolManager + assert isinstance(driver.command_executor._conn, urllib3.PoolManager) os.environ.pop("https_proxy") os.environ.pop("http_proxy") driver.quit() diff --git a/py/test/selenium/webdriver/common/executing_async_javascript_tests.py b/py/test/selenium/webdriver/common/executing_async_javascript_tests.py index a6e85bdf5fd08..77ceaad3ec09b 100644 --- a/py/test/selenium/webdriver/common/executing_async_javascript_tests.py +++ b/py/test/selenium/webdriver/common/executing_async_javascript_tests.py @@ -33,7 +33,7 @@ def reset_timeouts(driver): def test_should_not_timeout_if_callback_invoked_immediately(driver, pages): pages.load("ajaxy_page.html") result = driver.execute_async_script("arguments[arguments.length - 1](123);") - assert type(result) == int + assert isinstance(result, int) assert 123 == result @@ -55,7 +55,7 @@ def test_should_be_able_to_return_an_array_literal_from_an_async_script(driver, pages.load("ajaxy_page.html") result = driver.execute_async_script("arguments[arguments.length - 1]([]);") assert "Expected not to be null!", result is not None - assert type(result) == list + assert isinstance(result, list) assert len(result) == 0 @@ -63,7 +63,7 @@ def test_should_be_able_to_return_an_array_object_from_an_async_script(driver, p pages.load("ajaxy_page.html") result = driver.execute_async_script("arguments[arguments.length - 1](new Array());") assert "Expected not to be null!", result is not None - assert type(result) == list + assert isinstance(result, list) assert len(result) == 0 @@ -73,7 +73,7 @@ def test_should_be_able_to_return_arrays_of_primitives_from_async_scripts(driver result = driver.execute_async_script("arguments[arguments.length - 1]([null, 123, 'abc', true, false]);") assert result is not None - assert type(result) == list + assert isinstance(result, list) assert not bool(result.pop()) assert bool(result.pop()) assert "abc" == result.pop() @@ -96,7 +96,7 @@ def test_should_be_able_to_return_arrays_of_web_elements_from_async_scripts(driv result = driver.execute_async_script("arguments[arguments.length - 1]([document.body, document.body]);") assert result is not None - assert type(result) == list + assert isinstance(result, list) list_ = result assert 2 == len(list_) diff --git a/py/test/selenium/webdriver/common/executing_javascript_tests.py b/py/test/selenium/webdriver/common/executing_javascript_tests.py index 28d19b4bc97c6..d94b759e54121 100644 --- a/py/test/selenium/webdriver/common/executing_javascript_tests.py +++ b/py/test/selenium/webdriver/common/executing_javascript_tests.py @@ -32,7 +32,7 @@ def test_should_be_able_to_execute_simple_javascript_and_return_astring(driver, result = driver.execute_script("return document.title") - assert type(result) == str, "The type of the result is %s" % type(result) + assert isinstance(result, str), "The type of the result is %s" % type(result) assert "XHTML Test Page" == result @@ -40,7 +40,7 @@ def test_should_be_able_to_execute_simple_javascript_and_return_an_integer(drive pages.load("nestedElements.html") result = driver.execute_script("return document.getElementsByName('checky').length") - assert type(result) == int + assert isinstance(result, int) assert int(result) > 1 @@ -124,7 +124,7 @@ def test_should_be_able_to_execute_simple_javascript_and_return_aboolean(driver, result = driver.execute_script("return true") assert result is not None - assert type(result) == bool + assert isinstance(result, bool) assert bool(result) @@ -149,7 +149,7 @@ def test_should_be_able_to_execute_simple_javascript_and_return_an_array(driver, expectedResult.append(subList) result = driver.execute_script("return ['zero', [true, false]]") assert result is not None - assert type(result) == list + assert isinstance(result, list) assert expectedResult == result @@ -157,7 +157,7 @@ def test_passing_and_returning_an_int_should_return_awhole_number(driver, pages) pages.load("javascriptPage.html") expectedResult = 1 result = driver.execute_script("return arguments[0]", expectedResult) - assert type(result) == int + assert isinstance(result, int) assert expectedResult == result @@ -165,7 +165,7 @@ def test_passing_and_returning_adouble_should_return_adecimal(driver, pages): pages.load("javascriptPage.html") expectedResult = 1.2 result = driver.execute_script("return arguments[0]", expectedResult) - assert type(result) == float + assert isinstance(result, float) assert expectedResult == result diff --git a/py/test/selenium/webdriver/marionette/mn_options_tests.py b/py/test/selenium/webdriver/marionette/mn_options_tests.py index 10d14c65749bf..51e4e35765f97 100644 --- a/py/test/selenium/webdriver/marionette/mn_options_tests.py +++ b/py/test/selenium/webdriver/marionette/mn_options_tests.py @@ -41,9 +41,9 @@ class TestUnit: def test_ctor(self): opts = Options() assert opts._binary is None - assert opts._preferences == {} + assert not opts._preferences assert opts._profile is None - assert opts._arguments == [] + assert not opts._arguments assert isinstance(opts.log, Log) def test_binary(self): diff --git a/py/test/unit/selenium/webdriver/remote/remote_connection_tests.py b/py/test/unit/selenium/webdriver/remote/remote_connection_tests.py index ca4ccde5acec7..2c798365d85f5 100644 --- a/py/test/unit/selenium/webdriver/remote/remote_connection_tests.py +++ b/py/test/unit/selenium/webdriver/remote/remote_connection_tests.py @@ -27,11 +27,11 @@ def test_get_remote_connection_headers_defaults(): url = "http://remote" headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url)) - assert "Authorization" not in headers.keys() - assert "Connection" not in headers.keys() + assert "Authorization" not in headers + assert "Connection" not in headers assert headers.get("Accept") == "application/json" assert headers.get("Content-Type") == "application/json;charset=UTF-8" - assert headers.get("User-Agent").startswith("selenium/%s (python " % __version__) + assert headers.get("User-Agent").startswith(f"selenium/{__version__} (python ") assert headers.get("User-Agent").split(" ")[-1] in {"windows)", "mac)", "linux)"} @@ -88,7 +88,7 @@ def test_get_proxy_url_https_auth(mock_proxy_auth_settings): def test_get_connection_manager_without_proxy(mock_proxy_settings_missing): remote_connection = RemoteConnection("http://remote", keep_alive=False) conn = remote_connection._get_connection_manager() - assert type(conn) == urllib3.PoolManager + assert isinstance(conn, urllib3.PoolManager) def test_get_connection_manager_for_certs_and_timeout(monkeypatch): @@ -109,13 +109,13 @@ def test_default_socket_timeout_is_correct(): def test_get_connection_manager_with_proxy(mock_proxy_settings): remote_connection = RemoteConnection("http://remote", keep_alive=False) conn = remote_connection._get_connection_manager() - assert type(conn) == urllib3.ProxyManager + assert isinstance(conn, urllib3.ProxyManager) assert conn.proxy.scheme == "http" assert conn.proxy.host == "http_proxy.com" assert conn.proxy.port == 8080 remote_connection_https = RemoteConnection("https://remote", keep_alive=False) conn = remote_connection_https._get_connection_manager() - assert type(conn) == urllib3.ProxyManager + assert isinstance(conn, urllib3.ProxyManager) assert conn.proxy.scheme == "http" assert conn.proxy.host == "https_proxy.com" assert conn.proxy.port == 8080 @@ -125,14 +125,14 @@ def test_get_connection_manager_with_auth_proxy(mock_proxy_auth_settings): proxy_auth_header = urllib3.make_headers(proxy_basic_auth="user:password") remote_connection = RemoteConnection("http://remote", keep_alive=False) conn = remote_connection._get_connection_manager() - assert type(conn) == urllib3.ProxyManager + assert isinstance(conn, urllib3.ProxyManager) assert conn.proxy.scheme == "http" assert conn.proxy.host == "http_proxy.com" assert conn.proxy.port == 8080 assert conn.proxy_headers == proxy_auth_header remote_connection_https = RemoteConnection("https://remote", keep_alive=False) conn = remote_connection_https._get_connection_manager() - assert type(conn) == urllib3.ProxyManager + assert isinstance(conn, urllib3.ProxyManager) assert conn.proxy.scheme == "https" assert conn.proxy.host == "https_proxy.com" assert conn.proxy.port == 8080 @@ -160,13 +160,13 @@ def test_get_connection_manager_with_auth_proxy(mock_proxy_auth_settings): def test_get_connection_manager_when_no_proxy_set(mock_no_proxy_settings, url): remote_connection = RemoteConnection(url) conn = remote_connection._get_connection_manager() - assert type(conn) == urllib3.PoolManager + assert isinstance(conn, urllib3.PoolManager) def test_ignore_proxy_env_vars(mock_proxy_settings): remote_connection = RemoteConnection("http://remote", ignore_proxy=True) conn = remote_connection._get_connection_manager() - assert type(conn) == urllib3.PoolManager + assert isinstance(conn, urllib3.PoolManager) def test_get_socks_proxy_when_set(mock_socks_proxy_settings): @@ -174,7 +174,7 @@ def test_get_socks_proxy_when_set(mock_socks_proxy_settings): conn = remote_connection._get_connection_manager() from urllib3.contrib.socks import SOCKSProxyManager - assert type(conn) == SOCKSProxyManager + assert isinstance(conn, SOCKSProxyManager) class MockResponse: diff --git a/py/test/unit/selenium/webdriver/support/color_tests.py b/py/test/unit/selenium/webdriver/support/color_tests.py index 24bbf3b8ab76d..d435bf6305481 100644 --- a/py/test/unit/selenium/webdriver/support/color_tests.py +++ b/py/test/unit/selenium/webdriver/support/color_tests.py @@ -22,7 +22,7 @@ def test_color_can_be_subclassed(): class MyColor(Color): ... - assert type(MyColor.from_string("rgb(1, 2, 3)")) == MyColor + assert isinstance(MyColor.from_string("rgb(1, 2, 3)"), MyColor) def test_rgb_to_rgb():