1# Copyright (c) 2023 Nordic Semiconductor ASA 2# 3# SPDX-License-Identifier: Apache-2.0 4 5import os 6from pathlib import Path 7from typing import Generator 8from unittest.mock import patch 9 10import pytest 11 12from twister_harness.device.qemu_adapter import QemuAdapter 13from twister_harness.exceptions import TwisterHarnessException 14from twister_harness.twister_harness_config import DeviceConfig 15 16 17@pytest.fixture(name='device') 18def fixture_device_adapter(tmp_path) -> Generator[QemuAdapter, None, None]: 19 build_dir = tmp_path / 'build_dir' 20 os.mkdir(build_dir) 21 device = QemuAdapter(DeviceConfig(build_dir=build_dir, type='qemu', base_timeout=5.0)) 22 try: 23 yield device 24 finally: 25 device.close() # to make sure all running processes are closed 26 27 28@patch('shutil.which', return_value='west') 29def test_if_generate_command_creates_proper_command(patched_which, device: QemuAdapter): 30 device.device_config.build_dir = Path('build_dir') 31 device.generate_command() 32 assert device.command == ['west', 'build', '-d', 'build_dir', '-t', 'run'] 33 34 35def test_if_qemu_adapter_runs_without_errors(resources, device: QemuAdapter) -> None: 36 fifo_file_path = str(device.device_config.build_dir / 'qemu-fifo') 37 script_path = resources.joinpath('fifo_mock.py') 38 device.command = ['python', str(script_path), fifo_file_path] 39 device.launch() 40 lines = device.readlines_until(regex='Namespaces are one honking great idea') 41 device.close() 42 assert 'Readability counts.' in lines 43 assert os.path.isfile(device.handler_log_path) 44 with open(device.handler_log_path, 'r') as file: 45 file_lines = [line.strip() for line in file.readlines()] 46 assert file_lines[-2:] == lines[-2:] 47 48 49def test_if_qemu_adapter_raise_exception_due_to_no_fifo_connection(device: QemuAdapter) -> None: 50 device.base_timeout = 0.3 51 device.command = ['sleep', '1'] 52 with pytest.raises(TwisterHarnessException, match='Cannot establish communication with QEMU device.'): 53 device._flash_and_run() 54 device._close_device() 55 assert not os.path.exists(device._fifo_connection._fifo_out_path) 56 assert not os.path.exists(device._fifo_connection._fifo_in_path) 57