Skip to content

Commit e37c8c9

Browse files
committed
Use f-string instead of str.format()
1 parent 9a7df23 commit e37c8c9

30 files changed

+117
-135
lines changed

doc/source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161

6262
# General information about the project.
6363
project = "testinfra"
64-
copyright = "{}, Philippe Pepiot".format(datetime.date.today().year)
64+
copyright = f"{datetime.date.today().year}, Philippe Pepiot"
6565

6666
# The version info for the project you're documenting, acts as replacement for
6767
# |version| and |release|, also used in various other places throughout the

test/conftest.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -62,29 +62,29 @@ def has_docker():
6262
def setup_ansible_config(tmpdir, name, host, user, port, key):
6363
items = [
6464
name,
65-
"ansible_ssh_private_key_file={}".format(key),
66-
'ansible_ssh_common_args="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=FATAL"', # noqa
65+
f"ansible_ssh_private_key_file={key}",
66+
'ansible_ssh_common_args="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=FATAL"',
6767
"myvar=foo",
68-
"ansible_host={}".format(host),
69-
"ansible_user={}".format(user),
70-
"ansible_port={}".format(port),
68+
f"ansible_host={host}",
69+
f"ansible_user={user}",
70+
f"ansible_port={port}",
7171
]
7272
tmpdir.join("inventory").write("[testgroup]\n" + " ".join(items) + "\n")
7373
tmpdir.mkdir("host_vars").join(name).write(ANSIBLE_HOSTVARS)
7474
tmpdir.mkdir("group_vars").join("testgroup").write(
75-
("---\n" "myhostvar: should_be_overriden\n" "mygroupvar: qux\n")
75+
"---\n" "myhostvar: should_be_overriden\n" "mygroupvar: qux\n"
7676
)
7777
vault_password_file = tmpdir.join("vault-pass.txt")
7878
vault_password_file.write("polichinelle\n")
7979
ansible_cfg = tmpdir.join("ansible.cfg")
8080
ansible_cfg.write(
81-
(
81+
8282
"[defaults]\n"
83-
"vault_password_file={}\n"
83+
f"vault_password_file={str(vault_password_file)}\n"
8484
"host_key_checking=False\n\n"
8585
"[ssh_connection]\n"
8686
"pipelining=True\n"
87-
).format(str(vault_password_file))
87+
8888
)
8989

9090

@@ -119,7 +119,7 @@ def teardown():
119119

120120
return docker_id, docker_host, port
121121

122-
fname = "_docker_container_{}_{}".format(image, scope)
122+
fname = f"_docker_container_{image}_{scope}"
123123
mod = sys.modules[__name__]
124124
setattr(mod, fname, func)
125125

@@ -147,7 +147,7 @@ def host(request, tmpdir_factory):
147147
else:
148148
scope = "session"
149149

150-
fname = "_docker_container_{}_{}".format(spec.name, scope)
150+
fname = f"_docker_container_{spec.name}_{scope}"
151151
docker_id, docker_host, port = request.getfixturevalue(fname)
152152

153153
if kw["connection"] == "docker":
@@ -168,16 +168,16 @@ def host(request, tmpdir_factory):
168168
else:
169169
ssh_config = tmpdir.join("ssh_config")
170170
ssh_config.write(
171-
(
172-
"Host {}\n"
173-
" Hostname {}\n"
174-
" Port {}\n"
171+
172+
f"Host {hostname}\n"
173+
f" Hostname {docker_host}\n"
174+
f" Port {port}\n"
175175
" UserKnownHostsFile /dev/null\n"
176176
" StrictHostKeyChecking no\n"
177-
" IdentityFile {}\n"
177+
f" IdentityFile {str(key)}\n"
178178
" IdentitiesOnly yes\n"
179179
" LogLevel FATAL\n"
180-
).format(hostname, docker_host, port, str(key))
180+
181181
)
182182
kw["ssh_config"] = str(ssh_config)
183183

@@ -232,7 +232,7 @@ def build_image(build_failed, dockerfile, image, image_path):
232232
"-f",
233233
dockerfile,
234234
"-t",
235-
"testinfra:{0}".format(image),
235+
f"testinfra:{image}",
236236
image_path,
237237
]
238238
)

test/test_backends.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def test_sudo(host):
125125
def test_ansible_get_hosts():
126126
with tempfile.NamedTemporaryFile() as f:
127127
f.write(
128-
(
128+
129129
b"ungrp\n"
130130
b"[g1]\n"
131131
b"debian\n"
@@ -136,7 +136,7 @@ def test_ansible_get_hosts():
136136
b"g2\n"
137137
b"[g4:children]\n"
138138
b"g3"
139-
)
139+
140140
)
141141
f.flush()
142142

@@ -158,7 +158,7 @@ def get_hosts(spec):
158158
def test_ansible_get_variables():
159159
with tempfile.NamedTemporaryFile() as f:
160160
f.write(
161-
(
161+
162162
b"debian a=b c=d\n"
163163
b"rockylinux e=f\n"
164164
b"[all:vars]\n"
@@ -167,7 +167,7 @@ def test_ansible_get_variables():
167167
b"debian\n"
168168
b"[g:vars]\n"
169169
b"x=z\n"
170-
)
170+
171171
)
172172
f.flush()
173173

