1# Copyright (c) 2023 Nordic Semiconductor ASA
2#
3# SPDX-License-Identifier: Apache-2.0
4
5import pytest
6import textwrap
7
8from unittest import mock
9from twister_harness.helpers.mcumgr import MCUmgr, MCUmgrException
10
11
12@pytest.fixture(name='mcumgr')
13def fixture_mcumgr() -> MCUmgr:
14    return MCUmgr.create_for_serial('SERIAL_PORT')
15
16
17@mock.patch('twister_harness.helpers.mcumgr.MCUmgr.run_command', return_value='')
18def test_if_mcumgr_fixture_generate_proper_command(
19    patched_run_command: mock.Mock, mcumgr: MCUmgr
20) -> None:
21    mcumgr.reset_device()
22    patched_run_command.assert_called_with('reset')
23
24    mcumgr.get_image_list()
25    patched_run_command.assert_called_with('image list')
26
27    mcumgr.image_upload('/path/to/image', timeout=100)
28    patched_run_command.assert_called_with('-t 100 image upload /path/to/image')
29
30    mcumgr.image_test(hash='ABCD')
31    patched_run_command.assert_called_with('image test ABCD')
32
33    mcumgr.image_confirm(hash='ABCD')
34    patched_run_command.assert_called_with('image confirm ABCD')
35
36
37def test_if_mcumgr_fixture_raises_exception_when_no_hash_to_test(mcumgr: MCUmgr) -> None:
38    cmd_output = textwrap.dedent("""
39        Images:
40        image=0 slot=0
41            version: 0.0.0
42            bootable: true
43            flags: active confirmed
44            hash: 1234
45        Split status: N/A (0)
46    """)
47    mcumgr.run_command = mock.Mock(return_value=cmd_output)
48    with pytest.raises(MCUmgrException):
49        mcumgr.image_test()
50
51
52def test_if_mcumgr_fixture_parse_image_list(mcumgr: MCUmgr) -> None:
53    cmd_output = textwrap.dedent("""
54        Images:
55        image=0 slot=0
56            version: 0.0.0
57            bootable: true
58            flags:
59            hash: 0000
60        image=0 slot=1
61            version: 1.1.1
62            bootable: true
63            flags: pending
64            hash: 1111
65        Split status: N/A (0)
66    """)
67    mcumgr.run_command = mock.Mock(return_value=cmd_output)
68    image_list = mcumgr.get_image_list()
69    assert image_list[0].image == 0
70    assert image_list[0].slot == 0
71    assert image_list[0].version == '0.0.0'
72    assert image_list[0].flags == ''
73    assert image_list[0].hash == '0000'
74    assert image_list[1].image == 0
75    assert image_list[1].slot == 1
76    assert image_list[1].version == '1.1.1'
77    assert image_list[1].flags == 'pending'
78    assert image_list[1].hash == '1111'
79
80    # take second hash to test
81    mcumgr.image_test()
82    mcumgr.run_command.assert_called_with('image test 1111')
83
84    # take first hash to confirm
85    mcumgr.image_confirm()
86    mcumgr.run_command.assert_called_with('image confirm 0000')
87