1# Copyright 2025 NXP
2#
3# SPDX-License-Identifier: Apache-2.0
4
5import logging
6import re
7
8import pytest
9from twister_harness import DeviceAdapter, Shell
10
11logger = logging.getLogger(__name__)
12
13
14def pytest_addoption(parser) -> None:
15    """Add local parser options to pytest."""
16    parser.addoption('--hci-transport', default=None, help='Configuration HCI transport for bumble')
17
18
19@pytest.fixture(name='initialize', scope='session')
20def fixture_initialize(request, shell: Shell, dut: DeviceAdapter):
21    """Session initializtion"""
22    # Get HCI transport for bumble
23    hci = request.config.getoption('--hci-transport')
24
25    if hci is None:
26        for fixture in dut.device_config.fixtures:
27            if fixture.startswith('usb_hci:'):
28                hci = fixture.split(sep=':', maxsplit=1)[1]
29                break
30
31    assert hci is not None
32
33    shell.exec_command("bt init")
34    lines = dut.readlines_until("Bluetooth initialized")
35    regex = r'Identity: *(?P<bd_addr>([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}) *\((.*?)\))'
36    bd_addr = None
37    for line in lines:
38        logger.info(f"Shell log {line}")
39        m = re.search(regex, line)
40        if m:
41            bd_addr = m.group('bd_addr')
42
43    if bd_addr is None:
44        logger.error('Fail to get IUT BD address')
45        raise AssertionError
46
47    logger.info('initialized')
48    return hci, bd_addr
49
50
51@pytest.fixture
52def device_under_test(initialize):
53    logger.info('Start running testcase')
54    yield initialize
55    logger.info('Done')
56