1# Copyright (c) 2021 Gerson Fernando Budke <nandojve@gmail.com>
2# SPDX-License-Identifier: Apache-2.0
3
4import argparse
5import os
6import platform
7from unittest.mock import patch, call
8
9import pytest
10
11from runners.gd32isp import Gd32ispBinaryRunner
12from conftest import RC_KERNEL_BIN
13
14if platform.system() != 'Linux':
15    pytest.skip("skipping Linux-only gd32isp tests", allow_module_level=True)
16
17TEST_GD32ISP_CLI   = 'GD32_ISP_Console'
18TEST_GD32ISP_CLI_T = 'GD32_ISP_CLI'
19TEST_GD32ISP_DEV   = 'test-gd32test'
20TEST_GD32ISP_PORT  = 'test-gd32isp-serial'
21TEST_GD32ISP_SPEED = '2000000'
22TEST_GD32ISP_ADDR  = '0x08765430'
23
24EXPECTED_COMMANDS_DEFAULT = [
25    [TEST_GD32ISP_CLI, '-c', '--pn', '/dev/ttyUSB0', '--br', '57600',
26     '--sb', '1', '-i', TEST_GD32ISP_DEV, '-e', '--all', '-d',
27     '--a', '0x08000000', '--fn', RC_KERNEL_BIN],
28]
29
30EXPECTED_COMMANDS = [
31    [TEST_GD32ISP_CLI_T, '-c', '--pn', TEST_GD32ISP_PORT,
32     '--br', TEST_GD32ISP_SPEED,
33     '--sb', '1', '-i', TEST_GD32ISP_DEV, '-e', '--all', '-d',
34     '--a', TEST_GD32ISP_ADDR, '--fn', RC_KERNEL_BIN],
35]
36
37def require_patch(program):
38    assert program in [TEST_GD32ISP_CLI, TEST_GD32ISP_CLI_T]
39
40os_path_isfile = os.path.isfile
41
42def os_path_isfile_patch(filename):
43    if filename == RC_KERNEL_BIN:
44        return True
45    return os_path_isfile(filename)
46
47
48@patch('runners.core.ZephyrBinaryRunner.require', side_effect=require_patch)
49@patch('runners.core.ZephyrBinaryRunner.check_call')
50def test_gd32isp_init(cc, req, runner_config):
51    runner = Gd32ispBinaryRunner(runner_config, TEST_GD32ISP_DEV)
52    with patch('os.path.isfile', side_effect=os_path_isfile_patch):
53        runner.run('flash')
54    assert cc.call_args_list == [call(x) for x in EXPECTED_COMMANDS_DEFAULT]
55
56
57@patch('runners.core.ZephyrBinaryRunner.require', side_effect=require_patch)
58@patch('runners.core.ZephyrBinaryRunner.check_call')
59def test_gd32isp_create(cc, req, runner_config):
60    args = ['--device', TEST_GD32ISP_DEV,
61            '--port', TEST_GD32ISP_PORT,
62            '--speed', TEST_GD32ISP_SPEED,
63            '--addr', TEST_GD32ISP_ADDR,
64            '--isp', TEST_GD32ISP_CLI_T]
65    parser = argparse.ArgumentParser(allow_abbrev=False)
66    Gd32ispBinaryRunner.add_parser(parser)
67    arg_namespace = parser.parse_args(args)
68    runner = Gd32ispBinaryRunner.create(runner_config, arg_namespace)
69    with patch('os.path.isfile', side_effect=os_path_isfile_patch):
70        runner.run('flash')
71    assert cc.call_args_list == [call(x) for x in EXPECTED_COMMANDS]
72