1# Copyright (c) 2023 Nordic Semiconductor ASA
2#
3# SPDX-License-Identifier: Apache-2.0
4
5import textwrap
6from unittest import mock
7
8import pytest
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_upload('/path/to/image', slot=2, timeout=100)
31    patched_run_command.assert_called_with('-t 100 image upload /path/to/image -e -n 2')
32
33    mcumgr.image_test(hash='ABCD')
34    patched_run_command.assert_called_with('image test ABCD')
35
36    mcumgr.image_confirm(hash='ABCD')
37    patched_run_command.assert_called_with('image confirm ABCD')
38
39
40def test_if_mcumgr_fixture_raises_exception_when_no_hash_to_test(mcumgr: MCUmgr) -> None:
41    cmd_output = textwrap.dedent("""
42        Images:
43        image=0 slot=0
44            version: 0.0.0
45            bootable: true
46            flags: active confirmed
47            hash: 1234
48        Split status: N/A (0)
49    """)
50    mcumgr.run_command = mock.Mock(return_value=cmd_output)
51    with pytest.raises(MCUmgrException):
52        mcumgr.image_test()
53
54
55def test_if_mcumgr_fixture_parse_image_list(mcumgr: MCUmgr) -> None:
56    cmd_output = textwrap.dedent("""
57        Images:
58        image=0 slot=0
59            version: 0.0.0
60            bootable: true
61            flags: active confirmed
62            hash: 0000
63        image=0 slot=1
64            version: 1.1.1
65            bootable: true
66            flags:
67            hash: 1111
68        Split status: N/A (0)
69    """)
70    mcumgr.run_command = mock.Mock(return_value=cmd_output)
71    image_list = mcumgr.get_image_list()
72    assert image_list[0].image == 0
73    assert image_list[0].slot == 0
74    assert image_list[0].version == '0.0.0'
75    assert image_list[0].flags == 'active confirmed'
76    assert image_list[0].hash == '0000'
77    assert image_list[1].image == 0
78    assert image_list[1].slot == 1
79    assert image_list[1].version == '1.1.1'
80    assert image_list[1].flags == ''
81    assert image_list[1].hash == '1111'
82
83    # take second hash to test
84    mcumgr.image_test()
85    mcumgr.run_command.assert_called_with('image test 1111')
86
87    # take first hash to confirm
88    mcumgr.image_confirm()
89    mcumgr.run_command.assert_called_with('image confirm 1111')
90