diff --git a/.basedpyright/baseline.json b/.basedpyright/baseline.json index c9e0d881..20155ed3 100644 --- a/.basedpyright/baseline.json +++ b/.basedpyright/baseline.json @@ -279,14 +279,6 @@ "lineCount": 1 } }, - { - "code": "reportUnusedVariable", - "range": { - "startColumn": 28, - "endColumn": 30, - "lineCount": 1 - } - }, { "code": "reportUnknownVariableType", "range": { @@ -4985,14 +4977,6 @@ "lineCount": 1 } }, - { - "code": "reportUnusedVariable", - "range": { - "startColumn": 32, - "endColumn": 33, - "lineCount": 1 - } - }, { "code": "reportUnknownVariableType", "range": { @@ -7785,14 +7769,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 51, - "endColumn": 55, - "lineCount": 1 - } - }, { "code": "reportUnknownVariableType", "range": { @@ -8169,14 +8145,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 51, - "endColumn": 59, - "lineCount": 1 - } - }, { "code": "reportUnknownVariableType", "range": { @@ -8665,14 +8633,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 24, - "endColumn": 51, - "lineCount": 1 - } - }, { "code": "reportUnknownArgumentType", "range": { @@ -13321,14 +13281,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 54, - "endColumn": 62, - "lineCount": 1 - } - }, { "code": "reportUnknownArgumentType", "range": { @@ -13721,14 +13673,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 55, - "endColumn": 59, - "lineCount": 1 - } - }, { "code": "reportUnknownArgumentType", "range": { @@ -18543,14 +18487,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 79, - "endColumn": 90, - "lineCount": 1 - } - }, { "code": "reportUnknownVariableType", "range": { @@ -20013,14 +19949,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 75, - "endColumn": 79, - "lineCount": 1 - } - }, { "code": "reportUnannotatedClassAttribute", "range": { @@ -20053,6 +19981,22 @@ "lineCount": 1 } }, + { + "code": "reportUnknownParameterType", + "range": { + "startColumn": 8, + "endColumn": 12, + "lineCount": 1 + } + }, + { + "code": "reportUnknownVariableType", + "range": { + "startColumn": 15, + "endColumn": 25, + "lineCount": 1 + } + }, { "code": "reportUnknownParameterType", "range": { @@ -20070,23 +20014,23 @@ } }, { - "code": "reportUnknownArgumentType", + "code": "reportUnknownParameterType", "range": { - "startColumn": 91, - "endColumn": 96, + "startColumn": 8, + "endColumn": 15, "lineCount": 1 } }, { - "code": "reportUnknownParameterType", + "code": "reportUnknownVariableType", "range": { - "startColumn": 22, - "endColumn": 27, + "startColumn": 15, + "endColumn": 28, "lineCount": 1 } }, { - "code": "reportMissingParameterType", + "code": "reportUnknownParameterType", "range": { "startColumn": 22, "endColumn": 27, @@ -20094,10 +20038,10 @@ } }, { - "code": "reportUnknownArgumentType", + "code": "reportMissingParameterType", "range": { - "startColumn": 82, - "endColumn": 87, + "startColumn": 22, + "endColumn": 27, "lineCount": 1 } }, @@ -21588,16 +21532,16 @@ { "code": "reportUnknownArgumentType", "range": { - "startColumn": 69, - "endColumn": 73, + "startColumn": 39, + "endColumn": 43, "lineCount": 1 } }, { "code": "reportUnknownArgumentType", "range": { - "startColumn": 76, - "endColumn": 81, + "startColumn": 46, + "endColumn": 51, "lineCount": 1 } }, @@ -21652,24 +21596,24 @@ { "code": "reportUnknownArgumentType", "range": { - "startColumn": 55, - "endColumn": 59, + "startColumn": 25, + "endColumn": 29, "lineCount": 1 } }, { "code": "reportUnknownArgumentType", "range": { - "startColumn": 61, - "endColumn": 66, + "startColumn": 31, + "endColumn": 36, "lineCount": 1 } }, { "code": "reportArgumentType", "range": { - "startColumn": 68, - "endColumn": 72, + "startColumn": 38, + "endColumn": 42, "lineCount": 1 } }, @@ -21761,22 +21705,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 77, - "endColumn": 82, - "lineCount": 1 - } - }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 59, - "endColumn": 64, - "lineCount": 1 - } - }, { "code": "reportUnknownVariableType", "range": { @@ -23005,7 +22933,7 @@ "code": "reportUnknownArgumentType", "range": { "startColumn": 29, - "endColumn": 73, + "endColumn": 68, "lineCount": 1 } }, @@ -23028,16 +22956,16 @@ { "code": "reportUnknownArgumentType", "range": { - "startColumn": 69, - "endColumn": 71, + "startColumn": 64, + "endColumn": 66, "lineCount": 1 } }, { "code": "reportUnknownArgumentType", "range": { - "startColumn": 75, - "endColumn": 85, + "startColumn": 70, + "endColumn": 80, "lineCount": 1 } }, @@ -23963,6 +23891,14 @@ "lineCount": 1 } }, + { + "code": "reportFunctionMemberAccess", + "range": { + "startColumn": 51, + "endColumn": 72, + "lineCount": 1 + } + }, { "code": "reportUnknownVariableType", "range": { @@ -24680,8 +24616,8 @@ { "code": "reportUnknownArgumentType", "range": { - "startColumn": 25, - "endColumn": 29, + "startColumn": 22, + "endColumn": 26, "lineCount": 1 } }, @@ -28676,8 +28612,8 @@ { "code": "reportUnknownArgumentType", "range": { - "startColumn": 43, - "endColumn": 57, + "startColumn": 52, + "endColumn": 66, "lineCount": 1 } }, @@ -29393,14 +29329,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 81, - "endColumn": 90, - "lineCount": 1 - } - }, { "code": "reportUnannotatedClassAttribute", "range": { @@ -30075,6 +30003,14 @@ "lineCount": 1 } }, + { + "code": "reportUnknownParameterType", + "range": { + "startColumn": 4, + "endColumn": 15, + "lineCount": 1 + } + }, { "code": "reportUnknownParameterType", "range": { @@ -30124,10 +30060,10 @@ } }, { - "code": "reportUnknownArgumentType", + "code": "reportUnknownVariableType", "range": { - "startColumn": 19, - "endColumn": 23, + "startColumn": 11, + "endColumn": 44, "lineCount": 1 } } @@ -34849,14 +34785,6 @@ } ], "./tests/integration/test_collection.py": [ - { - "code": "reportUnusedImport", - "range": { - "startColumn": 23, - "endColumn": 37, - "lineCount": 1 - } - }, { "code": "reportImplicitOverride", "range": { @@ -36701,38 +36629,6 @@ } ], "./tests/integration/test_job.py": [ - { - "code": "reportUnusedImport", - "range": { - "startColumn": 7, - "endColumn": 9, - "lineCount": 1 - } - }, - { - "code": "reportUnusedImport", - "range": { - "startColumn": 7, - "endColumn": 15, - "lineCount": 1 - } - }, - { - "code": "reportUnusedImport", - "range": { - "startColumn": 15, - "endColumn": 22, - "lineCount": 1 - } - }, - { - "code": "reportUnusedImport", - "range": { - "startColumn": 20, - "endColumn": 24, - "lineCount": 1 - } - }, { "code": "reportPrivateUsage", "range": { @@ -36829,14 +36725,6 @@ "lineCount": 1 } }, - { - "code": "reportUnusedImport", - "range": { - "startColumn": 30, - "endColumn": 36, - "lineCount": 1 - } - }, { "code": "reportUnknownArgumentType", "range": { @@ -36853,14 +36741,6 @@ "lineCount": 1 } }, - { - "code": "reportUnusedImport", - "range": { - "startColumn": 30, - "endColumn": 36, - "lineCount": 1 - } - }, { "code": "reportUnknownArgumentType", "range": { @@ -36869,14 +36749,6 @@ "lineCount": 1 } }, - { - "code": "reportUnusedImport", - "range": { - "startColumn": 30, - "endColumn": 36, - "lineCount": 1 - } - }, { "code": "reportUnknownArgumentType", "range": { @@ -38557,14 +38429,6 @@ } ], "./tests/integration/test_role.py": [ - { - "code": "reportUnusedImport", - "range": { - "startColumn": 7, - "endColumn": 14, - "lineCount": 1 - } - }, { "code": "reportImplicitOverride", "range": { @@ -41450,8 +41314,8 @@ { "code": "reportUnknownArgumentType", "range": { - "startColumn": 76, - "endColumn": 84, + "startColumn": 73, + "endColumn": 81, "lineCount": 1 } } @@ -43054,14 +42918,6 @@ "endColumn": 41, "lineCount": 1 } - }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 67, - "endColumn": 87, - "lineCount": 1 - } } ], "./tests/unit/searchcommands/test_configuration_settings.py": [ @@ -44473,22 +44329,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 23, - "endColumn": 39, - "lineCount": 1 - } - }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 41, - "endColumn": 57, - "lineCount": 1 - } - }, { "code": "reportUnknownArgumentType", "range": { @@ -44839,14 +44679,6 @@ } ], "./tests/unit/searchcommands/test_search_command.py": [ - { - "code": "reportUnusedImport", - "range": { - "startColumn": 52, - "endColumn": 68, - "lineCount": 1 - } - }, { "code": "reportUnknownParameterType", "range": { diff --git a/Makefile b/Makefile index 56b0b26b..254f637b 100644 --- a/Makefile +++ b/Makefile @@ -27,7 +27,7 @@ lint: lint-python # TODO: Add mbake .PHONY: lint-python lint-python: $(UV_RUN_CMD) basedpyright -# $(UV_RUN_CMD) ruff check --fix-only + $(UV_RUN_CMD) ruff check --fix-only $(UV_RUN_CMD) ruff format UV_RUN_CMD := uv run --frozen --no-config @@ -37,7 +37,7 @@ ci-lint: ci-lint-python # TODO: Add mbake .PHONY: ci-lint-python ci-lint-python: $(UV_RUN_CMD) basedpyright -# $(UV_RUN_CMD) ruff check + $(UV_RUN_CMD) ruff check $(UV_RUN_CMD) ruff format --check .PHONY: clean diff --git a/splunklib/ai/__init__.py b/splunklib/ai/__init__.py index 868203da..b99e12ed 100644 --- a/splunklib/ai/__init__.py +++ b/splunklib/ai/__init__.py @@ -28,8 +28,8 @@ __all__ = [ "Agent", "AnthropicModel", - "OpenAIModel", "GoogleModel", + "OpenAIModel", "create_structured_prompt", "detect_injection", "truncate_input", diff --git a/splunklib/ai/engines/langchain.py b/splunklib/ai/engines/langchain.py index cccf9b6b..53089209 100644 --- a/splunklib/ai/engines/langchain.py +++ b/splunklib/ai/engines/langchain.py @@ -1859,9 +1859,7 @@ def check_tool_name(type: str, name: str) -> None: last_ai_message: AIMessage | None = None for message in messages: - if type(message) is HumanMessage: - check_no_pending_calls() - elif type(message) is SystemMessage: + if type(message) is HumanMessage or type(message) is SystemMessage: check_no_pending_calls() elif type(message) is AIMessage: last_ai_message = message diff --git a/splunklib/ai/tools.py b/splunklib/ai/tools.py index c10bbcd1..c5e68796 100644 --- a/splunklib/ai/tools.py +++ b/splunklib/ai/tools.py @@ -296,22 +296,24 @@ async def connect_remote_mcp( mcp_url = f"{management_url}/services/mcp" mcp_token = await asyncio.to_thread(lambda: _get_mcp_token(splunk_username, service)) if mcp_token is not None: - async with streamable_http_client( - url=mcp_url, - http_client=httpx.AsyncClient( - headers={ - "x-splunk-trace-id": trace_id, - "x-splunk-app-id": app_id, - }, - auth=_MCPAuth(f"Bearer {mcp_token}"), - verify=False, - follow_redirects=True, - timeout=httpx.Timeout(_MCP_DEFAULT_TIMEOUT, read=_MCP_DEFAULT_SSE_READ_TIMEOUT), - ), - ) as (read, write, _): - async with ClientSession(read, write) as session: - await session.initialize() - yield session + async with ( + streamable_http_client( + url=mcp_url, + http_client=httpx.AsyncClient( + headers={ + "x-splunk-trace-id": trace_id, + "x-splunk-app-id": app_id, + }, + auth=_MCPAuth(f"Bearer {mcp_token}"), + verify=False, + follow_redirects=True, + timeout=httpx.Timeout(_MCP_DEFAULT_TIMEOUT, read=_MCP_DEFAULT_SSE_READ_TIMEOUT), + ), + ) as (read, write, _), + ClientSession(read, write) as session, + ): + await session.initialize() + yield session else: yield None diff --git a/splunklib/binding.py b/splunklib/binding.py index 555b9217..6a3ce299 100644 --- a/splunklib/binding.py +++ b/splunklib/binding.py @@ -47,14 +47,14 @@ __all__ = [ "AuthenticationError", - "connect", "Context", - "handler", "HTTPError", "UrlEncoded", + "_NoAuthenticationToken", "_encode", "_make_cookie_header", - "_NoAuthenticationToken", + "connect", + "handler", "namespace", ] @@ -102,7 +102,7 @@ def mask_sensitive_data(data): if not isinstance(data, dict): try: data = json.loads(data) - except Exception as ex: + except Exception: return data # json.loads will return "123"(str) as 123(int), so return the data if it's not 'dict' type @@ -252,7 +252,7 @@ def __mod__(self, fields): raise TypeError("Cannot interpolate into a UrlEncoded object.") def __repr__(self): - return f"UrlEncoded({repr(parse.unquote(str(self)))})" + return f"UrlEncoded({parse.unquote(str(self))!r})" @contextmanager @@ -1619,7 +1619,7 @@ def request(self, url, message, **kwargs): time.sleep(self.retryDelay) self.retries -= 1 response = record(response) - if 400 <= response.status: + if response.status >= 400: raise HTTPError(response) # Update the cookie with any HTTP request diff --git a/splunklib/client.py b/splunklib/client.py index 7632067a..038980ea 100644 --- a/splunklib/client.py +++ b/splunklib/client.py @@ -641,7 +641,7 @@ def restart(self, timeout=None): continue else: return result - except Exception as e: + except Exception: sleep(1) raise Exception("Operation time out.") @@ -1053,7 +1053,7 @@ def __init__(self, service, path, **kwargs): Endpoint.__init__(self, service, path) self._state = None if not kwargs.get("skip_refresh", False): - self.refresh(kwargs.get("state", None)) # "Prefresh" + self.refresh(kwargs.get("state")) # "Prefresh" def __contains__(self, item): try: @@ -1645,7 +1645,7 @@ def iter(self, offset=0, count=None, pagesize=None, **kwargs): fetched += N for item in items: yield item - if pagesize is None or N < pagesize: + if pagesize is None or pagesize > N: break offset += N logger.debug( @@ -1945,7 +1945,7 @@ def create(self, name): # a ConfigurationFile (which is a Collection) instead of some # Entity. if not isinstance(name, str): - raise ValueError(f"Invalid name: {repr(name)}") + raise ValueError(f"Invalid name: {name!r}") response = self.post(__conf=name) if response.status == 303: return self[name] @@ -1996,7 +1996,7 @@ class StoragePassword(Entity): """This class contains a storage password.""" def __init__(self, service, path, **kwargs): - state = kwargs.get("state", None) + state = kwargs.get("state") kwargs["skip_refresh"] = kwargs.get("skip_refresh", state is not None) super().__init__(service, path, **kwargs) self._state = state @@ -2047,7 +2047,7 @@ def create(self, password, username, realm=None): :return: The :class:`StoragePassword` object created. """ if not isinstance(username, str): - raise ValueError(f"Invalid name: {repr(username)}") + raise ValueError(f"Invalid name: {username!r}") if realm is None: response = self.post(password=password, name=username) @@ -2202,8 +2202,8 @@ def attach(self, host=None, source=None, sourcetype=None): # the input mode sock = self.service.connect() headers = [ - f"POST {str(self.service._abspath(path))} HTTP/1.1\r\n".encode("utf-8"), - f"Host: {self.service.host}:{int(self.service.port)}\r\n".encode("utf-8"), + f"POST {self.service._abspath(path)!s} HTTP/1.1\r\n".encode(), + f"Host: {self.service.host}:{int(self.service.port)}\r\n".encode(), b"Accept-Encoding: identity\r\n", cookie_or_auth_header.encode("utf-8"), b"X-Splunk-Input-Mode: Streaming\r\n", @@ -2806,14 +2806,14 @@ def list(self, *kinds, **kwargs): entities = entities[kwargs["offset"] :] if "count" in kwargs: entities = entities[: kwargs["count"]] - if kwargs.get("sort_mode", None) == "alpha": + if kwargs.get("sort_mode") == "alpha": sort_field = kwargs.get("sort_field", "name") if sort_field == "name": f = lambda x: x.name.lower() else: f = lambda x: x[sort_field].lower() entities = sorted(entities, key=f) - if kwargs.get("sort_mode", None) == "alpha_case": + if kwargs.get("sort_mode") == "alpha_case": sort_field = kwargs.get("sort_field", "name") if sort_field == "name": f = lambda x: x.name @@ -3199,10 +3199,10 @@ def create(self, query, **kwargs): :return: The :class:`Job`. """ - if kwargs.get("exec_mode", None) == "oneshot": + if kwargs.get("exec_mode") == "oneshot": raise TypeError("Cannot specify exec_mode=oneshot; use the oneshot method instead.") response = self.post(search=query, **kwargs) - sid = _load_sid(response, kwargs.get("output_mode", None)) + sid = _load_sid(response, kwargs.get("output_mode")) return Job(self.service, sid) def export(self, query, **params): @@ -3421,7 +3421,7 @@ def dispatch(self, **kwargs): :return: The :class:`Job`. """ response = self.post("dispatch", **kwargs) - sid = _load_sid(response, kwargs.get("output_mode", None)) + sid = _load_sid(response, kwargs.get("output_mode")) return Job(self.service, sid) @property @@ -3737,7 +3737,7 @@ def create(self, username, password, roles, **params): hilda = users.create("hilda", "anotherpassword", roles=["user", "power"]) """ if not isinstance(username, str): - raise ValueError(f"Invalid username: {str(username)}") + raise ValueError(f"Invalid username: {username!s}") username = username.lower() self.post(name=username, password=password, roles=roles, **params) # splunkd doesn't return the user in the POST response body, @@ -3859,7 +3859,7 @@ def create(self, name, **params): paltry = roles.create("paltry", imported_roles="user", defaultApp="search") """ if not isinstance(name, str): - raise ValueError(f"Invalid role name: {str(name)}") + raise ValueError(f"Invalid role name: {name!s}") name = name.lower() self.post(name=name, **params) # splunkd doesn't return the user in the POST response body, diff --git a/splunklib/modularinput/utils.py b/splunklib/modularinput/utils.py index a8f7af58..f29e06d2 100644 --- a/splunklib/modularinput/utils.py +++ b/splunklib/modularinput/utils.py @@ -73,6 +73,6 @@ def parse_xml_data(parent_node, child_node_tag): data[child_name] = {"__app": child.get("app", None)} for param in child: data[child_name][param.get("name")] = parse_parameters(param) - elif "item" == parent_node.tag: + elif parent_node.tag == "item": data[child_name] = parse_parameters(child) return data diff --git a/splunklib/searchcommands/decorators.py b/splunklib/searchcommands/decorators.py index 87b538e5..63be49fa 100644 --- a/splunklib/searchcommands/decorators.py +++ b/splunklib/searchcommands/decorators.py @@ -218,7 +218,7 @@ def _get_specification(self): try: specification = ConfigurationSettingsType.specification_matrix[name] except KeyError: - raise AttributeError(f"Unknown configuration setting: {name}={repr(self._value)}") + raise AttributeError(f"Unknown configuration setting: {name}={self._value!r}") return ConfigurationSettingsType.validate_configuration_setting, specification diff --git a/splunklib/searchcommands/external_search_command.py b/splunklib/searchcommands/external_search_command.py index ad76be46..dff31717 100644 --- a/splunklib/searchcommands/external_search_command.py +++ b/splunklib/searchcommands/external_search_command.py @@ -31,7 +31,7 @@ class ExternalSearchCommand: def __init__(self, path, argv=None, environ=None): if not isinstance(path, (bytes, str)): - raise ValueError(f"Expected a string value for path, not {repr(path)}") + raise ValueError(f"Expected a string value for path, not {path!r}") self._logger = getLogger(self.__class__.__name__) self._path = str(path) @@ -45,22 +45,22 @@ def __init__(self, path, argv=None, environ=None): @property def argv(self): - return getattr(self, "_argv") + return self._argv @argv.setter def argv(self, value): if not (value is None or isinstance(value, (list, tuple))): - raise ValueError(f"Expected a list, tuple or value of None for argv, not {repr(value)}") + raise ValueError(f"Expected a list, tuple or value of None for argv, not {value!r}") self._argv = value @property def environ(self): - return getattr(self, "_environ") + return self._environ @environ.setter def environ(self, value): if not (value is None or isinstance(value, dict)): - raise ValueError(f"Expected a dictionary value for environ, not {repr(value)}") + raise ValueError(f"Expected a dictionary value for environ, not {value!r}") self._environ = value @property @@ -83,7 +83,7 @@ def execute(self): self._execute(self._path, self._argv, self._environ) except: error_type, error, tb = sys.exc_info() - message = f"Command execution failed: {str(error)}" + message = f"Command execution failed: {error!s}" self._logger.error(message + "\nTraceback:\n" + "".join(traceback.format_tb(tb))) sys.exit(1) diff --git a/splunklib/searchcommands/internals.py b/splunklib/searchcommands/internals.py index 7f1b3f72..40e46855 100644 --- a/splunklib/searchcommands/internals.py +++ b/splunklib/searchcommands/internals.py @@ -251,11 +251,11 @@ class ConfigurationSettingsType(type): """ def __new__(mcs, module, name, bases): - mcs = super(ConfigurationSettingsType, mcs).__new__(mcs, str(name), bases, {}) + mcs = super().__new__(mcs, str(name), bases, {}) return mcs def __init__(cls, module, name, bases): - super(ConfigurationSettingsType, cls).__init__(name, bases, None) + super().__init__(name, bases, None) cls.__module__ = module @staticmethod @@ -265,9 +265,9 @@ def validate_configuration_setting(specification, name, value): type_names = specification.type.__name__ else: type_names = ", ".join(map(lambda t: t.__name__, specification.type)) - raise ValueError(f"Expected {type_names} value, not {name}={repr(value)}") + raise ValueError(f"Expected {type_names} value, not {name}={value!r}") if specification.constraint and not specification.constraint(value): - raise ValueError(f"Illegal value: {name}={repr(value)}") + raise ValueError(f"Illegal value: {name}={value!r}") return value specification = namedtuple( @@ -549,7 +549,7 @@ def _write_record(self, record): if fieldnames is None: self._fieldnames = fieldnames = list(record.keys()) self._fieldnames.extend([i for i in self.custom_fields if i not in self._fieldnames]) - value_list = map(lambda fn: (str(fn), str("__mv_") + str(fn)), fieldnames) + value_list = map(lambda fn: (str(fn), "__mv_" + str(fn)), fieldnames) self._writerow(list(chain.from_iterable(value_list))) get_value = record.get diff --git a/splunklib/searchcommands/reporting_command.py b/splunklib/searchcommands/reporting_command.py index 317cc3dd..5530ad14 100644 --- a/splunklib/searchcommands/reporting_command.py +++ b/splunklib/searchcommands/reporting_command.py @@ -89,7 +89,7 @@ def _has_custom_method(self, method_name): def prepare(self): if self.phase == "map": if self._has_custom_method("map"): - phase_method = getattr(self.__class__, "map") + phase_method = self.__class__.map self._configuration = phase_method.ConfigurationSettings(self) else: self._configuration = self.ConfigurationSettings(self) diff --git a/splunklib/searchcommands/search_command.py b/splunklib/searchcommands/search_command.py index 15add5f7..6c28fc02 100644 --- a/splunklib/searchcommands/search_command.py +++ b/splunklib/searchcommands/search_command.py @@ -15,7 +15,6 @@ # Absolute imports import csv -import io import os import re import sys @@ -279,11 +278,11 @@ def search_results_info(self): path = os.path.join(dispatch_dir, "info.csv") try: - with io.open(path, "r") as f: + with open(path) as f: reader = csv.reader(f, dialect=CsvDialect) fields = next(reader) values = next(reader) - except IOError as error: + except OSError as error: if error.errno == 2: self.logger.error( f"Search results info file {json_encode_string(path)} does not exist." @@ -606,10 +605,10 @@ def _prepare_recording(self, argv, ifile, ofile): # Save a splunk command line because it is useful for developing tests with open(recording + ".splunk_cmd", "wb") as f: - f.write("splunk cmd python ".encode()) + f.write(b"splunk cmd python ") f.write(os.path.basename(argv[0]).encode()) for arg in islice(argv, 1, len(argv)): - f.write(" ".encode()) + f.write(b" ") f.write(arg.encode()) return ifile, ofile @@ -1048,7 +1047,7 @@ def _report_unexpected_error(self): filename = origin.tb_frame.f_code.co_filename lineno = origin.tb_lineno - message = f'{error_type.__name__} at "{filename}", line {str(lineno)} : {error}' + message = f'{error_type.__name__} at "{filename}", line {lineno!s} : {error}' environment.splunklib_logger.error( message + "\nTraceback:\n" + "".join(traceback.format_tb(tb)) diff --git a/splunklib/searchcommands/validators.py b/splunklib/searchcommands/validators.py index 19d09bc0..587ca87b 100644 --- a/splunklib/searchcommands/validators.py +++ b/splunklib/searchcommands/validators.py @@ -12,11 +12,12 @@ # License for the specific language governing permissions and limitations # under the License. +import builtins import csv import os import re from collections import namedtuple -from io import StringIO, open +from io import StringIO from json.encoder import encode_basestring_ascii as json_encode_string from os import getcwd @@ -142,11 +143,11 @@ def __call__(self, value): try: value = ( - open(path, self.mode) + builtins.open(path, self.mode) if self.buffering is None - else open(path, self.mode, self.buffering) + else builtins.open(path, self.mode, self.buffering) ) - except IOError as error: + except OSError as error: raise ValueError( f"Cannot open {value} with mode={self.mode} and buffering={self.buffering}: {error}" ) @@ -286,7 +287,7 @@ def format(self, value): m = value // 60 % 60 h = value // (60 * 60) - return "{0:02d}:{1:02d}:{2:02d}".format(h, m, s) + return f"{h:02d}:{m:02d}:{s:02d}" _60 = Integer(0, 59) _unsigned = Integer(0) @@ -299,17 +300,17 @@ class Dialect(csv.Dialect): """Describes the properties of list option values.""" strict = True - delimiter = str(",") - quotechar = str('"') + delimiter = "," + quotechar = '"' doublequote = True - lineterminator = str("\n") + lineterminator = "\n" skipinitialspace = True quoting = csv.QUOTE_MINIMAL def __init__(self, validator=None): if not (validator is None or isinstance(validator, Validator)): raise ValueError( - f"Expected a Validator instance or None for validator, not {repr(validator)}" + f"Expected a Validator instance or None for validator, not {validator!r}" ) self._validator = validator @@ -440,8 +441,8 @@ def format(self, value): "Code", "Duration", "File", - "Integer", "Float", + "Integer", "List", "Map", "RegularExpression", diff --git a/splunklib/utils.py b/splunklib/utils.py index c4ae0f91..4e82ac65 100644 --- a/splunklib/utils.py +++ b/splunklib/utils.py @@ -44,4 +44,4 @@ def ensure_str(s, encoding="utf-8", errors="strict"): def assertRegex(self, *args, **kwargs): - return getattr(self, "assertRegex")(*args, **kwargs) + return self.assertRegex(*args, **kwargs) diff --git a/tests/ai_testlib.py b/tests/ai_testlib.py index f25b1657..e90a207a 100644 --- a/tests/ai_testlib.py +++ b/tests/ai_testlib.py @@ -41,7 +41,7 @@ def _parse_content_block(self, block: str | ContentBlock) -> str | None: case str(): return block case _: - warn(f"Skipping OpaqueBlock when parsing the AIMessage.content") + warn("Skipping OpaqueBlock when parsing the AIMessage.content") return None def parse_content(self, message: AIMessage) -> str: diff --git a/tests/integration/ai/test_conversation_store.py b/tests/integration/ai/test_conversation_store.py index d26b6317..7b45fe31 100644 --- a/tests/integration/ai/test_conversation_store.py +++ b/tests/integration/ai/test_conversation_store.py @@ -286,16 +286,17 @@ async def _model_middleware( after_first_call = True return await handler(request) - async with Agent( - model=(await self.model()), - system_prompt="You are a helpful assistant. ", - service=self.service, - name="MemoryAgent", - description=("A conversational agent that remembers user information. "), - conversation_store=InMemoryStore(), - middleware=[_model_middleware], - ) as subagent: - async with Agent( + async with ( + Agent( + model=(await self.model()), + system_prompt="You are a helpful assistant. ", + service=self.service, + name="MemoryAgent", + description=("A conversational agent that remembers user information. "), + conversation_store=InMemoryStore(), + middleware=[_model_middleware], + ) as subagent, + Agent( model=(await self.model()), system_prompt=( "You are a supervisor assistant. " @@ -305,33 +306,34 @@ async def _model_middleware( service=self.service, conversation_store=InMemoryStore(), agents=[subagent], - ) as supervisor: - resp = await supervisor.invoke( - [HumanMessage(content="Tell MemoryAgent that my name is Chris.")] - ) + ) as supervisor, + ): + resp = await supervisor.invoke( + [HumanMessage(content="Tell MemoryAgent that my name is Chris.")] + ) - assert after_first_call, "middleware not called" + assert after_first_call, "middleware not called" - ai_msgs = [m for m in resp.messages if isinstance(m, AIMessage)] - assert len(ai_msgs) == 2, "invalid AIMessage count" + ai_msgs = [m for m in resp.messages if isinstance(m, AIMessage)] + assert len(ai_msgs) == 2, "invalid AIMessage count" - first_ai_msg = ai_msgs[0] - assert isinstance(first_ai_msg.calls[0], SubagentCall) - thread_id = first_ai_msg.calls[0].thread_id - assert thread_id is not None, "missing thread_id" + first_ai_msg = ai_msgs[0] + assert isinstance(first_ai_msg.calls[0], SubagentCall) + thread_id = first_ai_msg.calls[0].thread_id + assert thread_id is not None, "missing thread_id" - resp = await supervisor.invoke( - [HumanMessage(content="Ask MemoryAgent what my name is.")] - ) + resp = await supervisor.invoke( + [HumanMessage(content="Ask MemoryAgent what my name is.")] + ) - ai_msgs = [m for m in resp.messages if isinstance(m, AIMessage)] - assert len(ai_msgs) == 4, "invalid AIMessage count" + ai_msgs = [m for m in resp.messages if isinstance(m, AIMessage)] + assert len(ai_msgs) == 4, "invalid AIMessage count" - third_ai_msg = ai_msgs[2] - assert isinstance(third_ai_msg.calls[0], SubagentCall) - assert thread_id == third_ai_msg.calls[0].thread_id, "missing thread_id" + third_ai_msg = ai_msgs[2] + assert isinstance(third_ai_msg.calls[0], SubagentCall) + assert thread_id == third_ai_msg.calls[0].thread_id, "missing thread_id" - assert "chris" in self.parse_content(resp.final_message).lower() + assert "chris" in self.parse_content(resp.final_message).lower() @pytest.mark.asyncio @deterministic_thread_ids() @@ -360,17 +362,18 @@ async def _model_middleware( class MemoryAgentInput(BaseModel): message: str = Field(description="The message to send to the memory agent") - async with Agent( - model=(await self.model()), - system_prompt="You are a helpful assistant. ", - service=self.service, - name="MemoryAgent", - description=("A conversational agent that remembers user information. "), - conversation_store=InMemoryStore(), - input_schema=MemoryAgentInput, - middleware=[_model_middleware], - ) as subagent: - async with Agent( + async with ( + Agent( + model=(await self.model()), + system_prompt="You are a helpful assistant. ", + service=self.service, + name="MemoryAgent", + description=("A conversational agent that remembers user information. "), + conversation_store=InMemoryStore(), + input_schema=MemoryAgentInput, + middleware=[_model_middleware], + ) as subagent, + Agent( model=(await self.model()), system_prompt=( "You are a supervisor assistant. " @@ -380,30 +383,31 @@ class MemoryAgentInput(BaseModel): service=self.service, conversation_store=InMemoryStore(), agents=[subagent], - ) as supervisor: - resp = await supervisor.invoke( - [HumanMessage(content="Tell MemoryAgent that my name is Chris.")] - ) + ) as supervisor, + ): + resp = await supervisor.invoke( + [HumanMessage(content="Tell MemoryAgent that my name is Chris.")] + ) - assert after_first_call, "middleware not called" + assert after_first_call, "middleware not called" - ai_msgs = [m for m in resp.messages if isinstance(m, AIMessage)] - assert len(ai_msgs) == 2, "invalid AIMessage count" + ai_msgs = [m for m in resp.messages if isinstance(m, AIMessage)] + assert len(ai_msgs) == 2, "invalid AIMessage count" - first_ai_msg = ai_msgs[0] - assert isinstance(first_ai_msg.calls[0], SubagentCall) - thread_id = first_ai_msg.calls[0].thread_id - assert thread_id is not None, "missing thread_id" + first_ai_msg = ai_msgs[0] + assert isinstance(first_ai_msg.calls[0], SubagentCall) + thread_id = first_ai_msg.calls[0].thread_id + assert thread_id is not None, "missing thread_id" - resp = await supervisor.invoke( - [HumanMessage(content="Ask MemoryAgent what my name is.")] - ) + resp = await supervisor.invoke( + [HumanMessage(content="Ask MemoryAgent what my name is.")] + ) - ai_msgs = [m for m in resp.messages if isinstance(m, AIMessage)] - assert len(ai_msgs) == 4, "invalid AIMessage count" + ai_msgs = [m for m in resp.messages if isinstance(m, AIMessage)] + assert len(ai_msgs) == 4, "invalid AIMessage count" - third_ai_msg = ai_msgs[2] - assert isinstance(third_ai_msg.calls[0], SubagentCall) - assert thread_id == third_ai_msg.calls[0].thread_id, "invalid thread_id" + third_ai_msg = ai_msgs[2] + assert isinstance(third_ai_msg.calls[0], SubagentCall) + assert thread_id == third_ai_msg.calls[0].thread_id, "invalid thread_id" - assert "chris" in self.parse_content(resp.final_message).lower() + assert "chris" in self.parse_content(resp.final_message).lower() diff --git a/tests/integration/ai/test_hooks.py b/tests/integration/ai/test_hooks.py index 94b64cfd..729a00d4 100644 --- a/tests/integration/ai/test_hooks.py +++ b/tests/integration/ai/test_hooks.py @@ -72,7 +72,7 @@ def test_hook_after(resp: ModelResponse) -> None: hook_calls += 1 response = self.parse_content(resp.message).strip().lower().replace(".", "") - assert "stefan" == response + assert response == "stefan" @after_model async def test_async_hook_after(resp: ModelResponse) -> None: @@ -80,7 +80,7 @@ async def test_async_hook_after(resp: ModelResponse) -> None: hook_calls += 1 response = self.parse_content(resp.message).strip().lower().replace(".", "") - assert "stefan" == response + assert response == "stefan" async with Agent( model=(await self.model()), @@ -102,7 +102,7 @@ async def test_async_hook_after(resp: ModelResponse) -> None: ) response = self.parse_content(result.final_message).strip().lower().replace(".", "") - assert "stefan" == response + assert response == "stefan" assert hook_calls == 4 @pytest.mark.asyncio @@ -170,7 +170,7 @@ async def after_async_agent_hook(resp: AgentResponse) -> None: ) response = self.parse_content(result.final_message).strip().lower().replace(".", "") - assert '{"name":"stefan"}' == response + assert response == '{"name":"stefan"}' assert hook_calls == 4 @pytest.mark.asyncio diff --git a/tests/integration/ai/test_middleware.py b/tests/integration/ai/test_middleware.py index 5255f23b..569203eb 100644 --- a/tests/integration/ai/test_middleware.py +++ b/tests/integration/ai/test_middleware.py @@ -662,7 +662,7 @@ async def test_middleware( ) response = self.parse_content(res.final_message) - assert "My response is made up" == response + assert response == "My response is made up" assert middleware_called, "Middleware was not called" @pytest.mark.asyncio diff --git a/tests/integration/test_binding.py b/tests/integration/test_binding.py index a6254029..8ba6b8de 100755 --- a/tests/integration/test_binding.py +++ b/tests/integration/test_binding.py @@ -271,13 +271,13 @@ class TestSocket(BindingTestCase): def test_socket(self): socket = self.context.connect() socket.write( - (f"POST {self.context._abspath('some/path/to/post/to')} HTTP/1.1\r\n").encode("utf-8") + (f"POST {self.context._abspath('some/path/to/post/to')} HTTP/1.1\r\n").encode() ) - socket.write((f"Host: {self.context.host}:{self.context.port}\r\n").encode("utf-8")) - socket.write("Accept-Encoding: identity\r\n".encode("utf-8")) - socket.write((f"Authorization: {self.context.token}\r\n").encode("utf-8")) - socket.write("X-Splunk-Input-Mode: Streaming\r\n".encode("utf-8")) - socket.write("\r\n".encode("utf-8")) + socket.write((f"Host: {self.context.host}:{self.context.port}\r\n").encode()) + socket.write(b"Accept-Encoding: identity\r\n") + socket.write((f"Authorization: {self.context.token}\r\n").encode()) + socket.write(b"X-Splunk-Input-Mode: Streaming\r\n") + socket.write(b"\r\n") socket.close() # Sockets take bytes not strings @@ -445,7 +445,7 @@ def urllib2_handler(url, message, **kwargs): req = Request(url, data, headers) try: response = urlopen(req, context=ssl._create_unverified_context()) # nosemgrep - except HTTPError as response: + except HTTPError: pass # Propagate HTTP errors via the returned response message return { "status": response.code, @@ -489,7 +489,7 @@ def urllib2_insert_cookie_handler(url, message, **kwargs): req = Request(url, data, headers) try: response = urlopen(req, context=ssl._create_unverified_context()) # nosemgrep - except HTTPError as response: + except HTTPError: pass # Propagate HTTP errors via the returned response message # Mimic the insertion of 3rd party cookies into the response. @@ -803,13 +803,13 @@ def test_preexisting_token(self): socket = newContext.connect() socket.write( - (f"POST {self.context._abspath('some/path/to/post/to')} HTTP/1.1\r\n").encode("utf-8") + (f"POST {self.context._abspath('some/path/to/post/to')} HTTP/1.1\r\n").encode() ) - socket.write((f"Host: {self.context.host}:{self.context.port}\r\n").encode("utf-8")) - socket.write("Accept-Encoding: identity\r\n".encode("utf-8")) - socket.write((f"Authorization: {self.context.token}\r\n").encode("utf-8")) - socket.write("X-Splunk-Input-Mode: Streaming\r\n".encode("utf-8")) - socket.write("\r\n".encode("utf-8")) + socket.write((f"Host: {self.context.host}:{self.context.port}\r\n").encode()) + socket.write(b"Accept-Encoding: identity\r\n") + socket.write((f"Authorization: {self.context.token}\r\n").encode()) + socket.write(b"X-Splunk-Input-Mode: Streaming\r\n") + socket.write(b"\r\n") socket.close() def test_preexisting_token_sans_splunk(self): @@ -830,13 +830,13 @@ def test_preexisting_token_sans_splunk(self): socket = newContext.connect() socket.write( - (f"POST {self.context._abspath('some/path/to/post/to')} HTTP/1.1\r\n").encode("utf-8") + (f"POST {self.context._abspath('some/path/to/post/to')} HTTP/1.1\r\n").encode() ) - socket.write((f"Host: {self.context.host}:{self.context.port}\r\n").encode("utf-8")) - socket.write("Accept-Encoding: identity\r\n".encode("utf-8")) - socket.write((f"Authorization: {self.context.token}\r\n").encode("utf-8")) - socket.write("X-Splunk-Input-Mode: Streaming\r\n".encode("utf-8")) - socket.write("\r\n".encode("utf-8")) + socket.write((f"Host: {self.context.host}:{self.context.port}\r\n").encode()) + socket.write(b"Accept-Encoding: identity\r\n") + socket.write((f"Authorization: {self.context.token}\r\n").encode()) + socket.write(b"X-Splunk-Input-Mode: Streaming\r\n") + socket.write(b"\r\n") socket.close() def test_connect_with_preexisting_token_sans_user_and_pass(self): @@ -852,13 +852,13 @@ def test_connect_with_preexisting_token_sans_user_and_pass(self): socket = newContext.connect() socket.write( - (f"POST {self.context._abspath('some/path/to/post/to')} HTTP/1.1\r\n").encode("utf-8") + (f"POST {self.context._abspath('some/path/to/post/to')} HTTP/1.1\r\n").encode() ) - socket.write((f"Host: {self.context.host}:{self.context.port}\r\n").encode("utf-8")) - socket.write("Accept-Encoding: identity\r\n".encode("utf-8")) - socket.write((f"Authorization: {self.context.token}\r\n").encode("utf-8")) - socket.write("X-Splunk-Input-Mode: Streaming\r\n".encode("utf-8")) - socket.write("\r\n".encode("utf-8")) + socket.write((f"Host: {self.context.host}:{self.context.port}\r\n").encode()) + socket.write(b"Accept-Encoding: identity\r\n") + socket.write((f"Authorization: {self.context.token}\r\n").encode()) + socket.write(b"X-Splunk-Input-Mode: Streaming\r\n") + socket.write(b"\r\n") socket.close() diff --git a/tests/integration/test_collection.py b/tests/integration/test_collection.py index d1bd13a1..e049d57a 100755 --- a/tests/integration/test_collection.py +++ b/tests/integration/test_collection.py @@ -13,7 +13,6 @@ # under the License. import logging -from contextlib import contextmanager from splunklib import client from tests import testlib diff --git a/tests/integration/test_job.py b/tests/integration/test_job.py index b07b285b..cc16443f 100755 --- a/tests/integration/test_job.py +++ b/tests/integration/test_job.py @@ -12,12 +12,8 @@ # License for the specific language governing permissions and limitations # under the License. -import io import unittest -import warnings from datetime import datetime -from io import BytesIO -from pathlib import Path from time import sleep import pytest @@ -70,7 +66,7 @@ def test_export(self): self.assertTrue(len(nonmessages) <= 3) def test_export_docstring_sample(self): - from splunklib import client, results + from splunklib import results service = self.service # cheat rr = results.JSONResultsReader(service.jobs.export("search * | head 5", output_mode="json")) @@ -101,7 +97,7 @@ def test_results_docstring_sample(self): assert rr.is_preview == False def test_preview_docstring_sample(self): - from splunklib import client, results + from splunklib import results service = self.service # cheat job = service.jobs.create("search * | head 5") @@ -119,7 +115,7 @@ def test_preview_docstring_sample(self): pass # print("Job is finished. Results are final.") def test_oneshot_docstring_sample(self): - from splunklib import client, results + from splunklib import results service = self.service # cheat rr = results.JSONResultsReader( diff --git a/tests/integration/test_macro.py b/tests/integration/test_macro.py index 3c016506..56245171 100755 --- a/tests/integration/test_macro.py +++ b/tests/integration/test_macro.py @@ -12,7 +12,6 @@ # License for the specific language governing permissions and limitations # under the License. -from __future__ import absolute_import import logging @@ -27,7 +26,7 @@ @pytest.mark.smoke class TestMacro(testlib.SDKTestCase): def setUp(self): - super(TestMacro, self).setUp() + super().setUp() macros = self.service.macros logging.debug("Macros namespace: %s", macros.service.namespace) self.macro_name = testlib.tmpname() @@ -35,7 +34,7 @@ def setUp(self): self.macro = macros.create(self.macro_name, definition) def tearDown(self): - super(TestMacro, self).setUp() + super().setUp() for macro in self.service.macros: if macro.name.startswith("delete-me"): self.service.macros.delete(macro.name) diff --git a/tests/integration/test_role.py b/tests/integration/test_role.py index 1847b495..87efa47c 100755 --- a/tests/integration/test_role.py +++ b/tests/integration/test_role.py @@ -12,7 +12,6 @@ # License for the specific language governing permissions and limitations # under the License. -import logging from splunklib import client from tests import testlib diff --git a/tests/testlib.py b/tests/testlib.py index 5b951e93..cd2c55ce 100644 --- a/tests/testlib.py +++ b/tests/testlib.py @@ -178,7 +178,7 @@ def install_app_from_collection(self, name): self.service.post("apps/local", **kwargs) except client.HTTPError as he: if he.status == 400: - raise IOError(f"App {name} not found in app collection") + raise OSError(f"App {name} not found in app collection") if self.service.restart_required: self.restart_splunk() self.installedApps.append(name) diff --git a/tests/unit/ai/engine/test_langchain_backend.py b/tests/unit/ai/engine/test_langchain_backend.py index 8141b453..b1d6d552 100644 --- a/tests/unit/ai/engine/test_langchain_backend.py +++ b/tests/unit/ai/engine/test_langchain_backend.py @@ -150,7 +150,7 @@ def test_map_message_from_langchain_ai_tool_call_with_additional_kwargs( self, ) -> None: tool_call = LC_ToolCall( - name=f"__local-startup_time", + name="__local-startup_time", args={"q": "test"}, id="tc-2", ) @@ -420,7 +420,7 @@ def test_map_message_to_langchain_ai_with_tool_call_with_thought_signature( assert isinstance(mapped, LC_AIMessage) assert mapped.tool_calls == [ LC_ToolCall( - name=f"__local-startup_time", + name="__local-startup_time", args={"q": "test"}, id="tc-2", type="tool_call", diff --git a/tests/unit/modularinput/modularinput_testlib.py b/tests/unit/modularinput/modularinput_testlib.py index 329b614c..189b1b4f 100644 --- a/tests/unit/modularinput/modularinput_testlib.py +++ b/tests/unit/modularinput/modularinput_testlib.py @@ -12,7 +12,6 @@ # License for the specific language governing permissions and limitations # under the License. -import io import os import sys @@ -20,4 +19,4 @@ def data_open(filepath): - return io.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), filepath), "rb") + return open(os.path.join(os.path.dirname(os.path.abspath(__file__)), filepath), "rb") diff --git a/tests/unit/searchcommands/test_builtin_options.py b/tests/unit/searchcommands/test_builtin_options.py index d28d67d6..91132125 100644 --- a/tests/unit/searchcommands/test_builtin_options.py +++ b/tests/unit/searchcommands/test_builtin_options.py @@ -229,11 +229,11 @@ def _test_boolean_option(self, option): pass except BaseException as error: self.fail( - f"Expected ValueError when setting {option.name}={repr(value)}, but {type(error)} was raised" + f"Expected ValueError when setting {option.name}={value!r}, but {type(error)} was raised" ) else: self.fail( - f"Expected ValueError, but {option.name}={repr(option.fget(command))} was accepted." + f"Expected ValueError, but {option.name}={option.fget(command)!r} was accepted." ) diff --git a/tests/unit/searchcommands/test_decorators.py b/tests/unit/searchcommands/test_decorators.py index 4b2d74d4..e1f58e17 100755 --- a/tests/unit/searchcommands/test_decorators.py +++ b/tests/unit/searchcommands/test_decorators.py @@ -332,10 +332,10 @@ def fix_up(cls, command_class): self.assertIsInstance( error, ValueError, - f"Expected ValueError, not {type(error).__name__}({error}) for {name}={repr(value)}", + f"Expected ValueError, not {type(error).__name__}({error}) for {name}={value!r}", ) else: - self.fail(f"Expected ValueError, not success for {name}={repr(value)}") + self.fail(f"Expected ValueError, not success for {name}={value!r}") settings_class = new_configuration_settings_class() settings_instance = settings_class(command=None) diff --git a/tests/unit/searchcommands/test_internals_v2.py b/tests/unit/searchcommands/test_internals_v2.py index 6109e5ba..0879c1ca 100755 --- a/tests/unit/searchcommands/test_internals_v2.py +++ b/tests/unit/searchcommands/test_internals_v2.py @@ -235,11 +235,9 @@ def _compare_chunks(self, chunks_1, chunks_2): self.assertDictEqual( chunk_1.metadata, chunk_2.metadata, - 'Chunk {0}: metadata error: "{1}" != "{2}"'.format( - n, chunk_1.metadata, chunk_2.metadata - ), + f'Chunk {n}: metadata error: "{chunk_1.metadata}" != "{chunk_2.metadata}"', ) - self.assertMultiLineEqual(chunk_1.body, chunk_2.body, "Chunk {0}: data error".format(n)) + self.assertMultiLineEqual(chunk_1.body, chunk_2.body, f"Chunk {n}: data error") n += 1 def _load_chunks(self, ifile): diff --git a/tests/unit/searchcommands/test_search_command.py b/tests/unit/searchcommands/test_search_command.py index d9b68090..79e391ab 100755 --- a/tests/unit/searchcommands/test_search_command.py +++ b/tests/unit/searchcommands/test_search_command.py @@ -22,7 +22,7 @@ import pytest from splunklib.client import Service -from splunklib.searchcommands import Configuration, StreamingCommand +from splunklib.searchcommands import Configuration from splunklib.searchcommands.decorators import ConfigurationSetting, Option from splunklib.searchcommands.internals import ObjectView from splunklib.searchcommands.search_command import SearchCommand @@ -166,7 +166,7 @@ def test_process_scpv2(self): # noinspection PyTypeChecker command.process(argv, ifile, ofile=result) except SystemExit as error: - self.fail("Unexpected exception: {}: {}".format(type(error).__name__, error)) + self.fail(f"Unexpected exception: {type(error).__name__}: {error}") self.assertEqual(command.logging_configuration, logging_configuration) self.assertEqual(command.logging_level, "ERROR") diff --git a/tests/unit/test_data.py b/tests/unit/test_data.py index 359e84f2..b10a1da0 100755 --- a/tests/unit/test_data.py +++ b/tests/unit/test_data.py @@ -87,7 +87,7 @@ def test_real(self): """Test some real Splunk response examples.""" testpath = path.dirname(path.abspath(__file__)) - fh = open(path.join(testpath, "data/services.xml"), "r") + fh = open(path.join(testpath, "data/services.xml")) result = data.load(fh.read()) self.assertTrue("feed" in result) self.assertTrue("author" in result.feed) @@ -116,7 +116,7 @@ def test_real(self): ], ) - fh = open(path.join(testpath, "data/services.server.info.xml"), "r") + fh = open(path.join(testpath, "data/services.server.info.xml")) result = data.load(fh.read()) self.assertTrue("feed" in result) self.assertTrue("author" in result.feed) diff --git a/utils/cmdopts.py b/utils/cmdopts.py index d76066c7..b3f74038 100644 --- a/utils/cmdopts.py +++ b/utils/cmdopts.py @@ -20,7 +20,7 @@ from dotenv import dotenv_values -__all__ = ["error", "Parser", "cmdline"] +__all__ = ["Parser", "cmdline", "error"] # Print the given message to stderr, and optionally exit