Skip to content

Commit

Permalink
Merge pull request #234 from RIOT-OS/pr_fix_pylint
Browse files Browse the repository at this point in the history
treewide: use f-string where possible
  • Loading branch information
miri64 authored Sep 28, 2021
2 parents f404f94 + b84dbe8 commit 9287224
Show file tree
Hide file tree
Showing 17 changed files with 114 additions and 109 deletions.
12 changes: 5 additions & 7 deletions 03-single-hop-ipv6-icmp/test_spec03.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,20 +96,18 @@ def test_task04(riot_ctrl, log_nodes):
_, pinged_addr = lladdr(node.ifconfig_list())
assert pinged_addr.startswith("fe80::")
iface = bridge('tap0')
pinged_addr += "%{}".format(iface)
pinged_addr += f"%{iface}"
ping_cmd = get_ping_cmd()

futures = []
try:
for pinger in pingers:
if log_nodes:
pinger.child.logfile = sys.stdout
out = pinger.run_command("{ping_cmd} -f -s 1452 {pinged_addr}"
out = pinger.run_command(f"{ping_cmd} -f -s 1452 {pinged_addr}"
# pipe to /dev/null because output can go
# into MiB of data ;-)
" 2>&1 > /dev/null"
.format(ping_cmd=ping_cmd,
pinged_addr=pinged_addr),
" 2>&1 > /dev/null",
async_=True, timeout=60 * 60)
futures.append(out)
timeout_futures(futures, 60 * 60)
Expand All @@ -122,15 +120,15 @@ def test_task04(riot_ctrl, log_nodes):


@pytest.mark.xfail(reason="See https://github.com/RIOT-OS/RIOT/issues/12565")
@pytest.mark.skipif(not bridged(["tap{}".format(i)
@pytest.mark.skipif(not bridged([f"tap{i}"
for i in range(TASK05_NODES)]),
reason="tap0 to tap10 are not bridged")
@pytest.mark.parametrize('nodes',
[pytest.param(['native'] * TASK05_NODES)],
indirect=['nodes'])
def test_task05(nodes, riot_ctrl):
nodes = [
riot_ctrl(i, APP, Shell, port='tap{}'.format(i))
riot_ctrl(i, APP, Shell, port=f'tap{i}')
for i in range(len(nodes))
]

Expand Down
10 changes: 5 additions & 5 deletions 07-multi-hop/test_spec07.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,14 @@ def _init_rpl_dodag(nodes, nodes_netifs):
dodag_id = nodes_netifs[0]["lladdr"].replace("fe80::", "2001:db8::")
nodes[0].ifconfig_add(nodes_netifs[0]["netif"], dodag_id + "/64")
# TODO provide rpl ShellInteraction in `riotctrl_shell` upstream
res = nodes[0].cmd("rpl init {}".format(nodes_netifs[0]["netif"]))
res = nodes[0].cmd(f"rpl init {nodes_netifs[0]['netif']}")
if "success" not in res:
raise RuntimeError(res)
res = nodes[0].cmd("rpl root 0 {}".format(dodag_id))
res = nodes[0].cmd(f"rpl root 0 {dodag_id}")
if "success" not in res:
raise RuntimeError(res)
for i, node in enumerate(nodes[1:], 1):
res = node.cmd("rpl init {}".format(nodes_netifs[i]["netif"]))
res = node.cmd(f"rpl init {nodes_netifs[i]['netif']}")
if "success" not in res:
raise RuntimeError(res)
nodes_configured = [False]
Expand Down Expand Up @@ -205,10 +205,10 @@ def test_task05(rpl_nodes):
packet_loss = server.udp_server_check_output(count=100, delay_ms=100)
if packet_loss >= 10:
pytest.xfail(
"packet_loss {} >= 10. This is an experimental task, see also "
f"packet_loss {packet_loss} >= 10. This is an experimental "
"task, see also "
# pylint: disable=C0301
"https://github.com/RIOT-OS/Release-Specs/issues/142#issuecomment-561677974" # noqa: E501
.format(packet_loss)
)
assert packet_loss < 10
server.udp_server_stop()
Expand Down
16 changes: 8 additions & 8 deletions 08-interop/test_spec08.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ def test_task01(riot_ctrl, log_nodes):

if log_nodes:
linux.child.logfile = sys.stdout
out = linux.run_command("{ping_cmd} -c 20 -i .5 {node_addr}%{linux_iface}"
.format(ping_cmd=ping_cmd, node_addr=node_addr,
linux_iface=linux_iface), timeout=20)
out = linux.run_command(
f"{ping_cmd} -c 20 -i .5 {node_addr}%{linux_iface}", timeout=20
)
m = re.search(r"\b(\d+)% packet loss", out)
assert m is not None
assert int(m.group(1)) < 1
res = ping6(node, "{}%{}".format(linux_addr, node_iface),
res = ping6(node, f"{linux_addr}%{node_iface}",
count=20, interval=100, packet_size=8)
assert res["stats"]["packet_loss"] < 1

Expand All @@ -73,16 +73,16 @@ def test_task08(riot_ctrl):

gnrc_node.udp_server_start(61616)

lwip_node.cmd("udp send [{gnrc_addr}]:61616 012345678abcdef"
.format(gnrc_addr=gnrc_addr))
lwip_node.cmd(f"udp send [{gnrc_addr}]:61616 012345678abcdef")
packet_loss = gnrc_node.udp_server_check_output(count=1, delay_ms=0)
assert packet_loss == 0
gnrc_node.udp_server_stop()

lwip_node.cmd("udp server start 61617")
gnrc_node.udp_client_send(lwip_addr, 61617, "01234567")
lwip_node.riotctrl.term.expect_exact("Received UDP data from [{}]:61617"
.format(gnrc_addr))
lwip_node.riotctrl.term.expect_exact(
f"Received UDP data from [{gnrc_addr}]:61617"
)
lwip_node.riotctrl.term.expect_exact("00000000 " +
" ".join(hex(ord(c))[2:]
for c in "01234567"),
Expand Down
4 changes: 2 additions & 2 deletions 09-coap/task03.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ async def main(host, block_size):
b' he will meet with a success unexpected in common hours.')

request = Message(code=POST, payload=payload,
uri='coap://{0}/sha256'.format(host))
uri=f'coap://{host}/sha256')

block_exp = round(math.log(block_size, 2)) - 4
request.opt.block1 = optiontypes.BlockOption.BlockwiseTuple(0, 0, block_exp)

response = await context.request(request).response

print('Result: %s\n%r'%(response.code, response.payload))
print(f'Result: {response.code}\n{response.payload!r}')

if __name__ == "__main__":
# read command line
Expand Down
4 changes: 2 additions & 2 deletions 09-coap/task04.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,14 @@ async def main(host, block_size):
context = await Context.create_client_context()
await asyncio.sleep(2)

request = Message(code=GET, uri='coap://{0}/riot/ver'.format(host))
request = Message(code=GET, uri=f'coap://{host}/riot/ver')

block_exp = round(math.log(block_size, 2)) - 4
request.opt.block2 = optiontypes.BlockOption.BlockwiseTuple(0, 0, block_exp)

response = await context.request(request).response

print('Result: %s\n%r'%(response.code, response.payload))
print(f'Result: {response.code}\n{response.payload!r}')

if __name__ == "__main__":
# read command line
Expand Down
6 changes: 3 additions & 3 deletions 09-coap/task05.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,14 @@ async def main(host):

context = await Context.create_server_context(root)

msg = Message(code=GET, uri='coap://{0}/cli/stats'.format(host), observe=0)
msg = Message(code=GET, uri=f'coap://{host}/cli/stats', observe=0)
req = context.request(msg)

resp = await req.response
print("First response: %s\n%r"%(resp, resp.payload))
print(f"First response: {resp}\n{resp.payload!r}")

async for resp in req.observation:
print("Next result: %s\n%r"%(resp, resp.payload))
print(f"Next result: {resp}\n{resp.payload!r}")

req.observation.cancel()
break
Expand Down
32 changes: 16 additions & 16 deletions 09-coap/test_spec09.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ def coap_get(self, addr, port, resource, confirmable=False, timeout=-1,
cmd = "coap get "
if confirmable:
cmd += "-c "
cmd += "{} {:d} {}".format(addr, port, resource)
cmd += f"{addr} {port:d} {resource}"
return self.cmd(cmd, timeout=timeout, async_=async_)


# pylint: disable=R0903
class TimeResource(aiocoap.resource.Resource):
"""Handle GET for clock time."""
# pylint: disable=W0613
# pylint: disable=W0613, disable=R0201
async def render_get(self, request):
payload = datetime.datetime.now().\
strftime("%Y-%m-%d %H:%M").encode('ascii')
Expand All @@ -63,13 +63,13 @@ async def coap_server():
def setup_function(function):
if function.__name__ in ["test_task01", "test_task02", "test_task05"]:
host_netif = bridge(TAP)
ip_addr_add(host_netif, "{}/64".format(HOST_ULA))
ip_addr_add(host_netif, f"{HOST_ULA}/64")


def teardown_function(function):
if function.__name__ in ["test_task01", "test_task02", "test_task05"]:
host_netif = bridge(TAP)
ip_addr_del(host_netif, "{}/64".format(HOST_ULA))
ip_addr_del(host_netif, f"{HOST_ULA}/64")


# sudo required for function setup (address configuration of interface)
Expand All @@ -91,14 +91,14 @@ def test_task01(riot_ctrl, log_nodes):
stderr=None if log_nodes else subprocess.DEVNULL,
)
try:
res = node.cord_ep_register("[{}]".format(HOST_ULA))
res = node.cord_ep_register(f"[{HOST_ULA}]")
parser = CordEpRegistrationInfoParser()
core_reg = parser.parse(res)
if core_reg["ltime"] > 300:
pytest.xfail("CoRE RD lifetime is configured for {}s (> 5min). "
"That's way to long for a test!"
.format(core_reg["ltime"]))
time.sleep(core_reg["ltime"])
ltime = core_reg['ltime']
if ltime > 300:
pytest.xfail(f"CoRE RD lifetime is configured for {ltime}s "
"(> 5min). That's way to long for a test!")
time.sleep(ltime)
finally:
aiocoap_rd.terminate()
aiocoap_rd.wait()
Expand Down Expand Up @@ -164,7 +164,7 @@ async def client(host, block_size):

# pylint: disable=E1101
request = aiocoap.Message(code=aiocoap.POST, payload=payload,
uri='coap://{0}/sha256'.format(host))
uri=f'coap://{host}/sha256')

block_exp = round(math.log(block_size, 2)) - 4
# pylint: disable=E0237
Expand All @@ -177,7 +177,7 @@ async def client(host, block_size):
for block_size in range(16, 1024 + 1, 16):
print("Testing block size", block_size)
response = asyncio.get_event_loop().run_until_complete(
client("[{}%{}]".format(node_lladdr, host_netif), block_size)
client(f"[{node_lladdr}%{host_netif}]", block_size)
)
assert str(response.code) == "2.04 Changed"
# payload is a sha256 digest
Expand All @@ -204,7 +204,7 @@ async def client(host, block_size):

# pylint: disable=E1101
request = aiocoap.Message(code=aiocoap.GET,
uri='coap://{0}/riot/ver'.format(host))
uri=f'coap://{host}/riot/ver')

block_exp = round(math.log(block_size, 2)) - 4
# pylint: disable=E0237
Expand All @@ -217,7 +217,7 @@ async def client(host, block_size):
for block_size in range(16, 1024 + 1, 16):
print("Testing block size", block_size)
response = asyncio.get_event_loop().run_until_complete(
client("[{}%{}]".format(node_lladdr, host_netif), block_size)
client(f"[{node_lladdr}%{host_netif}]", block_size)
)
assert str(response.code) == "2.05 Content"
assert re.search(r"This is RIOT \(Version: .*\) running on a "
Expand All @@ -244,7 +244,7 @@ async def client_server(host):

# pylint: disable=E1101
msg = aiocoap.Message(code=aiocoap.GET,
uri='coap://{0}/cli/stats'.format(host),
uri=f'coap://{host}/cli/stats',
observe=0)
req = context.request(msg)

Expand All @@ -261,7 +261,7 @@ async def client_server(host):
break
await context.shutdown()

timeout_futures([client_server('[{}]'.format(NODE_ULA))], timeout=2)
timeout_futures([client_server(f'[{NODE_ULA}]')], timeout=2)
node.riotctrl.term.expect(r"gcoap: response Success, code 2.05, \d+ bytes")
assert len(responses) == 2
for i, response in enumerate(responses):
Expand Down
11 changes: 6 additions & 5 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,11 +266,11 @@ def nodes(local, request, boards, iotlab_site):
only_native = all(b.startswith("native") for b in boards)
for board in boards:
if local or only_native or IoTLABExperiment.valid_board(board):
env = {'BOARD': '{}'.format(board)}
env = {'BOARD': f'{board}'}
else:
env = {
'BOARD': IoTLABExperiment.board_from_iotlab_node(board),
'IOTLAB_NODE': '{}'.format(board)
'IOTLAB_NODE': f'{board}'
}
ctrls.append(RIOTCtrl(env=env))
if local or only_native:
Expand All @@ -279,6 +279,7 @@ def nodes(local, request, boards, iotlab_site):
name_fmt = get_namefmt(request)
# Start IoT-LAB experiment if requested
exp = IoTLABExperiment(
# pylint: disable=C0209
name="RIOT-release-test-{module}-{function}".format(**name_fmt),
ctrls=ctrls,
site=iotlab_site)
Expand All @@ -302,7 +303,7 @@ def update_env(node, modules=None, cflags=None, port=None, termflags=None):
# see: https://github.com/RIOT-OS/RIOT/issues/14504
node.env['DOCKER_ENVIRONMENT_CMDLINE'] = (
node.env.get('DOCKER_ENVIRONMENT_CMDLINE', '') +
" -e 'USEMODULE={}'".format(node.env['USEMODULE'])
f" -e 'USEMODULE={node.env['USEMODULE']}'"
)
if cflags is not None:
node.env['CFLAGS'] = cflags
Expand Down Expand Up @@ -336,8 +337,8 @@ def ctrl(nodes_idx, application_dir, shell_interaction_cls,
if node.env.get("IOTLAB_NODE"):
node_name = node.env["IOTLAB_NODE"]
else:
node_name = "{}-{}".format(
node.board(), re.sub(r'\W+', '-', node.env["PORT"]))
node_port = re.sub(r'\W+', '-', node.env["PORT"])
node_name = f"{node.board()}-{node_port}"
node.env["TERMLOG"] = os.path.join(
os.getcwd(), log_file_fmt.format(
node=node_name, time=int(time.time()),
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ disable=
duplicate-code,
fixme,
invalid-name,
logging-fstring-interpolation,
logging-format-interpolation,
missing-module-docstring,
missing-class-docstring,
Expand Down
2 changes: 1 addition & 1 deletion testutils/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def __init__(self, root='.', quiet=True):
self._quiet = quiet

def __repr__(self):
return "<{}: {}>".format(type(self).__name__, self._root)
return f"<{type(self).__name__}: {self._root}>"

@staticmethod
def _cmd(cmd, quiet=True):
Expand Down
Loading

0 comments on commit 9287224

Please sign in to comment.