forked from pybricks/pybricksdev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
248 lines (210 loc) · 8.29 KB
/
test_cli.py
File metadata and controls
248 lines (210 loc) · 8.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""Tests for the pybricksdev CLI commands."""
import argparse
import contextlib
import io
import os
import tempfile
from unittest.mock import AsyncMock, mock_open, patch
import pytest
from pybricksdev.cli import Run, Tool
class TestTool:
"""Tests for the base Tool class."""
def test_is_abstract(self):
"""Test that Tool is an abstract base class."""
with pytest.raises(TypeError):
Tool()
class TestRun:
"""Tests for the Download command."""
def test_add_parser(self):
"""Test that the parser is set up correctly."""
# Create a subparsers object
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
# Add the download command
run = Run()
run.add_parser(subparsers)
# Verify the parser was created with correct arguments
assert "run" in subparsers.choices
parser = subparsers.choices["run"]
assert parser.tool is run
# Test that required arguments are present
mock_file = mock_open(read_data="print('test')")
mock_file.return_value.name = "test.py"
with patch("builtins.open", mock_file):
args = parser.parse_args(["ble", "test.py"])
assert args.conntype == "ble"
assert args.file.name == "test.py"
assert args.name is None
# Test with optional name argument
mock_file = mock_open(read_data="print('test')")
mock_file.return_value.name = "test.py"
with patch("builtins.open", mock_file):
args = parser.parse_args(["ble", "test.py", "-n", "MyHub"])
assert args.name == "MyHub"
# Test that invalid connection type is rejected
with pytest.raises(SystemExit):
parser.parse_args(["invalid", "test.py"])
@pytest.mark.asyncio
async def test_download_ble(self):
"""Test running the download command with BLE connection."""
# Create a mock hub
mock_hub = AsyncMock()
mock_hub._mpy_abi_version = 6
mock_hub.download = AsyncMock()
# Set up mocks using ExitStack
with contextlib.ExitStack() as stack:
# Create and manage temporary file
temp = stack.enter_context(
tempfile.NamedTemporaryFile(
suffix=".py", mode="w+", delete=False, encoding="utf-8"
)
)
temp.write("print('test')")
temp_path = temp.name
stack.callback(os.unlink, temp_path)
# Create args
args = argparse.Namespace(
conntype="ble",
file=stack.enter_context(open(temp_path, "r", encoding="utf-8")),
name="MyHub",
start=False,
wait=False,
)
mock_hub_class = stack.enter_context(
patch(
"pybricksdev.connections.pybricks.PybricksHubBLE",
return_value=mock_hub,
)
)
stack.enter_context(
patch("pybricksdev.ble.find_device", return_value="mock_device")
)
# Run the command
run = Run()
await run.run(args)
# Verify the hub was created and used correctly
mock_hub_class.assert_called_once_with("mock_device")
mock_hub.connect.assert_called_once()
mock_hub.download.assert_called_once()
mock_hub.disconnect.assert_called_once()
@pytest.mark.asyncio
async def test_download_usb(self):
"""Test running the download command with USB connection."""
# Create a mock hub
mock_hub = AsyncMock()
mock_hub._mpy_abi_version = 6
mock_hub.download = AsyncMock()
# Set up mocks using ExitStack
with contextlib.ExitStack() as stack:
# Create and manage temporary file
temp = stack.enter_context(
tempfile.NamedTemporaryFile(
suffix=".py", mode="w+", delete=False, encoding="utf-8"
)
)
temp.write("print('test')")
temp_path = temp.name
stack.callback(os.unlink, temp_path)
# Create args
args = argparse.Namespace(
conntype="usb",
file=stack.enter_context(open(temp_path, "r", encoding="utf-8")),
name=None,
start=False,
wait=False,
)
mock_hub_class = stack.enter_context(
patch(
"pybricksdev.connections.pybricks.PybricksHubUSB",
return_value=mock_hub,
)
)
stack.enter_context(patch("usb.core.find", return_value="mock_device"))
# Run the command
run = Run()
await run.run(args)
# Verify the hub was created and used correctly
mock_hub_class.assert_called_once_with("mock_device")
mock_hub.connect.assert_called_once()
mock_hub.download.assert_called_once()
mock_hub.disconnect.assert_called_once()
@pytest.mark.asyncio
async def test_download_stdin(self):
"""Test running the download command with stdin input."""
# Create a mock hub
mock_hub = AsyncMock()
mock_hub._mpy_abi_version = 6
mock_hub.download = AsyncMock()
# Create a mock stdin
mock_stdin = io.StringIO("print('test')")
mock_stdin.buffer = io.BytesIO(b"print('test')")
mock_stdin.name = "<stdin>"
# Create args
args = argparse.Namespace(
conntype="ble",
file=mock_stdin,
name="MyHub",
start=False,
wait=False,
)
# Set up mocks using ExitStack
with contextlib.ExitStack() as stack:
mock_hub_class = stack.enter_context(
patch(
"pybricksdev.connections.pybricks.PybricksHubBLE",
return_value=mock_hub,
)
)
stack.enter_context(
patch("pybricksdev.ble.find_device", return_value="mock_device")
)
mock_temp = stack.enter_context(patch("tempfile.NamedTemporaryFile"))
mock_temp.return_value.__enter__.return_value.name = "/tmp/test.py"
# Run the command
run = Run()
await run.run(args)
# Verify the hub was created and used correctly
mock_hub_class.assert_called_once_with("mock_device")
mock_hub.connect.assert_called_once()
mock_hub.download.assert_called_once()
mock_hub.disconnect.assert_called_once()
@pytest.mark.asyncio
async def test_download_connection_error(self):
"""Test handling connection errors."""
# Create a mock hub that raises an error during connect
mock_hub = AsyncMock()
mock_hub.connect.side_effect = RuntimeError("Connection failed")
# Set up mocks using ExitStack
with contextlib.ExitStack() as stack:
# Create and manage temporary file
temp = stack.enter_context(
tempfile.NamedTemporaryFile(
suffix=".py", mode="w+", delete=False, encoding="utf-8"
)
)
temp.write("print('test')")
temp_path = temp.name
stack.callback(os.unlink, temp_path)
# Create args
args = argparse.Namespace(
conntype="ble",
file=stack.enter_context(open(temp_path, "r", encoding="utf-8")),
name="MyHub",
start=False,
wait=False,
)
stack.enter_context(
patch(
"pybricksdev.connections.pybricks.PybricksHubBLE",
return_value=mock_hub,
)
)
stack.enter_context(
patch("pybricksdev.ble.find_device", return_value="mock_device")
)
# Run the command and verify it raises the error
run = Run()
with pytest.raises(RuntimeError, match="Connection failed"):
await run.run(args)
# Verify disconnect was not called since connection failed
mock_hub.disconnect.assert_not_called()