1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-04-05 03:37:01 +00:00

unit tests: use f-strings (#10993)

This commit is contained in:
Alexei Znamensky 2025-10-27 12:32:33 +13:00 committed by GitHub
parent e177d1e61a
commit efad7a0d38
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 54 additions and 78 deletions

View file

@ -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'])

View file

@ -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)

View file

@ -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)

View file

@ -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'])

View file

@ -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():

View file

@ -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 = {

View file

@ -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)

View file

@ -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):

View file

@ -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):

View file

@ -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):