forked from Serial-Studio/Serial-Studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api.py
More file actions
2907 lines (2498 loc) · 118 KB
/
Copy pathtest_api.py
File metadata and controls
2907 lines (2498 loc) · 118 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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Serial Studio API Client & Test Suite
======================================
A versatile tool for interacting with the Serial Studio API Server.
Can be used as a command-line client, interactive shell, or test suite.
Usage:
# Send a single command
python test_api.py send io.manager.getStatus
# Send command with parameters (key=value format - works on all shells)
python test_api.py send io.driver.uart.setBaudRate -p baudRate=115200
# Multiple parameters
python test_api.py send io.driver.network.setTcpPort -p port=8080
# JSON format (use on bash/zsh, tricky on PowerShell)
python test_api.py send io.driver.uart.setBaudRate --params '{"baudRate": 115200}'
# List all available commands
python test_api.py list
# Interactive mode (REPL)
python test_api.py interactive
# Live monitor (real-time status updates)
python test_api.py monitor [--interval 500] [--compact] [--show-raw-data]
# Run test suite
python test_api.py test [--verbose]
# Send batch from JSON file
python test_api.py batch commands.json
# Pipe JSON output (for scripting)
python test_api.py send io.manager.getStatus --json | jq '.result'
Common options for all modes:
--host HOST Server host (default: 127.0.0.1)
--port PORT Server port (default: 7777)
Requirements:
- Serial Studio running with API Server enabled (port 7777)
- Python 3.8+
Copyright (C) 2020-2025 Alex Spataru
SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-SerialStudio-Commercial
"""
import json
import socket
import argparse
import sys
import time
import uuid
import select
import base64
import os
from typing import Any, Optional
from dataclasses import dataclass
from enum import Enum
try:
import readline
READLINE_AVAILABLE = True
except ImportError:
READLINE_AVAILABLE = False
# =============================================================================
# Configuration
# =============================================================================
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 7777
SOCKET_TIMEOUT = 5.0
RECV_BUFFER_SIZE = 65536
# ANSI color codes for terminal output
class Colors:
RESET = '\033[0m'
BOLD = '\033[1m'
DIM = '\033[2m'
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
GRAY = '\033[90m'
@staticmethod
def is_supported():
"""Check if terminal supports colors."""
return hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() and os.name != 'nt' or 'ANSICON' in os.environ
# Global color support flag
COLORS_ENABLED = Colors.is_supported()
# =============================================================================
# Protocol Constants (matching C++ API::MessageType and API::ErrorCode)
# =============================================================================
class MessageType:
COMMAND = "command"
BATCH = "batch"
RESPONSE = "response"
class ErrorCode:
INVALID_JSON = "INVALID_JSON"
INVALID_MESSAGE_TYPE = "INVALID_MESSAGE_TYPE"
UNKNOWN_COMMAND = "UNKNOWN_COMMAND"
INVALID_PARAM = "INVALID_PARAM"
MISSING_PARAM = "MISSING_PARAM"
EXECUTION_ERROR = "EXECUTION_ERROR"
# =============================================================================
# Color Helpers
# =============================================================================
def colorize(text: str, color: str) -> str:
"""Apply color to text if colors are enabled."""
if COLORS_ENABLED:
return f"{color}{text}{Colors.RESET}"
return text
def success(text: str) -> str:
"""Return text in success color (green)."""
return colorize(text, Colors.GREEN)
def error(text: str) -> str:
"""Return text in error color (red)."""
return colorize(text, Colors.RED)
def info(text: str) -> str:
"""Return text in info color (blue)."""
return colorize(text, Colors.BLUE)
def warning(text: str) -> str:
"""Return text in warning color (yellow)."""
return colorize(text, Colors.YELLOW)
def dim(text: str) -> str:
"""Return text in dim style."""
return colorize(text, Colors.DIM)
def bold(text: str) -> str:
"""Return text in bold style."""
return colorize(text, Colors.BOLD)
# =============================================================================
# Test Result Tracking
# =============================================================================
class TestResult(Enum):
PASSED = "PASSED"
FAILED = "FAILED"
SKIPPED = "SKIPPED"
@dataclass
class TestCase:
name: str
result: TestResult
message: str = ""
duration_ms: float = 0.0
class TestSuite:
def __init__(self, name: str):
self.name = name
self.tests: list[TestCase] = []
def add_result(self, test: TestCase):
self.tests.append(test)
@property
def passed(self) -> int:
return sum(1 for t in self.tests if t.result == TestResult.PASSED)
@property
def failed(self) -> int:
return sum(1 for t in self.tests if t.result == TestResult.FAILED)
@property
def skipped(self) -> int:
return sum(1 for t in self.tests if t.result == TestResult.SKIPPED)
def print_summary(self):
print(bold(f"\n{'=' * 60}"))
print(bold(f"Test Suite: {self.name}"))
print(bold(f"{'=' * 60}"))
total = len(self.tests)
passed_str = success(f"Passed: {self.passed}") if self.passed > 0 else dim(f"Passed: {self.passed}")
failed_str = error(f"Failed: {self.failed}") if self.failed > 0 else dim(f"Failed: {self.failed}")
skipped_str = warning(f"Skipped: {self.skipped}") if self.skipped > 0 else dim(f"Skipped: {self.skipped}")
print(f"Total: {total} | {passed_str} | {failed_str} | {skipped_str}")
print(bold(f"{'=' * 60}"))
if self.failed > 0:
print(error("\nFailed Tests:"))
for test in self.tests:
if test.result == TestResult.FAILED:
print(f" {error('✗')} {test.name}: {error(test.message)}")
print()
# =============================================================================
# API Client
# =============================================================================
class SerialStudioAPI:
"""Client for communicating with Serial Studio API Server."""
def __init__(self, host: str = DEFAULT_HOST, port: int = DEFAULT_PORT, verbose: bool = False):
self.host = host
self.port = port
self.verbose = verbose
self.socket: Optional[socket.socket] = None
self.receive_buffer = b""
def connect(self) -> bool:
"""Establish TCP connection to the API server."""
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.settimeout(SOCKET_TIMEOUT)
self.socket.connect((self.host, self.port))
if self.verbose:
print(f"[INFO] Connected to {self.host}:{self.port}")
return True
except Exception as e:
print(f"[ERROR] Failed to connect: {e}")
return False
def disconnect(self):
"""Close the TCP connection."""
if self.socket:
try:
self.socket.close()
except Exception:
pass
self.socket = None
self.receive_buffer = b""
def recv_message(self, timeout: float = SOCKET_TIMEOUT) -> Optional[dict]:
"""
Receive a single JSON message from the socket.
Handles newline-delimited JSON messages and buffering.
Returns None on timeout or error.
"""
if not self.socket:
return None
try:
end_time = time.time() + timeout
while True:
newline_pos = self.receive_buffer.find(b'\n')
if newline_pos != -1:
line = self.receive_buffer[:newline_pos]
self.receive_buffer = self.receive_buffer[newline_pos + 1:]
if line.strip():
if self.verbose:
print(f"[RECV] {line.decode('utf-8', errors='replace')}")
return json.loads(line.decode('utf-8'))
continue
remaining_time = end_time - time.time()
if remaining_time <= 0:
return None
ready = select.select([self.socket], [], [], min(remaining_time, 0.1))
if ready[0]:
chunk = self.socket.recv(RECV_BUFFER_SIZE)
if not chunk:
return None
self.receive_buffer += chunk
except Exception as e:
if self.verbose:
print(f"[ERROR] recv_message: {e}")
return None
def send_raw(self, data: bytes, expected_id: Optional[str] = None, timeout: float = SOCKET_TIMEOUT) -> Optional[dict]:
"""
Send raw bytes and receive JSON response.
If expected_id is provided, will wait for a response with that ID,
discarding any push notifications (data/frames) in the meantime.
"""
if not self.socket:
return None
try:
if self.verbose:
print(f"[SEND] {data.decode('utf-8', errors='replace').strip()}")
self.socket.sendall(data)
# If we're expecting a specific response ID, wait for it
if expected_id:
end_time = time.time() + timeout
while True:
remaining = end_time - time.time()
if remaining <= 0:
if self.verbose:
print(f"[ERROR] Timeout waiting for response ID {expected_id}")
return None
msg = self.recv_message(timeout=remaining)
if not msg:
return None
# Check if this is the response we're waiting for
if msg.get("type") == MessageType.RESPONSE and msg.get("id") == expected_id:
return msg
# Otherwise, it's a push notification - discard and continue waiting
if self.verbose:
print(f"[DEBUG] Discarding push notification while waiting for {expected_id}")
else:
# No expected ID, just return the next message
return self.recv_message(timeout=timeout)
except Exception as e:
if self.verbose:
print(f"[ERROR] {e}")
return None
def send_json(self, obj: dict) -> Optional[dict]:
"""Send JSON object and receive JSON response."""
data = json.dumps(obj, separators=(',', ':')) + "\n"
expected_id = obj.get("id")
return self.send_raw(data.encode('utf-8'), expected_id=expected_id, timeout=SOCKET_TIMEOUT)
def send_command(self, command: str, params: Optional[dict] = None,
request_id: Optional[str] = None) -> Optional[dict]:
"""Send a single command request."""
msg = {
"type": MessageType.COMMAND,
"id": request_id or str(uuid.uuid4()),
"command": command,
}
if params:
msg["params"] = params
return self.send_json(msg)
def send_batch(self, commands: list[dict], request_id: Optional[str] = None) -> Optional[dict]:
"""Send a batch of commands."""
msg = {
"type": MessageType.BATCH,
"id": request_id or str(uuid.uuid4()),
"commands": commands,
}
return self.send_json(msg)
def has_data_available(self, timeout: float = 0.0) -> bool:
"""Check if data is available to read from the socket."""
if not self.socket:
return False
if self.receive_buffer:
return True
try:
ready = select.select([self.socket], [], [], timeout)
return bool(ready[0])
except Exception:
return False
# =============================================================================
# Test Helpers
# =============================================================================
def assert_success(response: Optional[dict], test_name: str) -> tuple[bool, str]:
"""Assert that response indicates success."""
if response is None:
return False, "No response received"
if not isinstance(response, dict):
return False, f"Response is not a dict: {type(response)}"
if response.get("type") != MessageType.RESPONSE:
return False, f"Wrong type: {response.get('type')}"
if not response.get("success"):
error = response.get("error", {})
return False, f"Not successful: {error.get('code')} - {error.get('message')}"
return True, ""
def assert_error(response: Optional[dict], expected_code: str, test_name: str) -> tuple[bool, str]:
"""Assert that response is an error with specific code."""
if response is None:
return False, "No response received"
if not isinstance(response, dict):
return False, f"Response is not a dict: {type(response)}"
if response.get("success"):
return False, "Expected error but got success"
error = response.get("error", {})
if error.get("code") != expected_code:
return False, f"Expected error code {expected_code}, got {error.get('code')}"
return True, ""
def run_test(suite: TestSuite, name: str, test_fn) -> bool:
"""Run a single test and record the result."""
start_time = time.time()
try:
passed, message = test_fn()
duration_ms = (time.time() - start_time) * 1000
result = TestResult.PASSED if passed else TestResult.FAILED
suite.add_result(TestCase(name, result, message, duration_ms))
if passed:
status = success("✓")
print(f" {status} {dim(name)} {dim(f'({duration_ms:.1f}ms)')}")
else:
status = error("✗")
print(f" {status} {name} {dim(f'({duration_ms:.1f}ms)')} - {error(message)}")
return passed
except Exception as e:
duration_ms = (time.time() - start_time) * 1000
suite.add_result(TestCase(name, TestResult.FAILED, str(e), duration_ms))
print(f" {error('✗')} {name} {dim(f'({duration_ms:.1f}ms)')} - {error(f'Exception: {e}')}")
return False
# =============================================================================
# Protocol Tests
# =============================================================================
def test_protocol(api: SerialStudioAPI, suite: TestSuite):
"""Test basic protocol handling."""
print("\n--- Protocol Tests ---")
# Test: Invalid JSON
def test_invalid_json():
response = api.send_raw(b"{not valid json}\n")
return assert_error(response, ErrorCode.INVALID_JSON, "invalid_json")
run_test(suite, "Invalid JSON rejected", test_invalid_json)
# Test: Empty message
def test_empty_object():
response = api.send_json({})
return assert_error(response, ErrorCode.INVALID_JSON, "empty_object")
run_test(suite, "Empty object rejected", test_empty_object)
# Test: Missing type field
def test_missing_type():
response = api.send_json({"command": "test"})
return assert_error(response, ErrorCode.INVALID_JSON, "missing_type")
run_test(suite, "Missing type field rejected", test_missing_type)
# Test: Unknown message type
def test_unknown_type():
response = api.send_json({"type": "unknown_type", "command": "test"})
return assert_error(response, ErrorCode.INVALID_MESSAGE_TYPE, "unknown_type")
run_test(suite, "Unknown message type rejected", test_unknown_type)
# Test: Command without command field
def test_command_missing_cmd():
response = api.send_json({"type": MessageType.COMMAND, "id": "test-1"})
return assert_error(response, ErrorCode.INVALID_MESSAGE_TYPE, "missing_command")
run_test(suite, "Command without 'command' field rejected", test_command_missing_cmd)
# Test: Unknown command
def test_unknown_command():
response = api.send_command("nonexistent.command.xyz")
return assert_error(response, ErrorCode.UNKNOWN_COMMAND, "unknown_command")
run_test(suite, "Unknown command rejected", test_unknown_command)
# Test: Response ID matching
def test_response_id():
test_id = "test-id-12345"
response = api.send_command("api.getCommands", request_id=test_id)
if response is None:
return False, "No response"
if response.get("id") != test_id:
return False, f"ID mismatch: expected {test_id}, got {response.get('id')}"
return True, ""
run_test(suite, "Response ID matches request ID", test_response_id)
# =============================================================================
# API Commands Tests
# =============================================================================
def test_api_commands(api: SerialStudioAPI, suite: TestSuite):
"""Test api.* commands."""
print("\n--- API Commands Tests ---")
# Test: api.getCommands
def test_get_commands():
response = api.send_command("api.getCommands")
passed, msg = assert_success(response, "getCommands")
if not passed:
return False, msg
result = response.get("result", {})
commands = result.get("commands", [])
if not commands:
return False, "No commands returned"
# Verify some expected commands exist
command_names = [c.get("name") for c in commands]
expected = ["api.getCommands", "io.manager.connect", "io.driver.uart.setBaudRate"]
for cmd in expected:
if cmd not in command_names:
return False, f"Missing expected command: {cmd}"
return True, ""
run_test(suite, "api.getCommands returns command list", test_get_commands)
# Test: Command descriptions exist
def test_command_descriptions():
response = api.send_command("api.getCommands")
passed, msg = assert_success(response, "getCommands")
if not passed:
return False, msg
commands = response.get("result", {}).get("commands", [])
for cmd in commands:
if not cmd.get("description"):
return False, f"Command {cmd.get('name')} has no description"
return True, ""
run_test(suite, "All commands have descriptions", test_command_descriptions)
# =============================================================================
# IO Manager Tests
# =============================================================================
def test_io_manager(api: SerialStudioAPI, suite: TestSuite):
"""Test io.manager.* commands."""
print("\n--- IO Manager Tests ---")
# Test: getStatus
def test_get_status():
response = api.send_command("io.manager.getStatus")
passed, msg = assert_success(response, "getStatus")
if not passed:
return False, msg
result = response.get("result", {})
# Verify expected fields exist
expected_fields = ["isConnected", "paused", "busType", "configurationOk"]
for field in expected_fields:
if field not in result:
return False, f"Missing field: {field}"
return True, ""
run_test(suite, "io.manager.getStatus returns status", test_get_status)
# Test: getAvailableBuses
def test_get_buses():
response = api.send_command("io.manager.getAvailableBuses")
passed, msg = assert_success(response, "getAvailableBuses")
if not passed:
return False, msg
buses = response.get("result", {}).get("buses", [])
if not buses:
return False, "No buses returned"
# Verify bus structure
for bus in buses:
if "index" not in bus or "name" not in bus:
return False, f"Invalid bus structure: {bus}"
return True, ""
run_test(suite, "io.manager.getAvailableBuses returns bus list", test_get_buses)
# Test: setBusType
def test_set_bus_type():
response = api.send_command("io.manager.setBusType", {"busType": 0})
passed, msg = assert_success(response, "setBusType")
if not passed:
return False, msg
result = response.get("result", {})
if result.get("busType") != 0:
return False, f"busType not set correctly: {result.get('busType')}"
return True, ""
run_test(suite, "io.manager.setBusType sets bus type", test_set_bus_type)
# Test: setBusType invalid
def test_set_bus_type_invalid():
response = api.send_command("io.manager.setBusType", {"busType": 999})
return assert_error(response, ErrorCode.INVALID_PARAM, "setBusType_invalid")
run_test(suite, "io.manager.setBusType rejects invalid bus type", test_set_bus_type_invalid)
# Test: setBusType missing param
def test_set_bus_type_missing():
response = api.send_command("io.manager.setBusType", {})
return assert_error(response, ErrorCode.MISSING_PARAM, "setBusType_missing")
run_test(suite, "io.manager.setBusType requires busType param", test_set_bus_type_missing)
# Test: setPaused
def test_set_paused():
response = api.send_command("io.manager.setPaused", {"paused": True})
passed, msg = assert_success(response, "setPaused")
if not passed:
return False, msg
# Restore to false
api.send_command("io.manager.setPaused", {"paused": False})
return True, ""
run_test(suite, "io.manager.setPaused sets pause state", test_set_paused)
# Test: setPaused missing param
def test_set_paused_missing():
response = api.send_command("io.manager.setPaused", {})
return assert_error(response, ErrorCode.MISSING_PARAM, "setPaused_missing")
run_test(suite, "io.manager.setPaused requires paused param", test_set_paused_missing)
# Test: connect when not configured (should fail)
def test_connect_not_configured():
response = api.send_command("io.manager.connect")
# This should either succeed (if configured) or fail gracefully
# We just verify we get a valid response
if response is None:
return False, "No response"
if response.get("type") != MessageType.RESPONSE:
return False, f"Wrong response type: {response.get('type')}"
# Clean up: Disconnect if we connected successfully
if response.get("success"):
api.send_command("io.manager.disconnect")
return True, ""
run_test(suite, "io.manager.connect returns valid response", test_connect_not_configured)
# Test: disconnect when not connected
def test_disconnect_not_connected():
response = api.send_command("io.manager.disconnect")
# Should fail because not connected
return assert_error(response, ErrorCode.EXECUTION_ERROR, "disconnect_not_connected")
run_test(suite, "io.manager.disconnect fails when not connected", test_disconnect_not_connected)
# Test: writeData when not connected
def test_write_data_not_connected():
import base64
test_data = base64.b64encode(b"Hello").decode()
response = api.send_command("io.manager.writeData", {"data": test_data})
return assert_error(response, ErrorCode.EXECUTION_ERROR, "writeData_not_connected")
run_test(suite, "io.manager.writeData fails when not connected", test_write_data_not_connected)
# Test: writeData missing param
def test_write_data_missing():
response = api.send_command("io.manager.writeData", {})
return assert_error(response, ErrorCode.MISSING_PARAM, "writeData_missing")
run_test(suite, "io.manager.writeData requires data param", test_write_data_missing)
# =============================================================================
# UART Handler Tests
# =============================================================================
def test_uart_handler(api: SerialStudioAPI, suite: TestSuite):
"""Test io.driver.uart.* commands."""
print("\n--- UART Handler Tests ---")
# Test: getConfiguration
def test_get_configuration():
response = api.send_command("io.driver.uart.getConfiguration")
passed, msg = assert_success(response, "getConfiguration")
if not passed:
return False, msg
result = response.get("result", {})
expected_fields = ["baudRate", "parityIndex", "dataBitsIndex", "stopBitsIndex", "flowControlIndex"]
for field in expected_fields:
if field not in result:
return False, f"Missing field: {field}"
return True, ""
run_test(suite, "io.driver.uart.getConfiguration returns config", test_get_configuration)
# Test: getPortList
def test_get_port_list():
response = api.send_command("io.driver.uart.getPortList")
passed, msg = assert_success(response, "getPortList")
if not passed:
return False, msg
result = response.get("result", {})
if "portList" not in result:
return False, "Missing portList field"
if "currentPortIndex" not in result:
return False, "Missing currentPortIndex field"
return True, ""
run_test(suite, "io.driver.uart.getPortList returns port list", test_get_port_list)
# Test: getBaudRateList
def test_get_baud_rate_list():
response = api.send_command("io.driver.uart.getBaudRateList")
passed, msg = assert_success(response, "getBaudRateList")
if not passed:
return False, msg
result = response.get("result", {})
baud_rates = result.get("baudRateList", [])
if not baud_rates:
return False, "No baud rates returned"
# Verify common baud rates exist
common = ["9600", "115200"]
for rate in common:
if rate not in baud_rates:
return False, f"Missing common baud rate: {rate}"
return True, ""
run_test(suite, "io.driver.uart.getBaudRateList returns baud rates", test_get_baud_rate_list)
# Test: setBaudRate
def test_set_baud_rate():
response = api.send_command("io.driver.uart.setBaudRate", {"baudRate": 115200})
passed, msg = assert_success(response, "setBaudRate")
if not passed:
return False, msg
if response.get("result", {}).get("baudRate") != 115200:
return False, "Baud rate not set correctly"
return True, ""
run_test(suite, "io.driver.uart.setBaudRate sets baud rate", test_set_baud_rate)
# Test: setBaudRate invalid
def test_set_baud_rate_invalid():
response = api.send_command("io.driver.uart.setBaudRate", {"baudRate": -1})
return assert_error(response, ErrorCode.INVALID_PARAM, "setBaudRate_invalid")
run_test(suite, "io.driver.uart.setBaudRate rejects invalid rate", test_set_baud_rate_invalid)
# Test: setBaudRate missing
def test_set_baud_rate_missing():
response = api.send_command("io.driver.uart.setBaudRate", {})
return assert_error(response, ErrorCode.MISSING_PARAM, "setBaudRate_missing")
run_test(suite, "io.driver.uart.setBaudRate requires baudRate param", test_set_baud_rate_missing)
# Test: setParity
def test_set_parity():
response = api.send_command("io.driver.uart.setParity", {"parityIndex": 0})
passed, msg = assert_success(response, "setParity")
if not passed:
return False, msg
return True, ""
run_test(suite, "io.driver.uart.setParity sets parity", test_set_parity)
# Test: setParity invalid
def test_set_parity_invalid():
response = api.send_command("io.driver.uart.setParity", {"parityIndex": 999})
return assert_error(response, ErrorCode.INVALID_PARAM, "setParity_invalid")
run_test(suite, "io.driver.uart.setParity rejects invalid index", test_set_parity_invalid)
# Test: setDataBits
def test_set_data_bits():
response = api.send_command("io.driver.uart.setDataBits", {"dataBitsIndex": 3}) # 8 bits
passed, msg = assert_success(response, "setDataBits")
if not passed:
return False, msg
return True, ""
run_test(suite, "io.driver.uart.setDataBits sets data bits", test_set_data_bits)
# Test: setStopBits
def test_set_stop_bits():
response = api.send_command("io.driver.uart.setStopBits", {"stopBitsIndex": 0}) # 1 stop bit
passed, msg = assert_success(response, "setStopBits")
if not passed:
return False, msg
return True, ""
run_test(suite, "io.driver.uart.setStopBits sets stop bits", test_set_stop_bits)
# Test: setFlowControl
def test_set_flow_control():
response = api.send_command("io.driver.uart.setFlowControl", {"flowControlIndex": 0}) # None
passed, msg = assert_success(response, "setFlowControl")
if not passed:
return False, msg
return True, ""
run_test(suite, "io.driver.uart.setFlowControl sets flow control", test_set_flow_control)
# Test: setDtrEnabled
def test_set_dtr():
response = api.send_command("io.driver.uart.setDtrEnabled", {"dtrEnabled": True})
passed, msg = assert_success(response, "setDtrEnabled")
if not passed:
return False, msg
return True, ""
run_test(suite, "io.driver.uart.setDtrEnabled sets DTR", test_set_dtr)
# Test: setAutoReconnect
def test_set_auto_reconnect():
response = api.send_command("io.driver.uart.setAutoReconnect", {"autoReconnect": False})
passed, msg = assert_success(response, "setAutoReconnect")
if not passed:
return False, msg
return True, ""
run_test(suite, "io.driver.uart.setAutoReconnect sets auto-reconnect", test_set_auto_reconnect)
# Test: setDevice (with a test device name)
def test_set_device():
response = api.send_command("io.driver.uart.setDevice", {"device": "COM1"})
passed, msg = assert_success(response, "setDevice")
if not passed:
return False, msg
return True, ""
run_test(suite, "io.driver.uart.setDevice registers device", test_set_device)
# Test: setDevice empty
def test_set_device_empty():
response = api.send_command("io.driver.uart.setDevice", {"device": ""})
return assert_error(response, ErrorCode.INVALID_PARAM, "setDevice_empty")
run_test(suite, "io.driver.uart.setDevice rejects empty device", test_set_device_empty)
# =============================================================================
# Network Handler Tests
# =============================================================================
def test_bluetoothle_handler(api: SerialStudioAPI, suite: TestSuite):
"""Test io.driver.ble.* commands."""
print("\n--- Bluetooth LE Handler Tests ---")
# Test: getStatus
def test_get_status():
response = api.send_command("io.driver.ble.getStatus")
passed, msg = assert_success(response, "getStatus")
if not passed:
return False, msg
result = response.get("result", {})
expected_fields = ["operatingSystemSupported", "adapterAvailable", "isOpen", "deviceCount"]
for field in expected_fields:
if field not in result:
return False, f"Missing field: {field}"
return True, ""
run_test(suite, "io.driver.ble.getStatus returns status", test_get_status)
# Test: getConfiguration
def test_get_configuration():
response = api.send_command("io.driver.ble.getConfiguration")
passed, msg = assert_success(response, "getConfiguration")
if not passed:
return False, msg
result = response.get("result", {})
expected_fields = ["deviceIndex", "characteristicIndex", "isOpen", "configurationOk"]
for field in expected_fields:
if field not in result:
return False, f"Missing field: {field}"
return True, ""
run_test(suite, "io.driver.ble.getConfiguration returns config", test_get_configuration)
# Test: getDeviceList
def test_get_device_list():
response = api.send_command("io.driver.ble.getDeviceList")
passed, msg = assert_success(response, "getDeviceList")
if not passed:
return False, msg
result = response.get("result", {})
if "deviceList" not in result:
return False, "Missing deviceList field"
return True, ""
run_test(suite, "io.driver.ble.getDeviceList returns device list", test_get_device_list)
# Test: getServiceList
def test_get_service_list():
response = api.send_command("io.driver.ble.getServiceList")
passed, msg = assert_success(response, "getServiceList")
if not passed:
return False, msg
result = response.get("result", {})
if "serviceList" not in result:
return False, "Missing serviceList field"
return True, ""
run_test(suite, "io.driver.ble.getServiceList returns service list", test_get_service_list)
# Test: getCharacteristicList
def test_get_characteristic_list():
response = api.send_command("io.driver.ble.getCharacteristicList")
passed, msg = assert_success(response, "getCharacteristicList")
if not passed:
return False, msg
result = response.get("result", {})
if "characteristicList" not in result:
return False, "Missing characteristicList field"
return True, ""
run_test(suite, "io.driver.ble.getCharacteristicList returns list", test_get_characteristic_list)
def test_csv_export_handler(api: SerialStudioAPI, suite: TestSuite):
"""Test csv.export.* commands."""
print("\n--- CSV Export Handler Tests ---")
# Test: getStatus
def test_get_status():
response = api.send_command("csv.export.getStatus")
passed, msg = assert_success(response, "getStatus")
if not passed:
return False, msg
result = response.get("result", {})
expected_fields = ["enabled", "isOpen"]
for field in expected_fields:
if field not in result:
return False, f"Missing field: {field}"
return True, ""
run_test(suite, "csv.export.getStatus returns status", test_get_status)
# Test: setEnabled
def test_set_enabled():
response = api.send_command("csv.export.setEnabled", {"enabled": True})
passed, msg = assert_success(response, "setEnabled")
if not passed:
return False, msg
# Restore to false
api.send_command("csv.export.setEnabled", {"enabled": False})
return True, ""
run_test(suite, "csv.export.setEnabled sets export state", test_set_enabled)
# Test: setEnabled missing param
def test_set_enabled_missing():
response = api.send_command("csv.export.setEnabled", {})
return assert_error(response, ErrorCode.MISSING_PARAM, "setEnabled_missing")
run_test(suite, "csv.export.setEnabled requires enabled param", test_set_enabled_missing)
# Test: close
def test_close():
response = api.send_command("csv.export.close")
passed, msg = assert_success(response, "close")
if not passed:
return False, msg
return True, ""
run_test(suite, "csv.export.close executes", test_close)
def test_csv_player_handler(api: SerialStudioAPI, suite: TestSuite):
"""Test csv.player.* commands."""
print("\n--- CSV Player Handler Tests ---")
# Test: getStatus
def test_get_status():
response = api.send_command("csv.player.getStatus")
passed, msg = assert_success(response, "getStatus")
if not passed:
return False, msg
result = response.get("result", {})
expected_fields = ["isOpen", "isPlaying"]
for field in expected_fields:
if field not in result:
return False, f"Missing field: {field}"
return True, ""
run_test(suite, "csv.player.getStatus returns status", test_get_status)
# Test: close (should succeed even if nothing is open)
def test_close():
response = api.send_command("csv.player.close")
passed, msg = assert_success(response, "close")
if not passed:
return False, msg
return True, ""
run_test(suite, "csv.player.close executes", test_close)
# Test: pause (should work even if not playing)
def test_pause():
response = api.send_command("csv.player.pause")
passed, msg = assert_success(response, "pause")
if not passed:
return False, msg
return True, ""
run_test(suite, "csv.player.pause executes", test_pause)
def test_console_handler(api: SerialStudioAPI, suite: TestSuite):
"""Test console.* commands."""
print("\n--- Console Handler Tests ---")
# Test: getConfiguration
def test_get_configuration():
response = api.send_command("console.getConfiguration")
passed, msg = assert_success(response, "getConfiguration")
if not passed:
return False, msg
result = response.get("result", {})
expected_fields = ["echo", "showTimestamp", "displayMode", "dataMode"]
for field in expected_fields:
if field not in result:
return False, f"Missing field: {field}"
return True, ""
run_test(suite, "console.getConfiguration returns config", test_get_configuration)
# Test: setEcho
def test_set_echo():
response = api.send_command("console.setEcho", {"enabled": True})
passed, msg = assert_success(response, "setEcho")
if not passed:
return False, msg
# Restore to default
api.send_command("console.setEcho", {"enabled": False})
return True, ""
run_test(suite, "console.setEcho sets echo mode", test_set_echo)
# Test: setEcho missing param
def test_set_echo_missing():
response = api.send_command("console.setEcho", {})
return assert_error(response, ErrorCode.MISSING_PARAM, "setEcho_missing")
run_test(suite, "console.setEcho requires enabled param", test_set_echo_missing)
# Test: setShowTimestamp
def test_set_show_timestamp():
response = api.send_command("console.setShowTimestamp", {"enabled": True})
passed, msg = assert_success(response, "setShowTimestamp")
if not passed:
return False, msg
return True, ""
run_test(suite, "console.setShowTimestamp sets timestamp mode", test_set_show_timestamp)