Skip to content

Commit e19038d

Browse files
gchwierde-nordic
authored andcommitted
tests: boot: Fix formatting and other Ruff reported issues
Fixes up issues reported by Ruff Signed-off-by: Grzegorz Chwierut <[email protected]>
1 parent e684b50 commit e19038d

15 files changed

+204
-80
lines changed

tests/subsys/bootloader/upgrade/conftest.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@
1313
# Add the directory to PYTHONPATH
1414
zephyr_base = os.getenv("ZEPHYR_BASE")
1515
if zephyr_base:
16-
sys.path.insert(0, os.path.join(zephyr_base, "scripts", "pylib", "pytest-twister-harness", "src"))
16+
sys.path.insert(
17+
0, os.path.join(zephyr_base, "scripts", "pylib", "pytest-twister-harness", "src")
18+
)
1719
else:
18-
raise EnvironmentError("ZEPHYR_BASE environment variable is not set")
20+
raise OSError("ZEPHYR_BASE environment variable is not set")
1921

2022
pytest_plugins = [
2123
"twister_harness.plugin",
@@ -24,18 +26,21 @@
2426
USED_MARKERS = [
2527
# Test cycle:
2628
"commit: run on commit, every test without nightly or weekly marker get this marker",
27-
"nightly: use to skip tests in the on commit regression, tip: use -m 'nightly or commit' in regression",
28-
"weekly: for weekly run, tip: use -m 'weekly or nightly or commit' in regression to run all tests",
29+
"nightly: use to skip tests in the on commit regression, tip: use -m 'nightly or commit' "
30+
"in regression",
31+
"weekly: for weekly run, tip: use -m 'weekly or nightly or commit' in regression to run "
32+
"all tests",
2933
textwrap.dedent("""
3034
add_markers_if(condition, markers): decorate test with given markers
3135
if the condition evaluate to True.
3236
Example: add_markers_if('"nsib" in device_config.build_dir.name', [pytest.mark.nightly])
3337
"""),
3438
# filtering:
3539
textwrap.dedent("""
36-
skip_if(condition, reason=...): skip the given test function if the condition evaluate to True.
37-
'DeviceConfig' object is available as 'device_config' variable in the condition.
38-
Example: skip_if('"nrf54l" in device_config.platform', reason='Filtered out for nrf54l family')
40+
skip_if(condition, reason=...): skip the given test function if the condition evaluate to
41+
True. 'DeviceConfig' object is available as 'device_config' variable in the condition.
42+
Example: skip_if('"nrf54l" in device_config.platform',
43+
reason='Filtered out for nrf54l family')
3944
"""),
4045
]
4146

@@ -63,7 +68,9 @@ def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item
6368
item.add_marker(marker)
6469

6570
# Add default markers if not any of the used markers are present
66-
if not any(marker.name in ["commit", "nightly", "weekly"] for marker in item.iter_markers()):
71+
if not any(
72+
marker.name in ["commit", "nightly", "weekly"] for marker in item.iter_markers()
73+
):
6774
item.add_marker(pytest.mark.commit)
6875
item.add_marker(pytest.mark.nightly)
6976
item.add_marker(pytest.mark.weekly)

tests/subsys/bootloader/upgrade/pytest/check_lzma_compression.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,9 @@ def check_lzma_compression(
8585
ih_unlzma.loadbin(workdir / "stream")
8686

8787
if ih_unsigned.maxaddr() != ih_unlzma.maxaddr():
88-
raise CheckCompressionError("Decompressed data length is not identical as before compression")
88+
raise CheckCompressionError(
89+
"Decompressed data length is not identical as before compression"
90+
)
8991
if ih_unsigned.tobinarray() != ih_unlzma.tobinarray():
9092
raise CheckCompressionError("Decompressed data is not identical as before compression")
9193
logger.info("Decompressed data is identical as before compression")
@@ -114,7 +116,11 @@ def create_parser() -> argparse.ArgumentParser:
114116
help="Padding value for platforms that don't use partition manager (default: 0)",
115117
)
116118
parser.add_argument(
117-
"-ll", "--log-level", type=str.upper, default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
119+
"-ll",
120+
"--log-level",
121+
type=str.upper,
122+
default="INFO",
123+
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
118124
)
119125
return parser
120126

tests/subsys/bootloader/upgrade/pytest/helpers.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ def reset_board(dev_id: str | None = None, reset_kind: str | None = None):
8989
run_command(command)
9090

9191

92-
def nrfutil_write(address: str, value: str, dev_id: str | None = None, core: str | None = None) -> None:
92+
def nrfutil_write(
93+
address: str, value: str, dev_id: str | None = None, core: str | None = None
94+
) -> None:
9395
"""Write a value to a specific address on the device.
9496
9597
:param address: memory address to write to

tests/subsys/bootloader/upgrade/pytest/imgtool_wrapper.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,14 +90,16 @@ def imgtool_sign(
9090

9191
if not output_bin:
9292
output_bin = app_to_sign.parent / "{}_{}{}.bin".format(
93-
app_to_sign.stem, imgtool_params.version.replace(".", "_").replace("+", "_"), extend_output_name
93+
app_to_sign.stem,
94+
imgtool_params.version.replace(".", "_").replace("+", "_"),
95+
extend_output_name,
9496
)
9597

9698
command.extend([str(app_to_sign), str(output_bin)])
9799

98100
logger.info(f"CMD: {shlex.join(command)}")
99101
output = check_output(command, text=True, timeout=timeout)
100-
logger.debug("OUT: %s" % output)
102+
logger.debug(f"OUT: {output}")
101103
return output_bin
102104

103105

@@ -126,5 +128,5 @@ def imgtool_keygen(key_file: str | Path, key_type: str, imgtool: str | Path = "i
126128
command = [str(imgtool), "keygen", "--key", str(key_file), "--type", key_type]
127129
logger.info(f"CMD: {shlex.join(command)}")
128130
output = check_output(command, text=True)
129-
logger.debug("OUT: %s" % output)
131+
logger.debug(f"OUT: {output}")
130132
return Path(key_file)

tests/subsys/bootloader/upgrade/pytest/mcuboot_image_utils.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class ImageHeader:
3434
flags: int
3535

3636
@classmethod
37-
def from_bytes(cls, data: bytes) -> "ImageHeader":
37+
def from_bytes(cls, data: bytes) -> ImageHeader:
3838
"""Create an ImageHeader instance from bytes."""
3939
# 5 * 4 bytes (uint32_t) + 2 * 2 bytes (uint16_t)
4040
return cls(*struct.unpack("<I I H H I I", data))
@@ -78,7 +78,7 @@ def _parse_tlvs(self):
7878
tlv_off = self._parse_tlv_area(tlv_off, self.tlvs_protected)
7979
tlv_off = self._parse_tlv_area(tlv_off, self.tlvs)
8080

81-
def _parse_tlv_area(self, tlv_off: int, tlvs: list["TLV"]) -> int:
81+
def _parse_tlv_area(self, tlv_off: int, tlvs: list[TLV]) -> int:
8282
"""Parse a single TLV area and append TLVs to the list."""
8383
_, tlv_tot = struct.unpack("HH", self.ih.gets(tlv_off, TLV_INFO_SIZE)) # type: ignore
8484
tlv_end = tlv_off + tlv_tot
@@ -101,7 +101,9 @@ def copy_tlvs_areas(from_app: Path, to_app: Path, output_app: Path | None = None
101101
assert from_img.header == to_img.header, "Header of both images must be identical"
102102

103103
for tlv in from_img.tlvs_protected + from_img.tlvs:
104-
logger.debug(f"Copy protected TLV area of type 0x{tlv.tlv_type:x} at offset 0x{tlv.tlv_off:x}")
104+
logger.debug(
105+
f"Copy protected TLV area of type 0x{tlv.tlv_type:x} at offset 0x{tlv.tlv_off:x}"
106+
)
105107
to_img.ih.puts(tlv.tlv_off, tlv.tlv_data) # type: ignore
106108

107109
# Save modified image
@@ -110,7 +112,9 @@ def copy_tlvs_areas(from_app: Path, to_app: Path, output_app: Path | None = None
110112
return output_app
111113

112114

113-
def change_byte_in_tlv_area(image_file: Path, tlv_type: int, output_app: Path | None = None) -> Path:
115+
def change_byte_in_tlv_area(
116+
image_file: Path, tlv_type: int, output_app: Path | None = None
117+
) -> Path:
114118
"""Modify the TLV area for given type."""
115119
img = Image(image_file)
116120
img.parse()

tests/subsys/bootloader/upgrade/pytest/parameters.py

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def get_edt_node(edt_data: Path, node_label: str) -> devicetree.edtlib.EDTNode:
4040
except AttributeError as e:
4141
raise RuntimeError("Unexpected structure in loaded EDT data") from e
4242
except KeyError:
43-
raise KeyError(f"Node label '{node_label}' not found in EDT data")
43+
raise KeyError(f"Node label '{node_label}' not found in EDT data") from None
4444

4545

4646
@dataclass
@@ -62,7 +62,9 @@ class BuildParameters:
6262
mcuboot_secondary_app_to_sign: Path = field(init=False)
6363

6464
@classmethod
65-
def create_from_ncs_build_dir(cls, build_dir: Path, app_build_dir: Path | None = None) -> "BuildParameters":
65+
def create_from_ncs_build_dir(
66+
cls, build_dir: Path, app_build_dir: Path | None = None
67+
) -> BuildParameters:
6668
"""Create BuildParameters from NCS build directory and optional app build directory."""
6769
app_build_dir = app_build_dir or build_dir
6870
sysbuild = app_build_dir != build_dir
@@ -77,7 +79,8 @@ def create_from_ncs_build_dir(cls, build_dir: Path, app_build_dir: Path | None =
7779
header_size = find_in_config(pm_config, "PM_MCUBOOT_PAD_SIZE")
7880
slot_size = find_in_config(pm_config, "PM_MCUBOOT_PRIMARY_SIZE")
7981
else:
80-
# No PM used, thus take header size from app config and slot size from DTS (EDT represenation)
82+
# No PM used, thus take header size from app config and slot size from DTS
83+
# (EDT representation)
8184
header_size = find_in_config(zephyr_config, "CONFIG_ROM_START_OFFSET")
8285
slot_size = str(get_edt_node(edt_data, "cpuapp_slot0_partition").regs[0].size)
8386
imgtool_params = ImgtoolParams(
@@ -115,17 +118,23 @@ def _update_paths(self) -> None:
115118
sysbuild_config = self.build_dir / "zephyr" / ".config"
116119
self.net_core_name = find_in_config(sysbuild_config, "SB_CONFIG_NETCORE_IMAGE_NAME")
117120
self.netcore_to_sign = self.build_dir / f"signed_by_b0_{self.net_core_name}.bin"
118-
self.mcuboot_secondary_app_to_sign = self.build_dir / "mcuboot_secondary_app" / "zephyr" / "zephyr.bin"
121+
self.mcuboot_secondary_app_to_sign = (
122+
self.build_dir / "mcuboot_secondary_app" / "zephyr" / "zephyr.bin"
123+
)
119124
else:
120125
self.app_to_sign = self.build_dir / "zephyr" / "app_to_sign.bin"
121126
self.netcore_to_sign = self.build_dir / "zephyr" / "net_core_app_to_sign.bin"
122-
self.mcuboot_secondary_app_to_sign = self.build_dir / "zephyr" / "mcuboot_secondary_app_to_sign.bin"
127+
self.mcuboot_secondary_app_to_sign = (
128+
self.build_dir / "zephyr" / "mcuboot_secondary_app_to_sign.bin"
129+
)
123130

124131
def _update_imgtool(self) -> None:
125132
"""Update imgtool parameters based on build configuration."""
126133
self.imgtool_params.tool_path = str(self.mcuboot_dir / "scripts" / "imgtool.py")
127134
if self.sysbuild:
128-
self.imgtool_params.key_file = find_in_config(self.zephyr_config, "CONFIG_MCUBOOT_SIGNATURE_KEY_FILE") # type: ignore
135+
self.imgtool_params.key_file = find_in_config(
136+
self.zephyr_config, "CONFIG_MCUBOOT_SIGNATURE_KEY_FILE"
137+
) # type: ignore
129138
self.imgtool_params.encryption_key_file = (
130139
find_in_config(self.zephyr_config, "CONFIG_MCUBOOT_ENCRYPTION_KEY_FILE") or None # type: ignore
131140
)
@@ -138,11 +147,13 @@ def _update_imgtool(self) -> None:
138147
def update_params_for_netcore(self) -> None:
139148
"""Update imgtool parameters for netcore image slot size."""
140149
if not self.sysbuild:
141-
self.imgtool_params.slot_size = find_in_config(self.pm_config, "PM_MCUBOOT_SECONDARY_1_SIZE")
150+
self.imgtool_params.slot_size = find_in_config(
151+
self.pm_config, "PM_MCUBOOT_SECONDARY_1_SIZE"
152+
)
142153
else:
143154
cpunet_pm_config = self.build_dir / "pm_CPUNET.config"
144155
self.imgtool_params.slot_size = find_in_config(
145-
cpunet_pm_config, "PM_{}_SIZE".format(self.net_core_name.upper())
156+
cpunet_pm_config, f"PM_{self.net_core_name.upper()}_SIZE"
146157
)
147158

148159
def _update_imgtool_next(self) -> None:
@@ -155,7 +166,7 @@ def _update_imgtool_next(self) -> None:
155166
self.imgtool_params.pure = True
156167
elif find_in_config(sysbuild_config, "SB_CONFIG_BOOT_IMG_HASH_ALG_SHA512"):
157168
self.imgtool_params.sha = 512
158-
if find_in_config(sysbuild_config, "SB_CONFIG_BOOT_SIGNATURE_TYPE_ED25519") and find_in_config(
159-
sysbuild_config, "SB_CONFIG_SOC_SERIES_NRF54LX"
160-
):
169+
if find_in_config(
170+
sysbuild_config, "SB_CONFIG_BOOT_SIGNATURE_TYPE_ED25519"
171+
) and find_in_config(sysbuild_config, "SB_CONFIG_SOC_SERIES_NRF54LX"):
161172
self.imgtool_params.hmac_sha = 512

tests/subsys/bootloader/upgrade/pytest/required_build.py

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ def create_from_dut(
5555
if not source_dir:
5656
source_dir = find_in_config(
5757
dut.device_config.build_dir / "CMakeCache.txt", "APP_DIR:PATH"
58-
) or find_in_config(dut.device_config.build_dir / "CMakeCache.txt", "APPLICATION_SOURCE_DIR:PATH")
58+
) or find_in_config(
59+
dut.device_config.build_dir / "CMakeCache.txt", "APPLICATION_SOURCE_DIR:PATH"
60+
)
5961
testsuite = testsuite or dut.device_config.build_dir.name
6062
if not source_dir:
6163
raise RequiredBuildException("Not found source dir")
@@ -69,7 +71,9 @@ def create_from_dut(
6971
build_dir = str(build_dir) + suffix
7072
build_dir = Path(build_dir) # type: ignore
7173
if build_dir == dut.device_config.build_dir:
72-
raise RequiredBuildException("Build dir is the same as the current build dir, use suffix")
74+
raise RequiredBuildException(
75+
"Build dir is the same as the current build dir, use suffix"
76+
)
7377
board = (
7478
board
7579
or dut.device_config.platform
@@ -91,7 +95,16 @@ def create_from_dut(
9195
@timer
9296
def west_build(self):
9397
"""Run west build for the required build configuration."""
94-
command = ["west", "build", "-p", "-b", self.board, str(self.source_dir), "-d", str(self.build_dir)]
98+
command = [
99+
"west",
100+
"build",
101+
"-p",
102+
"-b",
103+
self.board,
104+
str(self.source_dir),
105+
"-d",
106+
str(self.build_dir),
107+
]
95108
if self.testsuite:
96109
command.extend(["-T", self.testsuite])
97110
if self.extra_args:
@@ -103,11 +116,11 @@ def west_build(self):
103116
# create empty file to indicate a build error, will be used
104117
# to avoid unnecessary builds in other tests
105118
Path(self.build_dir / "build.error").touch()
106-
raise RequiredBuildException("Failed to build required app")
119+
raise RequiredBuildException("Failed to build required app") from None
107120
except subprocess.TimeoutExpired:
108121
logger.error("Timeout building required app")
109122
shutil.rmtree(self.build_dir)
110-
raise RequiredBuildException("Timeout building required app")
123+
raise RequiredBuildException("Timeout building required app") from None
111124

112125
def get_ready_build(self):
113126
"""Get or create a ready build directory, using file locking to avoid conflicts."""
@@ -133,7 +146,7 @@ def get_ready_build(self):
133146
with FileLock(str(lockfile), timeout=self.timeout):
134147
pass
135148
except Timeout:
136-
raise RequiredBuildException(f"Timeout waiting for {self.build_dir}")
149+
raise RequiredBuildException(f"Timeout waiting for {self.build_dir}") from None
137150

138151
if not self.is_build_ready():
139152
raise RequiredBuildException(f"Build is not ready: {self.build_dir}")
@@ -210,7 +223,9 @@ def get_required_images_to_update(
210223
)
211224
req_build_dir = req_build.get_ready_build()
212225

213-
updated_app = req_build_dir / req_build.build_info.default_domain / "zephyr" / "zephyr.signed.bin" # type: ignore
226+
updated_app = (
227+
req_build_dir / req_build.build_info.default_domain / "zephyr" / "zephyr.signed.bin"
228+
) # type: ignore
214229
updated_netcore = req_build_dir / f"signed_by_mcuboot_and_b0_{netcore_name}.bin"
215230
s1_image = req_build_dir / "signed_by_mcuboot_and_b0_s1_image.bin"
216231
return updated_app, updated_netcore, s1_image

tests/subsys/bootloader/upgrade/pytest/test_direct_xip.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from pathlib import Path
1111

1212
import pytest
13-
1413
from required_build import RequiredBuild
1514
from twister_harness import DeviceAdapter, MCUmgr, Shell
1615
from twister_harness.helpers.utils import find_in_config
@@ -84,21 +83,27 @@ class UpgradeTestDirectXipUseMCUmgrNRF54H(UpgradeTestDirectXipUseMCUmgr):
8483
def generate_image_for_direct_xip_secondary_slot(self) -> Path:
8584
"""Generate image for direct XIP secondary slot."""
8685
logger.info("Generate image for direct xip secondary slot")
87-
req_build_dir = get_required_build_for_direct_xip_nRF54H(self.dut, self.get_current_sign_version())
86+
req_build_dir = get_required_build_for_direct_xip_nRF54H(
87+
self.dut, self.get_current_sign_version()
88+
)
8889
secondary_image = req_build_dir / "zephyr_secondary_app.signed.bin"
8990
assert secondary_image.is_file(), f"Secondary image not found: {secondary_image}"
9091
return secondary_image
9192

9293
def generate_image_for_direct_xip_primary_slot(self) -> Path:
9394
"""Generate image for direct XIP primary slot."""
9495
logger.info("Generate image for direct xip primary slot")
95-
req_build_dir = get_required_build_for_direct_xip_nRF54H(self.dut, self.get_current_sign_version())
96+
req_build_dir = get_required_build_for_direct_xip_nRF54H(
97+
self.dut, self.get_current_sign_version()
98+
)
9699
primary_image = req_build_dir / "zephyr.signed.bin"
97100
assert primary_image.is_file(), f"Primary image not found: {primary_image}"
98101
return primary_image
99102

100103

101-
def factory_upgrade_test_direct_xip(dut: DeviceAdapter, shell: Shell, mcumgr: MCUmgr) -> UpgradeTestDirectXipUseMCUmgr:
104+
def factory_upgrade_test_direct_xip(
105+
dut: DeviceAdapter, shell: Shell, mcumgr: MCUmgr
106+
) -> UpgradeTestDirectXipUseMCUmgr:
102107
"""Create an instance of UpgradeTestDirectXipUseMCUmgr."""
103108
if "nrf54h" in dut.device_config.platform:
104109
return UpgradeTestDirectXipUseMCUmgrNRF54H(dut, shell, mcumgr)
@@ -108,7 +113,9 @@ def factory_upgrade_test_direct_xip(dut: DeviceAdapter, shell: Shell, mcumgr: MC
108113
class TestDirectXipWithRevert:
109114
"""Test Direct XIP upgrade and revert scenarios."""
110115

111-
def test_direct_xip_upgrade_with_confirm(self, dut: DeviceAdapter, shell: Shell, mcumgr: MCUmgr):
116+
def test_direct_xip_upgrade_with_confirm(
117+
self, dut: DeviceAdapter, shell: Shell, mcumgr: MCUmgr
118+
):
112119
"""Verify that the application can be updated and confirmed.
113120
114121
APP based on smp_svr, MCUboot is the primary bootloader.
@@ -176,7 +183,9 @@ def test_direct_xip_upgrade_multiple(self, dut: DeviceAdapter, shell: Shell, mcu
176183
tm.run_upgrade(third_app, confirm=True)
177184
tm.verify_direct_xip_primary_slot_loaded()
178185

179-
def test_direct_xip_downgrade_prevention(self, dut: DeviceAdapter, shell: Shell, mcumgr: MCUmgr):
186+
def test_direct_xip_downgrade_prevention(
187+
self, dut: DeviceAdapter, shell: Shell, mcumgr: MCUmgr
188+
):
180189
"""Verify that the application is not downgraded.
181190
182191
APP based on smp_svr, MCUboot is the primary bootloader.
@@ -197,8 +206,11 @@ def test_direct_xip_downgrade_prevention(self, dut: DeviceAdapter, shell: Shell,
197206
class TestDirectXip:
198207
"""Test Direct XIP upgrade and downgrade prevention without revert mode."""
199208

200-
def test_direct_xip_no_revert_and_downgrade_prev(self, dut: DeviceAdapter, shell: Shell, mcumgr: MCUmgr):
201-
"""Verify that the application can be updated from both slots and not downgraded with lower version.
209+
def test_direct_xip_no_revert_and_downgrade_prev(
210+
self, dut: DeviceAdapter, shell: Shell, mcumgr: MCUmgr
211+
):
212+
"""Verify that the application can be updated from both slots and not downgraded with lower
213+
version.
202214
203215
APP based on smp_svr, MCUboot is the primary bootloader.
204216
Direct XIP mode is enabled.
@@ -235,7 +247,12 @@ def test_direct_xip_no_revert_and_downgrade_prev(self, dut: DeviceAdapter, shell
235247
if "nrf54h" in dut.device_config.platform:
236248
tm.image_upload(dut.device_config.build_dir / "zephyr_secondary_app.signed.bin")
237249
else:
238-
tm.image_upload(dut.device_config.build_dir / "mcuboot_secondary_app" / "zephyr" / "zephyr.signed.bin")
250+
tm.image_upload(
251+
dut.device_config.build_dir
252+
/ "mcuboot_secondary_app"
253+
/ "zephyr"
254+
/ "zephyr.signed.bin"
255+
)
239256
tm.reset_device_from_shell()
240257
tm.verify_direct_xip_primary_slot_loaded()
241258
logger.info("Not downgraded from secondary slot")

0 commit comments

Comments
 (0)