@@ -202,7 +202,7 @@ def get_vars(host):
202202
(
203203
{},
204204
b"host ansible_connection=local ansible_become=yes ansible_become_user=u",
205-
{ # noqa
205+
{
206206
"NAME": "local",
207207
"sudo": True,
208208
"sudo_user": "u",
@@ -227,7 +227,7 @@ def get_vars(host):
227227
(
228228
{},
229229
b"host ansible_host=127.0.1.1 ansible_user=u ansible_ssh_private_key_file=key ansible_port=2222 ansible_become=yes ansible_become_user=u",
230-
{ # noqa
230+
{
231231
"NAME": "ssh",
232232
"sudo": True,
233233
"sudo_user": "u",
@@ -239,7 +239,7 @@ def get_vars(host):
239239
(
240240
{},
241241
b"host ansible_host=127.0.1.1 ansible_user=u ansible_private_key_file=key ansible_port=2222 ansible_become=yes ansible_become_user=u",
242-
{ # noqa
242+
{
243243
"NAME": "ssh",
244244
"sudo": True,
245245
"sudo_user": "u",
@@ -269,7 +269,7 @@ def get_vars(host):
269269
(
270270
{},
271271
b'host ansible_ssh_common_args="-o StrictHostKeyChecking=no" ansible_ssh_extra_args="-o LogLevel=FATAL"',
272-
{ # noqa
272+
{
273273
"NAME": "ssh",
274274
"host.name": "host",
275275
"ssh_extra_args": "-o StrictHostKeyChecking=no -o LogLevel=FATAL",
@@ -296,7 +296,7 @@ def get_vars(host):
296296
(
297297
{},
298298
b"host ansible_connection=docker ansible_become=yes ansible_become_user=u ansible_user=z ansible_host=container",
299-
{ # noqa
299+
{
300300
"NAME": "docker",
301301
"name": "container",
302302
"user": "z",
@@ -347,7 +347,7 @@ def test_ansible_get_host(kwargs, inventory, expected):
347347
# identity_file has highest priority
348348
(
349349
b"host ansible_user=user ansible_ssh_pass=password ansible_ssh_private_key_file=some_file",
350-
( # noqa
350+
(
351351
"ssh -o User=user -i some_file "
352352
"-o ConnectTimeout=10 -o ControlMaster=auto "
353353
"-o ControlPersist=60s host true"
@@ -373,7 +373,7 @@ def test_ansible_get_host(kwargs, inventory, expected):
373373
# escape %
374374
(
375375
b'host ansible_ssh_extra_args="-o ControlPath ~/.ssh/ansible/cp/%r@%h-%p"',
376-
( # noqa
376+
(
377377
"ssh -o ControlPath ~/.ssh/ansible/cp/%r@%h-%p -o ConnectTimeout=10 "
378378
"-o ControlMaster=auto -o ControlPersist=60s host true"
379379
),
@@ -419,7 +419,7 @@ def test_ansible_config():
419419
# test testinfra use ANSIBLE_CONFIG
420420
tmp = tempfile.NamedTemporaryFile
421421
with tmp(suffix=".cfg") as cfg, tmp() as inventory:
422-
cfg.write((b"[defaults]\n" b"inventory=" + inventory.name.encode() + b"\n"))
422+
cfg.write(b"[defaults]\n" b"inventory=" + inventory.name.encode() + b"\n")
423423
cfg.flush()
424424
inventory.write(b"h\n")
425425
inventory.flush()

test/test_modules.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525

2626
all_images = pytest.mark.testinfra_hosts(
2727
*[
28-
"docker://{}".format(image)
28+
f"docker://{image}"
2929
for image in (
3030
"rockylinux9",
3131
"debian_bookworm",

testinfra/backend/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
import importlib
1414
import os
1515
import urllib.parse
16-
from typing import TYPE_CHECKING, Any, Iterable
16+
from collections.abc import Iterable
17+
from typing import TYPE_CHECKING, Any
1718

1819
if TYPE_CHECKING:
1920
import testinfra.backend.base
@@ -39,7 +40,7 @@ def get_backend_class(connection: str) -> type["testinfra.backend.base.BaseBacke
3940
try:
4041
classpath = BACKENDS[connection]
4142
except KeyError:
42-
raise RuntimeError("Unknown connection type '{}'".format(connection))
43+
raise RuntimeError(f"Unknown connection type '{connection}'")
4344
module, name = classpath.rsplit(".", 1)
4445
return getattr(importlib.import_module(module), name) # type: ignore[no-any-return]
4546

testinfra/backend/base.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def __init__(
146146
**kwargs: Any,
147147
):
148148
self._encoding: Optional[str] = None
149-
self._host: Optional["testinfra.host.Host"] = None
149+
self._host: Optional[testinfra.host.Host] = None
150150
self.hostname = hostname
151151
self.sudo = sudo
152152
self.sudo_user = sudo_user
@@ -197,16 +197,14 @@ def get_pytest_id(self) -> str:
197197
def get_hosts(cls, host: str, **kwargs: Any) -> list[str]:
198198
if host is None:
199199
raise RuntimeError(
200-
"One or more hosts is required with the {} backend".format(
201-
cls.get_connection_type()
202-
)
200+
f"One or more hosts is required with the {cls.get_connection_type()} backend"
203201
)
204202
return [host]
205203

206204
@staticmethod
207205
def quote(command: str, *args: str) -> str:
208206
if args:
209-
return command % tuple(shlex.quote(a) for a in args) # noqa: S001
207+
return command % tuple(shlex.quote(a) for a in args)
210208
return command
211209

212210
def get_sudo_command(self, command: str, sudo_user: Optional[str]) -> str:

testinfra/backend/chroot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def __init__(self, name: str, *args: Any, **kwargs: Any):
3131
def run(self, command: str, *args: str, **kwargs: Any) -> base.CommandResult:
3232
if not os.path.exists(self.name) and os.path.isdir(self.name):
3333
raise RuntimeError(
34-
"chroot path {} not found or not a directory".format(self.name)
34+
f"chroot path {self.name} not found or not a directory"
3535
)
3636
cmd = self.get_command(command, *args)
3737
out = self.run_local("chroot %s /bin/sh -c %s", self.name, cmd)

testinfra/backend/paramiko.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@
1616
import paramiko
1717
except ImportError:
1818
raise RuntimeError(
19-
(
19+
2020
"You must install paramiko package (pip install paramiko) "
2121
"to use the paramiko backend"
22-
)
22+
2323
)
2424

2525
import functools
@@ -121,7 +121,7 @@ def client(self) -> paramiko.SSHClient:
121121
with open(default_ssh_config) as f:
122122
ssh_config = paramiko.SSHConfig()
123123
ssh_config.parse(f)
124-
except IOError:
124+
except OSError:
125125
pass
126126
else:
127127
self._load_ssh_config(client, cfg, ssh_config, ssh_config_dir)

testinfra/backend/salt.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ def run_salt(self, func: str, args: Any = None) -> Any:
4949
out = self.client.cmd(self.host, func, args or [])
5050
if self.host not in out:
5151
raise RuntimeError(
52-
"Error while running {}({}): {}. "
53-
"Minion not connected ?".format(func, args, out)
52+
f"Error while running {func}({args}): {out}. "
53+
"Minion not connected ?"
5454
)
5555
return out[self.host]
5656

@@ -65,6 +65,6 @@ def get_hosts(cls, host: str, **kwargs: Any) -> list[str]:
6565
else:
6666
hosts = client.cmd(host, "test.true").keys()
6767
if not hosts:
68-
raise RuntimeError("No host matching '{}'".format(host))
68+
raise RuntimeError(f"No host matching '{host}'")
6969
return sorted(hosts)
7070
return super().get_hosts(host, **kwargs)

testinfra/backend/ssh.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -68,21 +68,19 @@ def _build_ssh_command(self, command: str) -> tuple[list[str], list[str]]:
6868
cmd.append("-i %s")
6969
cmd_args.append(self.ssh_identity_file)
7070
if "connecttimeout" not in (self.ssh_extra_args or "").lower():
71-
cmd.append("-o ConnectTimeout={}".format(self.timeout))
71+
cmd.append(f"-o ConnectTimeout={self.timeout}")
7272
if self.controlpersist and (
7373
"controlmaster" not in (self.ssh_extra_args or "").lower()
7474
):
7575
cmd.append(
76-
"-o ControlMaster=auto -o ControlPersist={}s".format(
77-
self.controlpersist
78-
)
76+
f"-o ControlMaster=auto -o ControlPersist={self.controlpersist}s"
7977
)
8078
if (
8179
"ControlMaster" in " ".join(cmd)
8280
and self.controlpath
8381
and ("controlpath" not in (self.ssh_extra_args or "").lower())
8482
):
85-
cmd.append("-o ControlPath={}".format(self.controlpath))
83+
cmd.append(f"-o ControlPath={self.controlpath}")
8684
cmd.append("%s %s")
8785
cmd_args.extend([self.host.name, command])
8886
return cmd, cmd_args
@@ -120,11 +118,11 @@ def run(self, command: str, *args: str, **kwargs: Any) -> base.CommandResult:
120118
orig_command = self.get_command("sh -c %s", orig_command)
121119

122120
out = self.run_ssh(
123-
(
124-
"""of=$(mktemp)&&ef=$(mktemp)&&{} >$of 2>$ef; r=$?;"""
121+
122+
f"""of=$(mktemp)&&ef=$(mktemp)&&{orig_command} >$of 2>$ef; r=$?;"""
125123
"""echo "TESTINFRA_START;$r;$(base64 < $of);$(base64 < $ef);"""
126124
"""TESTINFRA_END";rm -f $of $ef"""
127-
).format(orig_command)
125+
128126
)
129127

130128
start = out.stdout.find("TESTINFRA_START;") + len("TESTINFRA_START;")

0 commit comments

Comments
 (0)