From efad7a0d380dfdd812a97686b49df664e0d690be Mon Sep 17 00:00:00 2001 From: Alexei Znamensky <103110+russoz@users.noreply.github.com> Date: Mon, 27 Oct 2025 12:32:33 +1300 Subject: [PATCH] unit tests: use f-strings (#10993) --- tests/unit/plugins/become/test_doas.py | 9 +++------ tests/unit/plugins/become/test_dzdo.py | 9 +++------ tests/unit/plugins/become/test_ksu.py | 9 +++------ tests/unit/plugins/become/test_pbrun.py | 9 +++------ tests/unit/plugins/become/test_pfexec.py | 6 +++--- tests/unit/plugins/become/test_sudosu.py | 3 +-- tests/unit/plugins/callback/test_elastic.py | 3 +-- tests/unit/plugins/callback/test_opentelemetry.py | 3 +-- tests/unit/plugins/inventory/test_icinga2.py | 2 +- tests/unit/plugins/inventory/test_lxd.py | 2 +- .../lookup/test_bitwarden_secrets_manager.py | 2 +- tests/unit/plugins/lookup/test_etcd3.py | 4 ++-- tests/unit/plugins/lookup/test_lastpass.py | 5 ++--- tests/unit/plugins/lookup/test_onepassword.py | 4 ++-- tests/unit/plugins/lookup/test_tss.py | 2 +- tests/unit/plugins/module_utils/test_cmd_runner.py | 14 +++++--------- tests/unit/plugins/module_utils/test_database.py | 2 +- .../unit/plugins/module_utils/test_ocapi_utils.py | 6 +++--- .../plugins/module_utils/test_python_runner.py | 10 +++------- tests/unit/plugins/module_utils/test_vardict.py | 6 +++--- .../unit/plugins/module_utils/xenserver/common.py | 2 +- .../xenserver/test_set_vm_power_state.py | 4 ++-- .../xenserver/test_wait_for_functions.py | 8 ++++---- .../plugins/module_utils/xenserver/test_xapi.py | 6 +++--- .../module_utils/xenserver/test_xenserverobject.py | 2 +- 25 files changed, 54 insertions(+), 78 deletions(-) diff --git a/tests/unit/plugins/become/test_doas.py b/tests/unit/plugins/become/test_doas.py index 29bd04b6f9..92dcc04c15 100644 --- a/tests/unit/plugins/become/test_doas.py +++ b/tests/unit/plugins/become/test_doas.py @@ -31,8 +31,7 @@ def test_doas_basic(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert (re.match("""%s %s %s -c 'echo %s; %s'""" % (doas_exe, doas_flags, default_exe, success, - default_cmd), cmd) is not None) + assert (re.match(f"""{doas_exe} {doas_flags} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None) def test_doas(mocker, parser, reset_cli_args): @@ -54,8 +53,7 @@ def test_doas(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert (re.match("""%s %s -u %s %s -c 'echo %s; %s'""" % (doas_exe, doas_flags, task['become_user'], default_exe, success, - default_cmd), cmd) is not None) + assert (re.match(f"""{doas_exe} {doas_flags} -u {task['become_user']} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None) def test_doas_varoptions(mocker, parser, reset_cli_args): @@ -80,5 +78,4 @@ def test_doas_varoptions(mocker, parser, reset_cli_args): } cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert (re.match("""%s %s -u %s %s -c 'echo %s; %s'""" % (doas_exe, doas_flags, var_options['ansible_become_user'], default_exe, success, - default_cmd), cmd) is not None) + assert (re.match(f"""{doas_exe} {doas_flags} -u {var_options['ansible_become_user']} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None) diff --git a/tests/unit/plugins/become/test_dzdo.py b/tests/unit/plugins/become/test_dzdo.py index 58797a06df..ff5f1f6b18 100644 --- a/tests/unit/plugins/become/test_dzdo.py +++ b/tests/unit/plugins/become/test_dzdo.py @@ -31,8 +31,7 @@ def test_dzdo_basic(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert re.match("""%s %s %s -c 'echo %s; %s'""" % (dzdo_exe, dzdo_flags, default_exe, - success, default_cmd), cmd) is not None + assert re.match(f"""{dzdo_exe} {dzdo_flags} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None def test_dzdo(mocker, parser, reset_cli_args): @@ -54,8 +53,7 @@ def test_dzdo(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert re.match("""%s %s -u %s %s -c 'echo %s; %s'""" % (dzdo_exe, dzdo_flags, task['become_user'], default_exe, - success, default_cmd), cmd) is not None + assert re.match(f"""{dzdo_exe} {dzdo_flags} -u {task['become_user']} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None task['become_pass'] = 'testpass' cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) @@ -85,8 +83,7 @@ def test_dzdo_varoptions(mocker, parser, reset_cli_args): } cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert re.match("""%s %s -u %s %s -c 'echo %s; %s'""" % (dzdo_exe, dzdo_flags, var_options['ansible_become_user'], default_exe, - success, default_cmd), cmd) is not None + assert re.match(f"""{dzdo_exe} {dzdo_flags} -u {var_options['ansible_become_user']} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None var_options['ansible_become_pass'] = 'testpass' cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) diff --git a/tests/unit/plugins/become/test_ksu.py b/tests/unit/plugins/become/test_ksu.py index 24606b383d..45234443fb 100644 --- a/tests/unit/plugins/become/test_ksu.py +++ b/tests/unit/plugins/become/test_ksu.py @@ -32,8 +32,7 @@ def test_ksu_basic(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert (re.match("""%s %s %s -e %s -c 'echo %s; %s'""" % (ksu_exe, task['become_user'], ksu_flags, - default_exe, success, default_cmd), cmd) is not None) + assert (re.match(f"""{ksu_exe} {task['become_user']} {ksu_flags} -e {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None) def test_ksu(mocker, parser, reset_cli_args): @@ -55,8 +54,7 @@ def test_ksu(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert (re.match("""%s %s %s -e %s -c 'echo %s; %s'""" % (ksu_exe, task['become_user'], ksu_flags, - default_exe, success, default_cmd), cmd) is not None) + assert (re.match(f"""{ksu_exe} {task['become_user']} {ksu_flags} -e {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None) def test_ksu_varoptions(mocker, parser, reset_cli_args): @@ -81,5 +79,4 @@ def test_ksu_varoptions(mocker, parser, reset_cli_args): } cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert (re.match("""%s %s %s -e %s -c 'echo %s; %s'""" % (ksu_exe, var_options['ansible_become_user'], ksu_flags, - default_exe, success, default_cmd), cmd) is not None) + assert (re.match(f"""{ksu_exe} {var_options['ansible_become_user']} {ksu_flags} -e {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None) diff --git a/tests/unit/plugins/become/test_pbrun.py b/tests/unit/plugins/become/test_pbrun.py index 0c21d898ee..5975c8df31 100644 --- a/tests/unit/plugins/become/test_pbrun.py +++ b/tests/unit/plugins/become/test_pbrun.py @@ -31,8 +31,7 @@ def test_pbrun_basic(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert re.match("""%s %s 'echo %s; %s'""" % (pbrun_exe, pbrun_flags, - success, default_cmd), cmd) is not None + assert re.match(f"""{pbrun_exe} {pbrun_flags} 'echo {success}; {default_cmd}'""", cmd) is not None def test_pbrun(mocker, parser, reset_cli_args): @@ -54,8 +53,7 @@ def test_pbrun(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert re.match("""%s %s -u %s 'echo %s; %s'""" % (pbrun_exe, pbrun_flags, task['become_user'], - success, default_cmd), cmd) is not None + assert re.match(f"""{pbrun_exe} {pbrun_flags} -u {task['become_user']} 'echo {success}; {default_cmd}'""", cmd) is not None def test_pbrun_var_varoptions(mocker, parser, reset_cli_args): @@ -80,5 +78,4 @@ def test_pbrun_var_varoptions(mocker, parser, reset_cli_args): } cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert re.match("""%s %s -u %s 'echo %s; %s'""" % (pbrun_exe, pbrun_flags, var_options['ansible_become_user'], - success, default_cmd), cmd) is not None + assert re.match(f"""{pbrun_exe} {pbrun_flags} -u {var_options['ansible_become_user']} 'echo {success}; {default_cmd}'""", cmd) is not None diff --git a/tests/unit/plugins/become/test_pfexec.py b/tests/unit/plugins/become/test_pfexec.py index 9ad2b10c9f..cb4e8e1460 100644 --- a/tests/unit/plugins/become/test_pfexec.py +++ b/tests/unit/plugins/become/test_pfexec.py @@ -31,7 +31,7 @@ def test_pfexec_basic(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert re.match("""%s %s 'echo %s; %s'""" % (pfexec_exe, pfexec_flags, success, default_cmd), cmd) is not None + assert re.match(f"""{pfexec_exe} {pfexec_flags} 'echo {success}; {default_cmd}'""", cmd) is not None def test_pfexec(mocker, parser, reset_cli_args): @@ -53,7 +53,7 @@ def test_pfexec(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert re.match("""%s %s 'echo %s; %s'""" % (pfexec_exe, pfexec_flags, success, default_cmd), cmd) is not None + assert re.match(f"""{pfexec_exe} {pfexec_flags} 'echo {success}; {default_cmd}'""", cmd) is not None def test_pfexec_varoptions(mocker, parser, reset_cli_args): @@ -78,4 +78,4 @@ def test_pfexec_varoptions(mocker, parser, reset_cli_args): } cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert re.match("""%s %s 'echo %s; %s'""" % (pfexec_exe, pfexec_flags, success, default_cmd), cmd) is not None + assert re.match(f"""{pfexec_exe} {pfexec_flags} 'echo {success}; {default_cmd}'""", cmd) is not None diff --git a/tests/unit/plugins/become/test_sudosu.py b/tests/unit/plugins/become/test_sudosu.py index 582e59c77d..c9b8cc2ddf 100644 --- a/tests/unit/plugins/become/test_sudosu.py +++ b/tests/unit/plugins/become/test_sudosu.py @@ -33,8 +33,7 @@ def test_sudosu(mocker, parser, reset_cli_args): var_options = {} cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe) print(cmd) - assert (re.match("""%s %s su -l %s %s -c 'echo %s; %s'""" % (sudo_exe, sudo_flags, task['become_user'], - default_exe, success, default_cmd), cmd) is not None) + assert (re.match(f"""{sudo_exe} {sudo_flags} su -l {task['become_user']} {default_exe} -c 'echo {success}; {default_cmd}'""", cmd) is not None) task = { 'become_user': 'foo', diff --git a/tests/unit/plugins/callback/test_elastic.py b/tests/unit/plugins/callback/test_elastic.py index 224cf27412..c3bc6aacf2 100644 --- a/tests/unit/plugins/callback/test_elastic.py +++ b/tests/unit/plugins/callback/test_elastic.py @@ -20,8 +20,7 @@ class TestOpentelemetry(unittest.TestCase): @patch('ansible_collections.community.general.plugins.callback.elastic.socket') def setUp(self, mock_socket): if sys.version_info < ELASTIC_MINIMUM_PYTHON_VERSION: - self.skipTest("Python %s+ is needed for Elastic" % - ",".join(map(str, ELASTIC_MINIMUM_PYTHON_VERSION))) + self.skipTest(f"Python {'.'.join(map(str, ELASTIC_MINIMUM_PYTHON_VERSION))}+ is needed for Elastic") mock_socket.gethostname.return_value = 'my-host' mock_socket.gethostbyname.return_value = '1.2.3.4' self.elastic = ElasticSource(display=None) diff --git a/tests/unit/plugins/callback/test_opentelemetry.py b/tests/unit/plugins/callback/test_opentelemetry.py index af4fc55660..6c7d039026 100644 --- a/tests/unit/plugins/callback/test_opentelemetry.py +++ b/tests/unit/plugins/callback/test_opentelemetry.py @@ -21,8 +21,7 @@ class TestOpentelemetry(unittest.TestCase): def setUp(self, mock_socket): # TODO: this python version validation won't be needed as long as the _time_ns call is mocked. if sys.version_info < OPENTELEMETRY_MINIMUM_PYTHON_VERSION: - self.skipTest("Python %s+ is needed for OpenTelemetry" % - ",".join(map(str, OPENTELEMETRY_MINIMUM_PYTHON_VERSION))) + self.skipTest(f"Python {'.'.join(map(str, OPENTELEMETRY_MINIMUM_PYTHON_VERSION))}+ is needed for OpenTelemetry") mock_socket.gethostname.return_value = 'my-host' mock_socket.gethostbyname.return_value = '1.2.3.4' diff --git a/tests/unit/plugins/inventory/test_icinga2.py b/tests/unit/plugins/inventory/test_icinga2.py index 673f373122..59067aa2c0 100644 --- a/tests/unit/plugins/inventory/test_icinga2.py +++ b/tests/unit/plugins/inventory/test_icinga2.py @@ -94,7 +94,7 @@ def test_populate(inventory, mocker): # module settings inventory.icinga2_user = 'ansible' inventory.icinga2_password = 'password' - inventory.icinga2_url = 'https://localhost:5665' + '/v1' + inventory.icinga2_url = "https://localhost:5665/v1" inventory.inventory_attr = "address" inventory.group_by_hostgroups = True diff --git a/tests/unit/plugins/inventory/test_lxd.py b/tests/unit/plugins/inventory/test_lxd.py index ad11780f67..ea625b5ba1 100644 --- a/tests/unit/plugins/inventory/test_lxd.py +++ b/tests/unit/plugins/inventory/test_lxd.py @@ -97,7 +97,7 @@ def test_build_inventory_groups_with_no_groupselection(inventory): group_comparative_data = {'all': [], 'ungrouped': []} eq = True - print("data: {0}".format(generated_data)) + print(f"data: {generated_data}") for key, value in group_comparative_data.items(): if generated_data[key] != value: eq = False diff --git a/tests/unit/plugins/lookup/test_bitwarden_secrets_manager.py b/tests/unit/plugins/lookup/test_bitwarden_secrets_manager.py index 9469223a6f..064b6527a8 100644 --- a/tests/unit/plugins/lookup/test_bitwarden_secrets_manager.py +++ b/tests/unit/plugins/lookup/test_bitwarden_secrets_manager.py @@ -62,7 +62,7 @@ class MockBitwardenSecretsManager(BitwardenSecretsManager): else: # This should never happen unless there's an error in the test MOCK_SECRETS. # The real Bitwarden Secrets Manager assigns each secret a unique ID. - raise ValueError("More than 1 secret found with id: '{0}'. Impossible!".format(secret_id)) + raise ValueError(f"More than 1 secret found with id: '{secret_id}'. Impossible!") return out, err, rc diff --git a/tests/unit/plugins/lookup/test_etcd3.py b/tests/unit/plugins/lookup/test_etcd3.py index 88910b2a34..d7f5a66b97 100644 --- a/tests/unit/plugins/lookup/test_etcd3.py +++ b/tests/unit/plugins/lookup/test_etcd3.py @@ -27,10 +27,10 @@ class FakeEtcd3Client(MagicMock): def get_prefix(self, key): for i in range(1, 4): - yield self.get('{0}_{1}'.format(key, i)) + yield self.get(f'{key}_{i}') def get(self, key): - return ("{0} value".format(key), FakeKVMetadata(key, None)) + return (f"{key} value", FakeKVMetadata(key, None)) class TestLookupModule(unittest.TestCase): diff --git a/tests/unit/plugins/lookup/test_lastpass.py b/tests/unit/plugins/lookup/test_lastpass.py index 8df4a8134c..ed27f44b43 100644 --- a/tests/unit/plugins/lookup/test_lastpass.py +++ b/tests/unit/plugins/lookup/test_lastpass.py @@ -45,7 +45,7 @@ class MockLPass(LPass): field_group = show_p.add_mutually_exclusive_group(required=True) for field in MOCK_ENTRIES[0].keys(): - field_group.add_argument("--{0}".format(field), default=False, action='store_true') + field_group.add_argument(f"--{field}", default=False, action='store_true') field_group.add_argument('--field', default=None) show_p.add_argument('selector', help='Unique Name or ID') @@ -73,8 +73,7 @@ class MockLPass(LPass): if args.subparser_name == 'show': if self._mock_logged_out: - return mock_exit(error='Error: Could not find decryption key.' + - ' Perhaps you need to login with `lpass login`.', rc=1) + return mock_exit(error="Error: Could not find decryption key. Perhaps you need to login with `lpass login`.", rc=1) if self._mock_disconnected: return mock_exit(error='Error: Couldn\'t resolve host name.', rc=1) diff --git a/tests/unit/plugins/lookup/test_onepassword.py b/tests/unit/plugins/lookup/test_onepassword.py index 11f53da949..f9b26167b4 100644 --- a/tests/unit/plugins/lookup/test_onepassword.py +++ b/tests/unit/plugins/lookup/test_onepassword.py @@ -134,7 +134,7 @@ def test_op_set_token_with_config(op_fixture, mocker, request): op = request.getfixturevalue(op_fixture) token = "F5417F77529B41B595D7F9D6F76EC057" mocker.patch("os.path.isfile", return_value=True) - mocker.patch.object(op._cli, "signin", return_value=(0, token + "\n", "")) + mocker.patch.object(op._cli, "signin", return_value=(0, f"{token}\n", "")) op.set_token() @@ -183,7 +183,7 @@ def test_op_set_token_without_config(op_fixture, request, mocker): token = "B988E8A2680A4A348962751A96861FA1" mocker.patch("os.path.isfile", return_value=False) mocker.patch.object(op._cli, "signin", return_value=(99, "", "")) - mocker.patch.object(op._cli, "full_signin", return_value=(0, token + "\n", "")) + mocker.patch.object(op._cli, "full_signin", return_value=(0, f"{token}\n", "")) op.set_token() diff --git a/tests/unit/plugins/lookup/test_tss.py b/tests/unit/plugins/lookup/test_tss.py index cf8273ef70..36951ee825 100644 --- a/tests/unit/plugins/lookup/test_tss.py +++ b/tests/unit/plugins/lookup/test_tss.py @@ -20,7 +20,7 @@ TSS_IMPORT_PATH = 'ansible_collections.community.general.plugins.lookup.tss' def make_absolute(name): - return '.'.join([TSS_IMPORT_PATH, name]) + return f"{TSS_IMPORT_PATH}.{name}" class SecretServerError(Exception): diff --git a/tests/unit/plugins/module_utils/test_cmd_runner.py b/tests/unit/plugins/module_utils/test_cmd_runner.py index 8152d1e6b0..c5d6b95792 100644 --- a/tests/unit/plugins/module_utils/test_cmd_runner.py +++ b/tests/unit/plugins/module_utils/test_cmd_runner.py @@ -55,8 +55,8 @@ def test_arg_format(func, value, expected, exception): fmt_func = func() try: actual = fmt_func(value) - print("formatted string = {0}".format(actual)) - assert actual == expected, "actual = {0}".format(actual) + print(f"formatted string = {actual}") + assert actual == expected, f"actual = {actual}" except Exception as e: if exception is None: raise @@ -192,7 +192,7 @@ TC_RUNNER = dict( runner_init_args=dict(default_args_order=['bb', 'aa']), runner_ctx_args=dict( args_order=['aa', 'bb'], - output_process=lambda rc, out, err: '-/-'.join([str(rc), out, err]) + output_process=lambda rc, out, err: f"{rc!s}-/-{out}-/-{err}" ), ), dict(runner_ctx_run_args=dict(bb=True), rc=0, out="ni", err="nu"), @@ -302,11 +302,7 @@ def test_runner_context(runner_input, cmd_execution, expected): orig_results = tuple(cmd_execution[x] for x in ('rc', 'out', 'err')) - print("arg_spec={0}\nparams={1}\narg_formats={2}\n".format( - arg_spec, - params, - arg_formats, - )) + print(f"arg_spec={arg_spec}\nparams={params}\narg_formats={arg_formats}\n") module = MagicMock() type(module).argument_spec = PropertyMock(return_value=arg_spec) @@ -323,7 +319,7 @@ def test_runner_context(runner_input, cmd_execution, expected): def _assert_run_info(actual, expected): reduced = {k: actual[k] for k in expected.keys()} - assert reduced == expected, "{0}".format(reduced) + assert reduced == expected, f"{reduced}" def _assert_run(runner_input, cmd_execution, expected, ctx, results): _assert_run_info(ctx.run_info, expected['run_info']) diff --git a/tests/unit/plugins/module_utils/test_database.py b/tests/unit/plugins/module_utils/test_database.py index 5ffd75945e..65ddfe2bc4 100644 --- a/tests/unit/plugins/module_utils/test_database.py +++ b/tests/unit/plugins/module_utils/test_database.py @@ -132,7 +132,7 @@ def test_how_many_dots(identifier, id_type, quoted_identifier, msg): assert pg_quote_identifier(identifier, id_type) == quoted_identifier with pytest.raises(SQLParseError) as ex: - pg_quote_identifier('%s.more' % identifier, id_type) + pg_quote_identifier(f'{identifier}.more', id_type) ex.match(msg) diff --git a/tests/unit/plugins/module_utils/test_ocapi_utils.py b/tests/unit/plugins/module_utils/test_ocapi_utils.py index 919af35f99..2d8d11c071 100644 --- a/tests/unit/plugins/module_utils/test_ocapi_utils.py +++ b/tests/unit/plugins/module_utils/test_ocapi_utils.py @@ -43,10 +43,10 @@ class TestOcapiUtils(unittest.TestCase): # Check the returned binary data boundary = m.group(1) - expected_content_text = '--%s\r\n' % boundary - expected_content_text += 'Content-Disposition: form-data; name="FirmwareFile"; filename="%s"\r\n' % filename + expected_content_text = f'--{boundary}\r\n' + expected_content_text += f'Content-Disposition: form-data; name="FirmwareFile"; filename="{filename}"\r\n' expected_content_text += 'Content-Type: application/octet-stream\r\n\r\n' expected_content_bytes = bytearray(expected_content_text, 'utf-8') expected_content_bytes += file_contents - expected_content_bytes += bytearray('\r\n--%s--' % boundary, 'utf-8') + expected_content_bytes += bytearray(f'\r\n--{boundary}--', 'utf-8') self.assertEqual(expected_content_bytes, b_form_data) diff --git a/tests/unit/plugins/module_utils/test_python_runner.py b/tests/unit/plugins/module_utils/test_python_runner.py index 760b3a42de..4c0bc109c4 100644 --- a/tests/unit/plugins/module_utils/test_python_runner.py +++ b/tests/unit/plugins/module_utils/test_python_runner.py @@ -162,11 +162,7 @@ def test_runner_context(runner_input, cmd_execution, expected): orig_results = tuple(cmd_execution[x] for x in ('rc', 'out', 'err')) - print("arg_spec={0}\nparams={1}\narg_formats={2}\n".format( - arg_spec, - params, - arg_formats, - )) + print(f"arg_spec={arg_spec}\nparams={params}\narg_formats={arg_formats}\n") module = MagicMock() type(module).argument_spec = PropertyMock(return_value=arg_spec) @@ -196,7 +192,7 @@ def test_runner_context(runner_input, cmd_execution, expected): def _assert_run_info_env_path(actual, expected): actual2 = set(actual.split(":")) - assert expected in actual2, "Missing expected path {0} in output PATH: {1}".format(expected, actual) + assert expected in actual2, f"Missing expected path {expected} in output PATH: {actual}" def _assert_run_info(actual, expected): reduced = {k: actual[k] for k in expected.keys()} @@ -204,7 +200,7 @@ def test_runner_context(runner_input, cmd_execution, expected): expected, exp_path = _extract_path(expected) if exp_path is not None: _assert_run_info_env_path(act_path, exp_path) - assert reduced == expected, "{0}".format(reduced) + assert reduced == expected, f"{reduced}" def _assert_run(expected, ctx, results): _assert_run_info(ctx.run_info, expected['run_info']) diff --git a/tests/unit/plugins/module_utils/test_vardict.py b/tests/unit/plugins/module_utils/test_vardict.py index 1a30d1117b..4d2ed2bb5f 100644 --- a/tests/unit/plugins/module_utils/test_vardict.py +++ b/tests/unit/plugins/module_utils/test_vardict.py @@ -50,7 +50,7 @@ def test_var_diff_scalar(): assert var.fact is False assert var.initial_value == 123 assert var.value == 456 - assert vd.diff() == {"before": {"aa": 123}, "after": {"aa": 456}}, "actual={0}".format(vd.diff()) + assert vd.diff() == {"before": {"aa": 123}, "after": {"aa": 456}}, f"actual={vd.diff()}" def test_var_diff_dict(): @@ -76,11 +76,11 @@ def test_var_diff_dict(): assert var.fact is False assert var.initial_value == val_before assert var.value == val_after - assert vd.diff() == {"before": {"dd": val_before}, "after": {"dd": val_after}}, "actual={0}".format(vd.diff()) + assert vd.diff() == {"before": {"dd": val_before}, "after": {"dd": val_after}}, f"actual={vd.diff()}" vd.set("aa", 123, diff=True) vd.aa = 456 - assert vd.diff() == {"before": {"aa": 123, "dd": val_before}, "after": {"aa": 456, "dd": val_after}}, "actual={0}".format(vd.diff()) + assert vd.diff() == {"before": {"aa": 123, "dd": val_before}, "after": {"aa": 456, "dd": val_after}}, f"actual={vd.diff()}" def test_vardict_set_meta(): diff --git a/tests/unit/plugins/module_utils/xenserver/common.py b/tests/unit/plugins/module_utils/xenserver/common.py index 75faba8cd7..1e9f8e51dd 100644 --- a/tests/unit/plugins/module_utils/xenserver/common.py +++ b/tests/unit/plugins/module_utils/xenserver/common.py @@ -7,7 +7,7 @@ from __future__ import annotations def fake_xenapi_ref(xenapi_class): - return "OpaqueRef:fake-xenapi-%s-ref" % xenapi_class + return f"OpaqueRef:fake-xenapi-{xenapi_class}-ref" testcase_bad_xenapi_refs = { diff --git a/tests/unit/plugins/module_utils/xenserver/test_set_vm_power_state.py b/tests/unit/plugins/module_utils/xenserver/test_set_vm_power_state.py index bc6e581ebf..af099e6478 100644 --- a/tests/unit/plugins/module_utils/xenserver/test_set_vm_power_state.py +++ b/tests/unit/plugins/module_utils/xenserver/test_set_vm_power_state.py @@ -198,7 +198,7 @@ def test_set_vm_power_state_xenapi_failure(mock_xenapi_failure, fake_ansible_mod with pytest.raises(FailJsonException) as exc_info: xenserver.set_vm_power_state(fake_ansible_module, fake_xenapi_ref('VM'), "poweredon") - assert exc_info.value.kwargs['msg'] == "XAPI ERROR: %s" % mock_xenapi_failure[1] + assert exc_info.value.kwargs['msg'] == f"XAPI ERROR: {mock_xenapi_failure[1]}" def test_set_vm_power_state_bad_power_state(mocker, fake_ansible_module, XenAPI, xenserver): @@ -350,7 +350,7 @@ def test_set_vm_power_state_transition_async(mocker, mocked_returns = { "VM.get_power_state.return_value": power_state_current, - "%s.return_value" % activated_xenapi_method: fake_xenapi_ref('task'), + f"{activated_xenapi_method}.return_value": fake_xenapi_ref('task'), } mocked_xenapi.configure_mock(**mocked_returns) diff --git a/tests/unit/plugins/module_utils/xenserver/test_wait_for_functions.py b/tests/unit/plugins/module_utils/xenserver/test_wait_for_functions.py index 2efc718469..6e117a27ce 100644 --- a/tests/unit/plugins/module_utils/xenserver/test_wait_for_functions.py +++ b/tests/unit/plugins/module_utils/xenserver/test_wait_for_functions.py @@ -70,7 +70,7 @@ def test_wait_for_vm_ip_address_xenapi_failure(mock_xenapi_failure, xenserver, f with pytest.raises(FailJsonException) as exc_info: xenserver.wait_for_vm_ip_address(fake_ansible_module, fake_xenapi_ref('VM')) - assert exc_info.value.kwargs['msg'] == "XAPI ERROR: %s" % mock_xenapi_failure[1] + assert exc_info.value.kwargs['msg'] == f"XAPI ERROR: {mock_xenapi_failure[1]}" @pytest.mark.parametrize('bad_power_state', @@ -89,8 +89,8 @@ def test_wait_for_vm_ip_address_bad_power_state(mocker, fake_ansible_module, Xen with pytest.raises(FailJsonException) as exc_info: xenserver.wait_for_vm_ip_address(fake_ansible_module, fake_xenapi_ref('VM')) - assert exc_info.value.kwargs['msg'] == ("Cannot wait for VM IP address when VM is in state '%s'!" % - xenserver.xapi_to_module_vm_power_state(bad_power_state.lower())) + assert exc_info.value.kwargs['msg'] == ( + f"Cannot wait for VM IP address when VM is in state '{xenserver.xapi_to_module_vm_power_state(bad_power_state.lower())}'!") @pytest.mark.parametrize('bad_guest_metrics_ref, bad_guest_metrics', @@ -170,7 +170,7 @@ def test_wait_for_task_xenapi_failure(mock_xenapi_failure, fake_ansible_module, with pytest.raises(FailJsonException) as exc_info: xenserver.wait_for_task(fake_ansible_module, fake_xenapi_ref('task')) - assert exc_info.value.kwargs['msg'] == "XAPI ERROR: %s" % mock_xenapi_failure[1] + assert exc_info.value.kwargs['msg'] == f"XAPI ERROR: {mock_xenapi_failure[1]}" def test_wait_for_task_timeout(mocker, fake_ansible_module, XenAPI, xenserver): diff --git a/tests/unit/plugins/module_utils/xenserver/test_xapi.py b/tests/unit/plugins/module_utils/xenserver/test_xapi.py index f1e9eb86ea..509d2fee91 100644 --- a/tests/unit/plugins/module_utils/xenserver/test_xapi.py +++ b/tests/unit/plugins/module_utils/xenserver/test_xapi.py @@ -111,7 +111,7 @@ def test_xapi_connect_login_failure(mocker, fake_ansible_module, XenAPI, xenserv with pytest.raises(FailJsonException) as exc_info: xapi_session = xenserver.XAPI.connect(fake_ansible_module) - assert exc_info.value.kwargs['msg'] == "Unable to log on to XenServer at http://%s as %s: %s" % (hostname, username, fake_error_msg) + assert exc_info.value.kwargs['msg'] == f"Unable to log on to XenServer at http://{hostname} as {username}: {fake_error_msg}" @pytest.mark.parametrize('fake_ansible_module', testcase_module_remote_conn_scheme['params'], ids=testcase_module_remote_conn_scheme['ids'], indirect=True) @@ -137,7 +137,7 @@ def test_xapi_connect_remote_no_scheme(mocker, fake_ansible_module, XenAPI, xens hostname = fake_ansible_module.params['hostname'] ignore_ssl = not fake_ansible_module.params['validate_certs'] - XenAPI.Session.assert_called_once_with("http://%s" % hostname, ignore_ssl=ignore_ssl) + XenAPI.Session.assert_called_once_with(f"http://{hostname}", ignore_ssl=ignore_ssl) def test_xapi_connect_support_ignore_ssl(mocker, fake_ansible_module, XenAPI, xenserver): @@ -151,7 +151,7 @@ def test_xapi_connect_support_ignore_ssl(mocker, fake_ansible_module, XenAPI, xe hostname = fake_ansible_module.params['hostname'] ignore_ssl = not fake_ansible_module.params['validate_certs'] - XenAPI.Session.assert_called_with("http://%s" % hostname) + XenAPI.Session.assert_called_with(f"http://{hostname}") def test_xapi_connect_no_disconnect_atexit(mocker, fake_ansible_module, XenAPI, xenserver): diff --git a/tests/unit/plugins/module_utils/xenserver/test_xenserverobject.py b/tests/unit/plugins/module_utils/xenserver/test_xenserverobject.py index 4027834372..a99dc591ac 100644 --- a/tests/unit/plugins/module_utils/xenserver/test_xenserverobject.py +++ b/tests/unit/plugins/module_utils/xenserver/test_xenserverobject.py @@ -27,7 +27,7 @@ def test_xenserverobject_xenapi_failure(mock_xenapi_failure, fake_ansible_module with pytest.raises(FailJsonException) as exc_info: xenserver.XenServerObject(fake_ansible_module) - assert exc_info.value.kwargs['msg'] == "XAPI ERROR: %s" % mock_xenapi_failure[1] + assert exc_info.value.kwargs['msg'] == f"XAPI ERROR: {mock_xenapi_failure[1]}" def test_xenserverobject(mocker, fake_ansible_module, XenAPI, xenserver):