1# Copyright (c) 2023 Nordic Semiconductor ASA
2#
3# SPDX-License-Identifier: Apache-2.0
4from __future__ import annotations
5
6import logging
7import re
8
9from pathlib import Path
10from twister_harness import Shell, MCUmgr
11from twister_harness.helpers.shell import ShellMCUbootCommandParsed
12
13
14logger = logging.getLogger(__name__)
15
16
17def find_in_config(config_file: Path | str, config_key: str) -> str:
18    re_key = re.compile(rf'{config_key}=(.+)')
19    with open(config_file) as f:
20        lines = f.readlines()
21    for line in lines:
22        if m := re_key.match(line):
23            logger.debug('Found matching key: %s' % line.strip())
24            return m.group(1).strip('"\'')
25    return ''
26
27
28def match_lines(output_lines: list[str], searched_lines: list[str]) -> None:
29    """Check all lines exist in the output"""
30    for sl in searched_lines:
31        assert any(sl in line for line in output_lines)
32
33
34def match_no_lines(output_lines: list[str], searched_lines: list[str]) -> None:
35    """Check lines not found in the output"""
36    for sl in searched_lines:
37        assert all(sl not in line for line in output_lines)
38
39
40def check_with_shell_command(shell: Shell, version: str, swap_type: str | None = None) -> None:
41    mcuboot_areas = ShellMCUbootCommandParsed.create_from_cmd_output(shell.exec_command('mcuboot'))
42    assert mcuboot_areas.areas[0].version == version
43    if swap_type:
44        assert mcuboot_areas.areas[0].swap_type == swap_type
45
46
47def check_with_mcumgr_command(mcumgr: MCUmgr, version: str) -> None:
48    image_list = mcumgr.get_image_list()
49    # version displayed by MCUmgr does not print +0 and changes + to '.' for non-zero values
50    assert image_list[0].version == version.replace('+0', '').replace('+', '.')
51