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
603 lines (511 loc) · 20.8 KB
/
test_cli.py
File metadata and controls
603 lines (511 loc) · 20.8 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
"""Tests for the pybricksdev CLI commands."""
import argparse
import contextlib
import io
import os
import tempfile
from unittest.mock import AsyncMock, Mock, mock_open, patch
import pytest
from pybricksdev.cli import Compile, Run, Tool, Udev
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,
stay_connected=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,
stay_connected=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,
stay_connected=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,
stay_connected=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()
@pytest.mark.asyncio
async def test_run_ble(self):
"""Test running a program with BLE connection."""
# Create a mock hub
mock_hub = AsyncMock()
mock_hub.run = 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=True,
wait=True,
stay_connected=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_cmd = Run()
await run_cmd.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.run.assert_called_once_with(temp_path, True)
mock_hub.disconnect.assert_called_once()
@pytest.mark.asyncio
async def test_run_usb(self):
"""Test running a program with USB connection."""
# Create a mock hub
mock_hub = AsyncMock()
mock_hub.run = 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=True,
wait=True,
stay_connected=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_cmd = Run()
await run_cmd.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.run.assert_called_once_with(temp_path, True)
mock_hub.disconnect.assert_called_once()
@pytest.mark.asyncio
async def test_run_stdin(self):
"""Test running a program from stdin."""
# Create a mock hub
mock_hub = AsyncMock()
mock_hub.run = 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=True,
wait=True,
stay_connected=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"
mock_temp.return_value.__enter__.return_value.write = Mock()
mock_temp.return_value.__enter__.return_value.flush = Mock()
# Run the command
run_cmd = Run()
await run_cmd.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.run.assert_called_once_with("<stdin>", True)
mock_hub.disconnect.assert_called_once()
@pytest.mark.asyncio
async def test_run_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=True,
stay_connected=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_cmd = Run()
with pytest.raises(RuntimeError, match="Connection failed"):
await run_cmd.run(args)
# Verify disconnect was not called since connection failed
mock_hub.disconnect.assert_not_called()
class TestCompile:
"""Tests for the Compile 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 compile command
compile_cmd = Compile()
compile_cmd.add_parser(subparsers)
# Verify the parser was created with correct arguments
assert "compile" in subparsers.choices
parser = subparsers.choices["compile"]
assert parser.tool is compile_cmd
# 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(["test.py"])
assert args.file.name == "test.py"
assert args.abi == 6 # Default ABI version
# Test with custom ABI version
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(["test.py", "--abi", "5"])
assert args.abi == 5
# Test that invalid ABI version is rejected
with pytest.raises(SystemExit):
parser.parse_args(["test.py", "--abi", "4"])
@pytest.mark.asyncio
async def test_compile_file(self):
"""Test compiling a Python file."""
# Create a mock compile function
mock_compile = AsyncMock()
mock_compile.return_value = b"compiled bytecode"
# 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(
file=stack.enter_context(open(temp_path, "r", encoding="utf-8")),
abi=6,
)
# Mock the compile function
stack.enter_context(
patch("pybricksdev.compile.compile_multi_file", mock_compile)
)
mock_print = stack.enter_context(patch("pybricksdev.compile.print_mpy"))
# Run the command
compile_cmd = Compile()
await compile_cmd.run(args)
# Verify compilation was called correctly
mock_compile.assert_called_once_with(temp_path, 6)
mock_print.assert_called_once_with(b"compiled bytecode")
@pytest.mark.asyncio
async def test_compile_stdin(self):
"""Test compiling from stdin."""
# Create a mock stdin
mock_stdin = io.StringIO("print('test')")
mock_stdin.buffer = io.BytesIO(b"print('test')")
mock_stdin.name = "<stdin>"
# Create a mock compile function
mock_compile = AsyncMock()
mock_compile.return_value = b"compiled bytecode"
# Set up mocks using ExitStack
with contextlib.ExitStack() as stack:
# Create args
args = argparse.Namespace(
file=mock_stdin,
abi=6,
)
# Mock the compile function and tempfile
stack.enter_context(
patch("pybricksdev.compile.compile_multi_file", mock_compile)
)
mock_print = stack.enter_context(patch("pybricksdev.compile.print_mpy"))
mock_temp = stack.enter_context(patch("tempfile.NamedTemporaryFile"))
mock_temp.return_value.__enter__.return_value.name = "/tmp/test.py"
mock_temp.return_value.__enter__.return_value.write = Mock()
mock_temp.return_value.__enter__.return_value.flush = Mock()
# Run the command
compile_cmd = Compile()
await compile_cmd.run(args)
# Verify compilation was called correctly
mock_compile.assert_called_once_with("<stdin>", 6)
mock_print.assert_called_once_with(b"compiled bytecode")
class TestUdev:
"""Tests for the Udev 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 udev command
udev_cmd = Udev()
udev_cmd.add_parser(subparsers)
# Verify the parser was created with correct arguments
assert "udev" in subparsers.choices
parser = subparsers.choices["udev"]
assert parser.tool is udev_cmd
@pytest.mark.asyncio
async def test_print_rules(self):
"""Test printing udev rules."""
# Mock the read_text function
mock_rules = (
'# Mock udev rules\nSUBSYSTEM=="usb", ATTRS{idVendor}=="0694", MODE="0666"'
)
mock_read_text = Mock(return_value=mock_rules)
# Set up mocks using ExitStack
with contextlib.ExitStack() as stack:
# Create args
args = argparse.Namespace()
# Mock the read_text function
stack.enter_context(patch("importlib.resources.read_text", mock_read_text))
mock_print = stack.enter_context(patch("builtins.print"))
# Run the command
udev_cmd = Udev()
await udev_cmd.run(args)
# Verify the rules were printed
mock_read_text.assert_called_once()
mock_print.assert_called_once_with(mock_rules)