-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
1942 lines (1659 loc) · 59.8 KB
/
Copy pathtest_cli.py
File metadata and controls
1942 lines (1659 loc) · 59.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
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
import subprocess
import json
from pathlib import Path
from types import SimpleNamespace
from pyspatialml import cli as cli_module
from pyspatialml.litert_tools import LiteRTCli, LiteRTToolError
REPO_ROOT = Path(__file__).resolve().parents[1]
FACE_MODEL = REPO_ROOT / "tests" / "data" / "face_mediapipe_package" / "model" / "face_detector.tflite"
def _create_cli_run_package(tmp_path, pipeline, *, pipeline_id="main"):
package = tmp_path / f"{pipeline.stem}-package"
assert cli_module.main(
[
"package",
"create",
"--id",
"run-demo",
"--pipeline",
f"{pipeline_id}={pipeline}",
"--output",
str(package),
]
) == 0
return package
def test_tools_litert_status_prints_resolved_cli(monkeypatch, capsys, tmp_path):
class _FakeLiteRT:
path = tmp_path / "bin" / "litert"
managed = False
def version(self):
return "litert 2.0.3"
litert = _FakeLiteRT()
monkeypatch.setattr(cli_module, "resolve_litert_cli", lambda cache_dir=None: litert)
exit_code = cli_module.main(["tools", "litert", "status", "--tool-cache", str(tmp_path)])
captured = capsys.readouterr()
assert exit_code == 0
assert f"LiteRT CLI: {litert.path}" in captured.out
assert "Source: system" in captured.out
assert "Version: litert 2.0.3" in captured.out
assert f"Managed cache: {tmp_path}" in captured.out
def test_tools_litert_status_json(monkeypatch, capsys, tmp_path):
class _FakeLiteRT:
path = tmp_path / "bin" / "litert"
managed = False
def version(self):
return "litert 2.0.3"
monkeypatch.setattr(cli_module, "resolve_litert_cli", lambda cache_dir=None: _FakeLiteRT())
exit_code = cli_module.main(["tools", "litert", "status", "--tool-cache", str(tmp_path), "--json"])
payload = json.loads(capsys.readouterr().out)
assert exit_code == 0
assert payload["ok"] is True
assert payload["command"] == "tools litert status"
assert payload["source"] == "system"
assert payload["version"] == "litert 2.0.3"
def test_tools_litert_status_format_json_alias(monkeypatch, capsys, tmp_path):
class _FakeLiteRT:
path = tmp_path / "bin" / "litert"
managed = False
def version(self):
return "litert 2.0.3"
monkeypatch.setattr(cli_module, "resolve_litert_cli", lambda cache_dir=None: _FakeLiteRT())
exit_code = cli_module.main(["tools", "litert", "status", "--tool-cache", str(tmp_path), "--format", "json"])
payload = json.loads(capsys.readouterr().out)
assert exit_code == 0
assert payload["ok"] is True
assert payload["command"] == "tools litert status"
def test_tools_litert_status_reports_missing_tool(monkeypatch, capsys, tmp_path):
def _raise_missing(cache_dir=None):
raise LiteRTToolError("missing litert")
monkeypatch.setattr(cli_module, "resolve_litert_cli", _raise_missing)
exit_code = cli_module.main(["tools", "litert", "status", "--tool-cache", str(tmp_path)])
captured = capsys.readouterr()
assert exit_code == 2
assert "PSM_LITERT_UNAVAILABLE" in captured.err
assert "missing litert" in captured.err
def test_tools_litert_status_json_reports_missing_tool(monkeypatch, capsys, tmp_path):
def _raise_missing(cache_dir=None):
raise LiteRTToolError("missing litert")
monkeypatch.setattr(cli_module, "resolve_litert_cli", _raise_missing)
exit_code = cli_module.main(["tools", "litert", "status", "--tool-cache", str(tmp_path), "--json"])
payload = json.loads(capsys.readouterr().err)
assert exit_code == 2
assert payload["ok"] is False
assert payload["error"]["code"] == "PSM_LITERT_UNAVAILABLE"
assert payload["error"]["category"] == "litert_tool"
assert payload["error"]["message"] == "missing litert"
def test_tools_litert_install_uses_requested_package_and_version(monkeypatch, capsys, tmp_path):
calls = []
litert = LiteRTCli(path=tmp_path / "litert-cli" / "bin" / "litert", managed=True)
def _install_litert_cli(*, cache_dir=None, package="", version="", force=False):
calls.append((cache_dir, package, version, force))
return litert
monkeypatch.setattr(cli_module, "install_litert_cli", _install_litert_cli)
exit_code = cli_module.main(
[
"tools",
"litert",
"install",
"--tool-cache",
str(tmp_path),
"--package",
"ai-edge-litert-nightly",
"--version",
"9.9.9",
]
)
captured = capsys.readouterr()
assert exit_code == 0
assert calls == [(tmp_path, "ai-edge-litert-nightly", "9.9.9", False)]
assert f"LiteRT CLI installed: {litert.path}" in captured.out
def test_tools_litert_install_force_recreates_managed_env(monkeypatch, capsys, tmp_path):
calls = []
litert = LiteRTCli(path=tmp_path / "litert-cli" / "bin" / "litert", managed=True)
def _install_litert_cli(*, cache_dir=None, package="", version="", force=False):
calls.append((cache_dir, package, version, force))
return litert
monkeypatch.setattr(cli_module, "install_litert_cli", _install_litert_cli)
exit_code = cli_module.main(["tools", "litert", "install", "--tool-cache", str(tmp_path), "--force"])
captured = capsys.readouterr()
assert exit_code == 0
assert calls == [(tmp_path, "litert-cli", "0.1.0", True)]
assert f"LiteRT CLI installed: {litert.path}" in captured.out
def test_tools_litert_repair_recreates_managed_env(monkeypatch, capsys, tmp_path):
calls = []
litert = LiteRTCli(path=tmp_path / "litert-cli" / "bin" / "litert", managed=True)
def _repair_litert_cli(*, cache_dir=None, package="", version=""):
calls.append((cache_dir, package, version))
return litert
monkeypatch.setattr(cli_module, "repair_litert_cli", _repair_litert_cli)
exit_code = cli_module.main(["tools", "litert", "repair", "--tool-cache", str(tmp_path), "--json"])
payload = json.loads(capsys.readouterr().out)
assert exit_code == 0
assert calls == [(tmp_path, "litert-cli", "0.1.0")]
assert payload["command"] == "tools litert repair"
assert payload["recreated"] is True
def test_compare_command_passes(capsys, tmp_path):
expected = tmp_path / "expected.npy"
actual = tmp_path / "actual.npy"
import numpy as np
np.save(expected, np.array([1.0, 2.0], dtype=np.float32))
np.save(actual, np.array([1.0, 2.0], dtype=np.float32))
assert cli_module.main(["compare", str(expected), str(actual)]) == 0
captured = capsys.readouterr()
assert "passed: yes" in captured.out
def test_compare_command_mismatch_returns_compare_code(capsys, tmp_path):
expected = tmp_path / "expected.npy"
actual = tmp_path / "actual.npy"
import numpy as np
np.save(expected, np.array([1.0], dtype=np.float32))
np.save(actual, np.array([2.0], dtype=np.float32))
assert cli_module.main(["compare", str(expected), str(actual), "--rtol", "1e-6", "--atol", "1e-6"]) == 4
captured = capsys.readouterr()
assert "passed: no" in captured.out
def test_compare_command_reports_errors(capsys, tmp_path):
expected = tmp_path / "expected.bin"
actual = tmp_path / "actual.bin"
expected.write_bytes(b"1")
actual.write_bytes(b"1")
assert cli_module.main(["compare", str(expected), str(actual)]) == 1
captured = capsys.readouterr()
assert "PSM_COMPARE" in captured.err
assert "Only .npy files" in captured.err
def test_model_command_delegates_to_litert_with_remainder_separator(monkeypatch, tmp_path):
litert = LiteRTCli(path=tmp_path / "bin" / "litert", managed=False)
resolve_calls = []
subprocess_calls = []
def _resolve_litert_cli(*, ensure=False, cache_dir=None):
resolve_calls.append((ensure, cache_dir))
return litert
def _run(argv, env=None):
subprocess_calls.append(argv)
return subprocess.CompletedProcess(argv, 7)
monkeypatch.setattr(cli_module, "resolve_litert_cli", _resolve_litert_cli)
monkeypatch.setattr(cli_module.subprocess, "run", _run)
exit_code = cli_module.main(
[
"model",
"benchmark",
"--tool-cache",
str(tmp_path),
"--",
"model.tflite",
"--target",
"host",
]
)
assert exit_code == 7
assert resolve_calls == [(True, tmp_path)]
assert subprocess_calls == [[str(litert.path), "benchmark", "model.tflite", "--target", "host"]]
def test_model_command_json_wraps_delegated_litert(monkeypatch, capsys, tmp_path):
litert = LiteRTCli(path=tmp_path / "bin" / "litert", managed=False)
monkeypatch.setattr(cli_module, "resolve_litert_cli", lambda ensure=False, cache_dir=None: litert)
def _run(argv, env=None, text=False, stdout=None, stderr=None):
return subprocess.CompletedProcess(argv, 0, stdout="litert stdout", stderr="litert stderr")
monkeypatch.setattr(cli_module.subprocess, "run", _run)
exit_code = cli_module.main(["model", "benchmark", "--json", "--", "model.tflite"])
payload = json.loads(capsys.readouterr().out)
assert exit_code == 0
assert payload["ok"] is True
assert payload["command"] == "model benchmark"
assert payload["argv"] == [str(litert.path), "benchmark", "model.tflite"]
assert payload["stdout"] == "litert stdout"
assert payload["stderr"] == "litert stderr"
def test_model_convert_help_includes_onnx_and_litert_help(monkeypatch, capsys, tmp_path):
litert = LiteRTCli(path=tmp_path / "bin" / "litert", managed=False)
monkeypatch.setattr(cli_module, "resolve_litert_cli", lambda ensure=False, cache_dir=None: litert)
def _run(argv, env=None, text=False, stdout=None, stderr=None):
return subprocess.CompletedProcess(argv, 0, stdout="Usage: litert convert [OPTIONS] MODEL_OR_SCRIPT\n", stderr="")
monkeypatch.setattr(cli_module.subprocess, "run", _run)
exit_code = cli_module.main(["model", "convert", "--", "--help"])
captured = capsys.readouterr()
assert exit_code == 0
assert "ONNX input:" in captured.out
assert "pyspatialml model convert -- model.onnx --output ./converted_tflite" in captured.out
assert "--input-shape NAME:DIMS" in captured.out
assert "--onnx2tf-arg VALUE" in captured.out
assert "LiteRT convert help:" in captured.out
assert "Usage: litert convert" in captured.out
def test_model_convert_help_json_includes_onnx_and_litert_help(monkeypatch, capsys, tmp_path):
litert = LiteRTCli(path=tmp_path / "bin" / "litert", managed=False)
monkeypatch.setattr(cli_module, "resolve_litert_cli", lambda ensure=False, cache_dir=None: litert)
def _run(argv, env=None, text=False, stdout=None, stderr=None):
return subprocess.CompletedProcess(argv, 0, stdout="Usage: litert convert [OPTIONS] MODEL_OR_SCRIPT\n", stderr="")
monkeypatch.setattr(cli_module.subprocess, "run", _run)
exit_code = cli_module.main(["model", "convert", "--json", "--", "--help"])
payload = json.loads(capsys.readouterr().out)
assert exit_code == 0
assert payload["ok"] is True
assert payload["command"] == "model convert"
assert "ONNX input:" in payload["stdout"]
assert "--no-large-tensor" in payload["stdout"]
assert "Usage: litert convert" in payload["stdout"]
def test_model_convert_routes_onnx_without_litert(monkeypatch, capsys, tmp_path):
model = tmp_path / "model.onnx"
output = tmp_path / "converted"
model.write_bytes(b"onnx")
calls = []
def _resolve_litert_cli(*_args, **_kwargs):
raise AssertionError("ONNX convert should not resolve LiteRT")
def _convert_onnx_to_tflite(**kwargs):
calls.append(kwargs)
tflite = output / "model.tflite"
tflite.parent.mkdir()
tflite.write_bytes(b"tflite")
return SimpleNamespace(
model=kwargs["model"],
output=kwargs["output"],
tflite_models=[tflite],
argv=["onnx2tf", "-i", str(model), "-o", str(output)],
stdout="stdout",
stderr="stderr",
tool=SimpleNamespace(path=tmp_path / "onnx2tf", managed=True),
)
monkeypatch.setattr(cli_module, "resolve_litert_cli", _resolve_litert_cli)
monkeypatch.setattr(cli_module.onnx_tools, "convert_onnx_to_tflite", _convert_onnx_to_tflite)
exit_code = cli_module.main(["model", "convert", "--", str(model), "--output", str(output), "--verbosity", "debug"])
captured = capsys.readouterr()
assert exit_code == 0
assert calls == [
{
"model": model,
"output": output,
"extra_args": ["--verbosity", "debug"],
"cache_dir": None,
"verbose": True,
}
]
assert f"Converted ONNX model: {model}" in captured.out
assert f"TFLite model: {output / 'model.tflite'}" in captured.out
assert "stderr" in captured.err
def test_model_convert_routes_onnx_json(monkeypatch, capsys, tmp_path):
model = tmp_path / "model.onnx"
output = tmp_path / "converted"
model.write_bytes(b"onnx")
def _convert_onnx_to_tflite(**kwargs):
tflite = output / "model.tflite"
return SimpleNamespace(
model=kwargs["model"],
output=kwargs["output"],
tflite_models=[tflite],
argv=["onnx2tf", "-i", str(model), "-o", str(output)],
stdout="stdout",
stderr="stderr",
tool=SimpleNamespace(path=tmp_path / "onnx2tf", managed=True),
)
monkeypatch.setattr(cli_module.onnx_tools, "convert_onnx_to_tflite", _convert_onnx_to_tflite)
exit_code = cli_module.main(["model", "convert", "--json", "--", str(model), "--output", str(output)])
payload = json.loads(capsys.readouterr().out)
assert exit_code == 0
assert payload["ok"] is True
assert payload["converter"] == "onnx2tf"
assert payload["model"] == str(model)
assert payload["output"] == str(output)
assert payload["tflite_models"] == [str(output / "model.tflite")]
def test_model_convert_translates_onnx_alias_flags(monkeypatch, tmp_path):
model = tmp_path / "model.onnx"
output = tmp_path / "converted"
model.write_bytes(b"onnx")
calls = []
def _convert_onnx_to_tflite(**kwargs):
calls.append(kwargs)
return SimpleNamespace(
model=kwargs["model"],
output=kwargs["output"],
tflite_models=[output / "model.tflite"],
argv=[],
stdout="",
stderr="",
tool=SimpleNamespace(path=tmp_path / "onnx2tf", managed=True),
)
monkeypatch.setattr(cli_module.onnx_tools, "convert_onnx_to_tflite", _convert_onnx_to_tflite)
assert cli_module.main(
[
"model",
"convert",
"--",
str(model),
"--output",
str(output),
"--input-shape",
"images:1,3,640,640",
"--shape-hint=tokens:1,128",
"--no-large-tensor",
"--keep-nchw",
"images",
"--keep-nhwc=features",
"--non-verbose",
"--copy-input-output-names",
"--dynamic-range-quantize",
"--integer-quantize",
"--onnx2tf-arg",
"--disable_strict_mode",
"--onnx2tf-arg=--output_nms_with_dynamic_tensor",
]
) == 0
assert calls[0]["extra_args"] == [
"--overwrite_input_shape",
"images:1,3,640,640",
"--shape_hints",
"tokens:1,128",
"--no_large_tensor",
"--keep_ncw_or_nchw_or_ncdhw_input_names",
"images",
"--keep_nwc_or_nhwc_or_ndhwc_input_names",
"features",
"--non_verbose",
"--copy_onnx_input_output_names_to_tflite",
"--output_dynamic_range_quantized_tflite",
"--output_integer_quantized_tflite",
"--disable_strict_mode",
"--output_nms_with_dynamic_tensor",
]
def test_model_convert_onnx_alias_requires_value(capsys, tmp_path):
model = tmp_path / "model.onnx"
output = tmp_path / "converted"
model.write_bytes(b"onnx")
exit_code = cli_module.main(["model", "convert", "--", str(model), "--output", str(output), "--input-shape"])
captured = capsys.readouterr()
assert exit_code == 1
assert "PSM_ONNX_CONVERT" in captured.err
assert "--input-shape requires a value" in captured.err
def test_model_convert_reports_missing_local_model_before_litert(capsys, tmp_path):
missing = tmp_path / "model.onn"
output = tmp_path / "model.tflite"
exit_code = cli_module.main(["model", "convert", str(missing), "--output", str(output)])
captured = capsys.readouterr()
assert exit_code == 1
assert "PSM_ONNX_CONVERT" in captured.err
assert f"Model input file not found: {missing}" in captured.err
assert "Pass an existing model file" in captured.err
def test_model_convert_allows_non_path_model_names(monkeypatch, tmp_path):
litert = SimpleNamespace(path=tmp_path / "litert", managed=False)
calls = []
monkeypatch.setattr(cli_module, "resolve_litert_cli", lambda ensure=False, cache_dir=None: litert)
monkeypatch.setattr(cli_module.subprocess, "run", lambda argv, **kwargs: calls.append((argv, kwargs)) or SimpleNamespace(returncode=0))
assert cli_module.main(["model", "convert", "repo/model-name", "--output", str(tmp_path / "out")]) == 0
assert calls[0][0] == [str(litert.path), "convert", "repo/model-name", "--output", str(tmp_path / "out")]
def test_model_convert_rejects_shape_hint_for_overwritten_input(capsys, tmp_path):
model = tmp_path / "model.onnx"
output = tmp_path / "converted"
model.write_bytes(b"onnx")
exit_code = cli_module.main(
[
"model",
"convert",
"--",
str(model),
"--output",
str(output),
"--input-shape",
"images:1,3,640,640",
"--shape-hint=images:1,3,640,640",
]
)
captured = capsys.readouterr()
assert exit_code == 1
assert "PSM_ONNX_CONVERT" in captured.err
assert "Do not pass both --input-shape and --shape-hint" in captured.err
assert "images" in captured.err
def test_model_convert_allows_shape_hint_for_different_input(monkeypatch, tmp_path):
model = tmp_path / "model.onnx"
output = tmp_path / "converted"
model.write_bytes(b"onnx")
calls = []
def _convert_onnx_to_tflite(**kwargs):
calls.append(kwargs)
return SimpleNamespace(
model=kwargs["model"],
output=kwargs["output"],
tflite_models=[output / "model.tflite"],
argv=[],
stdout="",
stderr="",
tool=SimpleNamespace(path=tmp_path / "onnx2tf", managed=True),
)
monkeypatch.setattr(cli_module.onnx_tools, "convert_onnx_to_tflite", _convert_onnx_to_tflite)
assert cli_module.main(
[
"model",
"convert",
"--",
str(model),
"--output",
str(output),
"--input-shape=images:1,3,640,640",
"--shape-hint",
"tokens:1,128",
]
) == 0
assert calls[0]["extra_args"] == [
"--overwrite_input_shape",
"images:1,3,640,640",
"--shape_hints",
"tokens:1,128",
]
def test_model_info_command_prints_model_metadata(capsys):
assert cli_module.main(["model", "info", str(FACE_MODEL)]) == 0
captured = capsys.readouterr()
assert "Inputs:" in captured.out
assert "image: shape=(1, 256, 256, 3) dtype=float32 index=0" in captured.out
assert "box_coords_1: shape=(1, 512, 16) dtype=float32" in captured.out
def test_model_info_command_reports_missing_model(capsys, tmp_path):
exit_code = cli_module.main(["model", "info", str(tmp_path / "missing.tflite")])
captured = capsys.readouterr()
assert exit_code == 1
assert "PSM_MODEL" in captured.err
assert "Model file not found" in captured.err
def test_operator_list_command(capsys):
assert cli_module.main(["operator", "list"]) == 0
captured = capsys.readouterr()
assert "Operators:" in captured.out
assert "ARITHMETIC_COMPOSE" in captured.out
assert "creator=arithmetic" in captured.out
def test_operator_describe_command(capsys):
assert cli_module.main(["operator", "describe-op", "arithmetic"]) == 0
captured = capsys.readouterr()
assert "Operator: ARITHMETIC_COMPOSE" in captured.out
assert "Creator: arithmetic" in captured.out
def test_operator_describe_command_reports_unknown(capsys):
exit_code = cli_module.main(["operator", "describe-op", "missing"])
captured = capsys.readouterr()
assert exit_code == 1
assert "PSM_OPERATOR" in captured.err
assert "Unknown operator" in captured.err
def test_visualize_model_delegates_to_litert(monkeypatch, tmp_path):
litert = LiteRTCli(path=tmp_path / "bin" / "litert", managed=False)
subprocess_calls = []
resolve_calls = []
def _resolve_litert_cli(*, ensure=False, cache_dir=None):
resolve_calls.append((ensure, cache_dir))
return litert
monkeypatch.setattr(cli_module, "resolve_litert_cli", _resolve_litert_cli)
subprocess_envs = []
def _run(argv, env=None):
subprocess_calls.append(argv)
subprocess_envs.append(env)
return subprocess.CompletedProcess(argv, 0)
monkeypatch.setattr(
cli_module.subprocess,
"run",
_run,
)
exit_code = cli_module.main(["visualize", "model", "model.tflite", "--output", "model.html"])
assert exit_code == 0
assert resolve_calls == [(True, None)]
assert subprocess_calls == [[str(litert.path), "visualize", "model.tflite", "--output", "model.html"]]
assert subprocess_envs[0]["UV_SYSTEM_CERTS"] == "true"
def test_called_process_error_is_reported(monkeypatch, capsys, tmp_path):
litert = LiteRTCli(path=tmp_path / "bin" / "litert", managed=False)
monkeypatch.setattr(cli_module, "resolve_litert_cli", lambda ensure=False, cache_dir=None: litert)
def _run(_argv, env=None):
raise subprocess.CalledProcessError(
4,
"litert run",
output="stdout message\n",
stderr="stderr message\n",
)
monkeypatch.setattr(cli_module.subprocess, "run", _run)
exit_code = cli_module.main(["model", "run", "model.tflite"])
captured = capsys.readouterr()
assert exit_code == 4
assert "stdout message" in captured.out
assert "stderr message" in captured.err
def test_pipeline_builder_commands_create_validate_and_inspect_pipeline(capsys, tmp_path):
pipeline = tmp_path / "pipeline.json"
assert cli_module.main(["pipeline", "init", str(pipeline)]) == 0
assert cli_module.main(
[
"pipeline",
"add-tensor",
str(pipeline),
"image",
"--shape",
"2,3",
"--dtype",
"uint8",
"--input",
]
) == 0
assert cli_module.main(
[
"pipeline",
"add-tensor",
str(pipeline),
"image_f32",
"--shape",
"2,3",
"--dtype",
"float32",
]
) == 0
assert cli_module.main(
[
"pipeline",
"add-tensor",
str(pipeline),
"normalized",
"--shape",
"2,3",
"--dtype",
"float32",
"--output",
]
) == 0
assert cli_module.main(
[
"pipeline",
"add-op",
str(pipeline),
"assignment",
"--input",
"image",
"--output",
"image_f32",
]
) == 0
assert cli_module.main(
[
"pipeline",
"add-op",
str(pipeline),
"arithmetic",
"--input",
"image_f32",
"--output",
"normalized",
"--expression",
"{0} / 255.0",
]
) == 0
assert cli_module.main(["pipeline", "set-input", str(pipeline), "image"]) == 0
assert cli_module.main(["pipeline", "set-output", str(pipeline), "normalized"]) == 0
assert cli_module.main(["pipeline", "validate", str(pipeline)]) == 0
assert cli_module.main(["pipeline", "inspect", str(pipeline)]) == 0
captured = capsys.readouterr()
spec = json.loads(pipeline.read_text(encoding="utf-8"))
assert spec["inputs"] == ["image"]
assert spec["outputs"] == ["normalized"]
assert len(spec["operators"]) == 2
assert spec["operators"][1]["expression"] == "{0} / 255.0"
assert "Pipeline is valid" in captured.out
assert "Operators: 2" in captured.out
def test_pipeline_add_op_arithmetic_requires_expression(capsys, tmp_path):
pipeline = tmp_path / "pipeline.json"
assert cli_module.main(["pipeline", "init", str(pipeline)]) == 0
assert cli_module.main(
["pipeline", "add-tensor", str(pipeline), "x", "--shape", "2,2", "--dtype", "float32", "--input"]
) == 0
assert cli_module.main(
["pipeline", "add-tensor", str(pipeline), "y", "--shape", "2,2", "--dtype", "float32", "--output"]
) == 0
exit_code = cli_module.main(["pipeline", "add-op", str(pipeline), "arithmetic", "--input", "x", "--output", "y"])
captured = capsys.readouterr()
assert exit_code == 1
assert "PSM_PIPELINE" in captured.err
assert "Arithmetic operators require --expression" in captured.err
def test_pipeline_add_op_javascript_requires_code(capsys, tmp_path):
pipeline = tmp_path / "pipeline.json"
assert cli_module.main(["pipeline", "init", str(pipeline)]) == 0
assert cli_module.main(
["pipeline", "add-tensor", str(pipeline), "x", "--shape", "2,2", "--dtype", "float32", "--input"]
) == 0
assert cli_module.main(
["pipeline", "add-tensor", str(pipeline), "y", "--shape", "2,2", "--dtype", "float32", "--output"]
) == 0
exit_code = cli_module.main(["pipeline", "add-op", str(pipeline), "javascript", "--input", "x", "--output", "y"])
captured = capsys.readouterr()
assert exit_code == 1
assert "PSM_PIPELINE" in captured.err
assert "javascript operators require --attr with JavaScript code" in captured.err
def test_pipeline_add_op_convert_color_requires_input(capsys, tmp_path):
pipeline = tmp_path / "pipeline.json"
assert cli_module.main(["pipeline", "init", str(pipeline)]) == 0
assert cli_module.main(
["pipeline", "add-tensor", str(pipeline), "y", "--shape", "2,2,3", "--dtype", "uint8", "--output"]
) == 0
exit_code = cli_module.main(["pipeline", "add-op", str(pipeline), "convert_color", "--output", "y", "--flag", "4"])
captured = capsys.readouterr()
assert exit_code == 1
assert "PSM_PIPELINE" in captured.err
assert "convert_color operators require exactly 1 input" in captured.err
def test_pipeline_commands_json_output(capsys, tmp_path):
pipeline = tmp_path / "pipeline.json"
assert cli_module.main(["pipeline", "init", str(pipeline), "--json"]) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["ok"] is True
assert payload["command"] == "pipeline.init"
assert payload["pipeline"] == str(pipeline)
assert cli_module.main(
[
"pipeline",
"add-tensor",
str(pipeline),
"x",
"--shape",
"2,2",
"--dtype",
"float32",
"--input",
"--json",
]
) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["command"] == "pipeline.add_tensor"
assert payload["tensor"] == "x"
assert cli_module.main(["pipeline", "remove-tensor", str(pipeline), "x", "--json"]) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["command"] == "pipeline.remove_tensor"
assert payload["tensor"] == "x"
assert payload["force"] is False
assert cli_module.main(
[
"pipeline",
"add-tensor",
str(pipeline),
"x",
"--shape",
"2,2",
"--dtype",
"float32",
"--input",
]
) == 0
assert cli_module.main(
[
"pipeline",
"add-tensor",
str(pipeline),
"y",
"--shape",
"2,2",
"--dtype",
"float32",
"--output",
]
) == 0
assert cli_module.main(
[
"pipeline",
"add-op",
str(pipeline),
"assignment",
"--input",
"x",
"--output",
"y",
]
) == 0
capsys.readouterr()
assert cli_module.main(["pipeline", "remove-op", str(pipeline), "--index", "0", "--json"]) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["command"] == "pipeline.remove_op"
assert payload["index"] == 0
assert cli_module.main(["pipeline", "inspect", str(pipeline), "--json"]) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["command"] == "pipeline.inspect"
assert payload["tensors"] == 2
assert payload["operators"] == 0
assert payload["inputs"] == ["x"]
def test_pipeline_add_op_model_writes_inline_litert_metadata(tmp_path):
pipeline = tmp_path / "pipeline.json"
assert cli_module.main(["pipeline", "init", str(pipeline)]) == 0
assert cli_module.main(
[
"pipeline",
"add-tensor",
str(pipeline),
"input",
"--shape",
"1,4",
"--dtype",
"float32",
"--input",
]
) == 0
assert cli_module.main(
[
"pipeline",
"add-tensor",
str(pipeline),
"scores",
"--shape",
"1,2",
"--dtype",
"float32",
"--output",
]
) == 0
assert cli_module.main(
[
"pipeline",
"add-op",
str(pipeline),
"run_model_inference",
"--input",
"input",
"--output",
"scores",
"--model",
"model/demo.tflite",
"--model-name",
"demo",
]
) == 0
op = json.loads(pipeline.read_text(encoding="utf-8"))["operators"][0]
assert op["model_type"] == "tflite"
assert op["model"]["bin_path"] == "model/demo.tflite"
assert "model_file" not in op
assert "model_asset" not in op
assert "model_id" not in op
def test_pipeline_add_op_accepts_spatial_only_aliases(tmp_path):
pipeline = tmp_path / "pipeline.json"
assert cli_module.main(["pipeline", "init", str(pipeline)]) == 0
assert cli_module.main(
["pipeline", "add-tensor", str(pipeline), "scene", "--shape", "1,1", "--dtype", "uint8"]
) == 0
assert cli_module.main(
["pipeline", "add-tensor", str(pipeline), "scale", "--shape", "1,3", "--dtype", "float32"]
) == 0
assert cli_module.main(
[
"pipeline",
"add-op",
str(pipeline),
"scenegraph_visibility",
"--input",
"scene",
"--attr",
"false",
]
) == 0
assert cli_module.main(
[
"pipeline",
"add-op",
str(pipeline),
"update_component",
"--input",
"scene",
"--input",
"scale",
"--entity-path",
"/target",
"--property",
"Transform.Scale",
]
) == 0
operators = json.loads(pipeline.read_text(encoding="utf-8"))["operators"]
assert operators[0]["type"] == "XR_SECURE_MR_OPERATOR_TYPE_SCENEGRAPH_VISIBILITY_PICO"
assert operators[0]["visible"] is False
assert operators[1]["type"] == "XR_SECURE_MR_OPERATOR_TYPE_UPDATE_COMPONENT_PICO"
assert operators[1]["data"] == "scale"
assert operators[1]["entity_path"] == "/target"
assert operators[1]["property"] == "Transform.Scale"
def test_pipeline_command_reports_builder_errors(capsys, tmp_path):
missing = tmp_path / "missing.json"
exit_code = cli_module.main(["pipeline", "validate", str(missing)])
captured = capsys.readouterr()
assert exit_code == 1
assert "PSM_PIPELINE" in captured.err
assert "Pipeline not found" in captured.err