|
| 1 | +"""Tests for the pybricks connection module.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import contextlib |
| 5 | +import os |
| 6 | +import tempfile |
| 7 | +from unittest.mock import AsyncMock, PropertyMock, patch |
| 8 | + |
| 9 | +import pytest |
| 10 | +from reactivex.subject import Subject |
| 11 | + |
| 12 | +from pybricksdev.connections.pybricks import ( |
| 13 | + ConnectionState, |
| 14 | + HubCapabilityFlag, |
| 15 | + HubKind, |
| 16 | + PybricksHubBLE, |
| 17 | + StatusFlag, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +class TestPybricksHub: |
| 22 | + """Tests for the PybricksHub base class functionality.""" |
| 23 | + |
| 24 | + @pytest.mark.asyncio |
| 25 | + async def test_download_modern_protocol(self): |
| 26 | + """Test downloading with modern protocol and capability flags.""" |
| 27 | + hub = PybricksHubBLE("mock_device") |
| 28 | + hub._mpy_abi_version = 6 |
| 29 | + hub._client = AsyncMock() |
| 30 | + hub.get_capabilities = AsyncMock(return_value={"pybricks": {"mpy": True}}) |
| 31 | + hub.download_user_program = AsyncMock() |
| 32 | + type(hub.connection_state_observable).value = PropertyMock( |
| 33 | + return_value=ConnectionState.CONNECTED |
| 34 | + ) |
| 35 | + hub._capability_flags = HubCapabilityFlag.USER_PROG_MULTI_FILE_MPY6 |
| 36 | + |
| 37 | + with contextlib.ExitStack() as stack: |
| 38 | + # Create and manage temporary file |
| 39 | + temp = stack.enter_context( |
| 40 | + tempfile.NamedTemporaryFile(suffix=".py", mode="w+", delete=False) |
| 41 | + ) |
| 42 | + temp.write("print('test')") |
| 43 | + temp_path = temp.name |
| 44 | + stack.callback(os.unlink, temp_path) |
| 45 | + |
| 46 | + await hub.download(temp_path) |
| 47 | + hub.download_user_program.assert_called_once() |
| 48 | + |
| 49 | + @pytest.mark.asyncio |
| 50 | + async def test_download_legacy_firmware(self): |
| 51 | + """Test downloading with legacy firmware.""" |
| 52 | + hub = PybricksHubBLE("mock_device") |
| 53 | + hub._mpy_abi_version = None # Legacy firmware |
| 54 | + hub._client = AsyncMock() |
| 55 | + hub.download_user_program = AsyncMock() |
| 56 | + hub.hub_kind = HubKind.BOOST |
| 57 | + type(hub.connection_state_observable).value = PropertyMock( |
| 58 | + return_value=ConnectionState.CONNECTED |
| 59 | + ) |
| 60 | + hub._capability_flags = HubCapabilityFlag.USER_PROG_MULTI_FILE_MPY6 |
| 61 | + |
| 62 | + with contextlib.ExitStack() as stack: |
| 63 | + # Create and manage temporary file |
| 64 | + temp = stack.enter_context( |
| 65 | + tempfile.NamedTemporaryFile(suffix=".py", mode="w+", delete=False) |
| 66 | + ) |
| 67 | + temp.write("print('test')") |
| 68 | + temp_path = temp.name |
| 69 | + stack.callback(os.unlink, temp_path) |
| 70 | + |
| 71 | + await hub.download(temp_path) |
| 72 | + hub.download_user_program.assert_called_once() |
| 73 | + |
| 74 | + @pytest.mark.asyncio |
| 75 | + async def test_download_unsupported_capabilities(self): |
| 76 | + """Test downloading when hub doesn't support required capabilities.""" |
| 77 | + hub = PybricksHubBLE("mock_device") |
| 78 | + hub._mpy_abi_version = 6 |
| 79 | + hub._client = AsyncMock() |
| 80 | + hub.get_capabilities = AsyncMock(return_value={"pybricks": {"mpy": False}}) |
| 81 | + type(hub.connection_state_observable).value = PropertyMock( |
| 82 | + return_value=ConnectionState.CONNECTED |
| 83 | + ) |
| 84 | + hub._capability_flags = 0 |
| 85 | + |
| 86 | + with contextlib.ExitStack() as stack: |
| 87 | + # Create and manage temporary file |
| 88 | + temp = stack.enter_context( |
| 89 | + tempfile.NamedTemporaryFile(suffix=".py", mode="w+", delete=False) |
| 90 | + ) |
| 91 | + temp.write("print('test')") |
| 92 | + temp_path = temp.name |
| 93 | + stack.callback(os.unlink, temp_path) |
| 94 | + |
| 95 | + with pytest.raises( |
| 96 | + RuntimeError, |
| 97 | + match="Hub is not compatible with any of the supported file formats", |
| 98 | + ): |
| 99 | + await hub.download(temp_path) |
| 100 | + |
| 101 | + @pytest.mark.asyncio |
| 102 | + async def test_download_compile_error(self): |
| 103 | + """Test handling compilation errors.""" |
| 104 | + hub = PybricksHubBLE("mock_device") |
| 105 | + hub._mpy_abi_version = 6 |
| 106 | + hub._client = AsyncMock() |
| 107 | + hub.get_capabilities = AsyncMock(return_value={"pybricks": {"mpy": True}}) |
| 108 | + type(hub.connection_state_observable).value = PropertyMock( |
| 109 | + return_value=ConnectionState.CONNECTED |
| 110 | + ) |
| 111 | + hub._capability_flags = HubCapabilityFlag.USER_PROG_MULTI_FILE_MPY6 |
| 112 | + hub._max_user_program_size = 1000 # Set a reasonable size limit |
| 113 | + |
| 114 | + with contextlib.ExitStack() as stack: |
| 115 | + # Create and manage temporary file |
| 116 | + temp = stack.enter_context( |
| 117 | + tempfile.NamedTemporaryFile(suffix=".py", mode="w+", delete=False) |
| 118 | + ) |
| 119 | + temp.write("print('test' # Missing closing parenthesis") |
| 120 | + temp_path = temp.name |
| 121 | + stack.callback(os.unlink, temp_path) |
| 122 | + |
| 123 | + # Mock compile_multi_file to raise SyntaxError |
| 124 | + stack.enter_context( |
| 125 | + patch( |
| 126 | + "pybricksdev.connections.pybricks.compile_multi_file", |
| 127 | + side_effect=SyntaxError("invalid syntax"), |
| 128 | + ) |
| 129 | + ) |
| 130 | + |
| 131 | + with pytest.raises(SyntaxError, match="invalid syntax"): |
| 132 | + await hub.download(temp_path) |
| 133 | + |
| 134 | + @pytest.mark.asyncio |
| 135 | + async def test_run_modern_protocol(self): |
| 136 | + """Test running a program with modern protocol.""" |
| 137 | + hub = PybricksHubBLE("mock_device") |
| 138 | + hub._mpy_abi_version = None # Use modern protocol |
| 139 | + hub._client = AsyncMock() |
| 140 | + hub.client = AsyncMock() |
| 141 | + hub.get_capabilities = AsyncMock(return_value={"pybricks": {"mpy": True}}) |
| 142 | + hub.download_user_program = AsyncMock() |
| 143 | + hub.start_user_program = AsyncMock() |
| 144 | + hub.write_gatt_char = AsyncMock() |
| 145 | + type(hub.connection_state_observable).value = PropertyMock( |
| 146 | + return_value=ConnectionState.CONNECTED |
| 147 | + ) |
| 148 | + hub._capability_flags = HubCapabilityFlag.USER_PROG_MULTI_FILE_MPY6 |
| 149 | + hub.hub_kind = HubKind.BOOST |
| 150 | + |
| 151 | + # Mock the status observable to simulate program start and stop |
| 152 | + status_subject = Subject() |
| 153 | + hub.status_observable = status_subject |
| 154 | + hub._stdout_line_queue = asyncio.Queue() |
| 155 | + hub._enable_line_handler = True |
| 156 | + |
| 157 | + with contextlib.ExitStack() as stack: |
| 158 | + # Create and manage temporary file |
| 159 | + temp = stack.enter_context( |
| 160 | + tempfile.NamedTemporaryFile(suffix=".py", mode="w+", delete=False) |
| 161 | + ) |
| 162 | + temp.write("print('test')") |
| 163 | + temp_path = temp.name |
| 164 | + stack.callback(os.unlink, temp_path) |
| 165 | + |
| 166 | + # Start the run task |
| 167 | + run_task = asyncio.create_task(hub.run(temp_path)) |
| 168 | + |
| 169 | + # Simulate program start |
| 170 | + await asyncio.sleep(0.1) |
| 171 | + status_subject.on_next(StatusFlag.USER_PROGRAM_RUNNING) |
| 172 | + |
| 173 | + # Simulate program stop after a short delay |
| 174 | + await asyncio.sleep(0.1) |
| 175 | + status_subject.on_next(0) # Clear all flags |
| 176 | + |
| 177 | + # Wait for run task to complete |
| 178 | + await run_task |
| 179 | + |
| 180 | + # Verify the expected calls were made |
| 181 | + hub.download_user_program.assert_called_once() |
| 182 | + hub.start_user_program.assert_called_once() |
0 commit comments