Repository navigation
Expand file tree
/
Copy pathtest_venv_diagnostics.py
More file actions
1381 lines (1237 loc) · 49.6 KB
/
Copy pathtest_venv_diagnostics.py
File metadata and controls
1381 lines (1237 loc) · 49.6 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
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
"""Tests for venv self-check diagnostics."""
from __future__ import annotations
import os
import subprocess
import sys
from unittest.mock import MagicMock, patch
from typing import Any
import pytest
from plugin.scripting.venv_diagnostics import (
GroupResult,
ProbeReport,
_AUDIO_OPTIONAL_KEYS,
_AUDIO_PACKAGE_KEYS,
_AUDIO_PROBE_SCRIPT,
_DUCKDB_PROBE_SCRIPT,
_NEMOTRON_RUNTIME_ERROR_KEY,
_NLP_PROBE_SCRIPT,
_OCR_ENGINE_KEYS,
_OCR_ENGINE_PROBE_BODY,
_UI_PACKAGE_KEYS,
_UI_PROBE_SCRIPT,
_VECTOR_SEARCH_PROBE_SCRIPT,
_VISION_OPTIONAL_KEYS,
_VISION_PACKAGE_KEYS,
_VISION_PROBE_SCRIPT,
_import_probe_script,
_import_try_block,
_parse_probe_stdout,
_run_named_json_probe,
probe_venv_path_with_progress,
run_venv_self_check_with_progress,
)
orig_named_probe = _run_named_json_probe
def test_probe_venv_path_with_progress_not_directory():
shown: list[str] = []
ok, msg = probe_venv_path_with_progress(__file__, shown.append)
assert ok is False
assert "Not a Python executable" in msg
assert shown == [msg]
def test_probe_venv_path_with_progress_blank_uses_process_python():
shown: list[str] = []
with patch("plugin.scripting.venv_diagnostics.resolve_libreoffice_python", return_value="/fake/lo/python") as mock_res:
with patch("plugin.scripting.venv_diagnostics.run_venv_self_check_with_progress", return_value=(True, "ignored")) as mock_check:
ok, msg = probe_venv_path_with_progress(" ", shown.append)
assert ok is True
assert msg == "LibreOffice process Python (/fake/lo/python) responds OK."
mock_res.assert_called_once()
assert mock_check.call_args.args[0] == "/fake/lo/python"
assert mock_check.call_args.kwargs.get("include_vector_search") is True
assert mock_check.call_args.kwargs.get("include_audio") is True
assert mock_check.call_args.kwargs.get("on_status") is None
assert mock_check.call_args.kwargs.get("extra_lines_after_header") is None
assert "timeout" not in mock_check.call_args.kwargs
def test_probe_venv_path_with_progress_blank_fails_when_no_process_interpreter():
shown: list[str] = []
with patch("plugin.scripting.venv_diagnostics.resolve_libreoffice_python", return_value=None):
ok, msg = probe_venv_path_with_progress("", shown.append)
assert ok is False
assert msg.startswith("No process interpreter:")
assert shown == [msg]
@pytest.mark.integration
def test_run_venv_self_check_with_progress_success():
ok, msg = run_venv_self_check_with_progress(sys.executable, lambda text: None)
assert ok is True
assert "responds OK." in msg
@pytest.mark.parametrize(
"value, value_2",
[
pytest.param("nope", "nope", id="test_run_venv_self_check_with_progress_worker_error_response"),
pytest.param("Python worker failed: Command timed out after 1 seconds", "Timed out", id="test_run_venv_self_check_with_progress_timeout"),
],
)
def test_run_venv_self_check_with_progress_worker_error_response(value, value_2):
mock_mgr = MagicMock()
mock_mgr.execute.return_value = {"status": "error", "message": value}
shown: list[str] = []
with patch("plugin.scripting.venv_worker.PythonWorkerManager.get", return_value=mock_mgr):
ok, msg = run_venv_self_check_with_progress("/x/python", shown.append)
assert ok is False
assert value_2 in msg
assert shown == [msg]
def test_run_venv_self_check_with_progress_unexpected_version_is_displayed():
mock_mgr = MagicMock()
mock_mgr.execute.return_value = {"status": "ok", "result": "nope"}
shown: list[str] = []
with patch("plugin.scripting.venv_worker.PythonWorkerManager.get", return_value=mock_mgr):
ok, msg = run_venv_self_check_with_progress("/x/python", shown.append)
assert ok is False
assert msg == "Unexpected output from test run: 'nope'"
assert shown == [msg]
def test_run_venv_self_check_with_progress_package_worker_error_continues():
from plugin.scripting.venv_worker import ExecRequest
mock_mgr = MagicMock()
def _execute(req: ExecRequest):
script = req.code or ""
if "platform" in script:
return {"status": "ok", "result": {"v": "3.12.0", "arch": "x86_64"}}
if "import pandas\n" in script:
return {"status": "error", "message": "died"}
return {"status": "ok", "result": "present"}
mock_mgr.execute.side_effect = _execute
shown: list[str] = []
with (
patch("plugin.scripting.venv_worker.PythonWorkerManager.get", return_value=mock_mgr),
patch("plugin.scripting.venv_diagnostics._run_named_json_probe", return_value=({}, None)),
):
ok, msg = run_venv_self_check_with_progress("/x/python", shown.append, include_audio=False)
assert ok is True
assert "Warning: pandas: died" in msg
assert "Scientific Libraries" in msg
assert "Could not run Python" not in msg
assert shown[-1] == msg
def test_run_venv_self_check_with_progress_reports_architecture():
"""Self-check success message includes platform.machine() from the worker payload."""
import platform
expected_arch = platform.machine()
mock_mgr = MagicMock()
mock_mgr.execute.return_value = {
"status": "ok",
"result": {
"v": "3.12.0",
"arch": expected_arch,
"p": {},
"sci": [],
"eda": [],
"ui": [],
},
}
with (
patch("plugin.scripting.venv_worker.PythonWorkerManager.get", return_value=mock_mgr),
patch(
"plugin.scripting.venv_diagnostics._run_named_json_probe",
side_effect=lambda exe, name, timeout=None: (
({}, None) if name in {"audio", "nlp", "vector_search", "vision"} else orig_named_probe(exe, name)
),
),
):
ok, msg = run_venv_self_check_with_progress("/x/python", lambda text: None)
assert ok is True
assert expected_arch in msg
@pytest.mark.parametrize(
("arch", "expect_paren"),
[("ARM64", True), ("", False)],
)
def test_probe_report_render_header_arch(arch: str, expect_paren: bool) -> None:
msg = ProbeReport(version="3.12.0", arch=arch).render()
first_line = msg.splitlines()[0]
assert "3.12.0" in first_line
assert (f"({arch})" in first_line) is expect_paren
if not expect_paren:
assert "(" not in first_line
def test_probe_report_render_skips_empty_groups_and_shows_failures() -> None:
report = ProbeReport(
version="3.12.0",
packages={"pint": "present"},
groups=[
GroupResult("empty", "Empty Group", packages=()),
GroupResult("data_eng", "Data Engineering Libraries", packages=("pint", "duckdb"), failure="probe timed out"),
],
)
msg = report.render(include_install_footer=True)
assert "Empty Group" not in msg
assert "Data Engineering Libraries" in msg
assert "probe timed out" in msg
@pytest.mark.parametrize(
("include_footer", "packages", "group_specs", "expect_footer", "expected_in_footer", "excluded_from_footer"),
[
pytest.param(
# Mid-Test refresh must not show a partial uv/pip install recipe.
False,
{"numpy": "present", "scipy": None, "sklearn": None},
[("sci", "Scientific Libraries", ("numpy", "scipy", "sklearn"), ())],
False,
(),
(),
id="progressive_omits_footer",
),
pytest.param(
True,
{"numpy": "present", "scipy": "present"},
[("sci", "Scientific Libraries", ("numpy", "scipy"), ())],
False,
(),
(),
id="all_present_omits_footer",
),
pytest.param(
True,
{"numpy": "present", "scipy": None, "sklearn": None, "language_tool_python": None},
[("sci", "Scientific Libraries", ("numpy", "scipy", "sklearn", "language_tool_python"), ("language_tool_python",))],
True,
("scipy", "scikit-learn"),
("language_tool_python", "language-tool-python"),
id="missing_required_shown_optional_excluded",
),
pytest.param(
True,
{"numpy": None, "scipy": None, "docling": None, "rapidocr": None, "onnxruntime": None, "css_inline": None},
[
("sci", "Scientific Libraries", ("numpy", "scipy"), ()),
("vision", "Vision Libraries", ("docling", "rapidocr", "onnxruntime", "css_inline", "numpy"), ()),
],
True,
("numpy", "scipy", '"docling>=2.145"', "rapidocr", "css-inline", "onnxruntime"),
(),
id="multiple_groups_single_deduplicated_footer",
),
],
)
def test_probe_report_install_footer_structure(
include_footer: bool,
packages: dict[str, str | None],
group_specs: list[tuple[str, str, tuple[str, ...], tuple[str, ...]]],
expect_footer: bool,
expected_in_footer: tuple[str, ...],
excluded_from_footer: tuple[str, ...],
) -> None:
report = ProbeReport(
version="3.12.0",
packages=packages,
groups=[
GroupResult(key, title, packages=pkgs, optional_keys=opt)
for key, title, pkgs, opt in group_specs
],
)
msg = report.render(include_install_footer=include_footer)
lines = msg.splitlines()
uv_lines = [line for line in lines if line.startswith("uv pip install ")]
pip_lines = [line for line in lines if line.startswith("pip install ")]
if not expect_footer:
assert not uv_lines
assert not pip_lines
return
assert len(uv_lines) == 1
assert len(pip_lines) == 1
assert lines.index(uv_lines[0]) < lines.index(pip_lines[0])
uv_tokens = uv_lines[0].split()
pip_tokens = pip_lines[0].split()
for pkg in expected_in_footer:
assert uv_tokens.count(pkg) == 1
assert pip_tokens.count(pkg) == 1
for pkg in excluded_from_footer:
assert pkg not in uv_tokens
assert pkg not in pip_tokens
@pytest.mark.parametrize(
("packages", "expect_ready_engine", "expect_footer", "expected_in_footer"),
[
pytest.param(
{"docling": "present", "rapidocr": "present", "onnxruntime": "present", "css_inline": "present"},
"Docling",
False,
(),
id="docling_ready",
),
pytest.param(
{"docling": None, "rapidocr": None, "css_inline": "present", "paddleocr": "present", "paddle": "present"},
"Paddle",
False,
(),
id="paddle_ready_fallback",
),
pytest.param(
{"docling": "present", "rapidocr": None, "onnxruntime": None, "css_inline": "present"},
None,
True,
("rapidocr", "onnxruntime"),
id="docling_without_rapidocr_not_ready",
),
pytest.param(
{"docling": "present", "rapidocr": "present", "onnxruntime": None, "css_inline": "present"},
None,
True,
("onnxruntime",),
id="docling_without_onnxruntime_not_ready",
),
pytest.param(
{
"docling": "present",
"rapidocr": "present",
"onnxruntime": None,
"css_inline": "present",
"paddleocr": "present",
"paddle": "present",
},
None,
True,
("onnxruntime",),
id="docling_paddle_without_onnxruntime_not_ready",
),
pytest.param(
{},
None,
True,
("docling", "rapidocr", "css-inline", "onnxruntime"),
id="all_ocr_missing_not_ready",
),
],
)
def test_probe_report_vision_ocr_structure(
packages: dict[str, str | None],
expect_ready_engine: str | None,
expect_footer: bool,
expected_in_footer: tuple[str, ...],
) -> None:
report = ProbeReport(
version="3.12.0",
packages=packages,
groups=[
GroupResult(
"vision",
"Vision Libraries",
packages=_VISION_PACKAGE_KEYS,
optional_keys=_VISION_OPTIONAL_KEYS,
)
],
)
if expect_ready_engine:
assert report.collect_missing_keys() == []
else:
assert report.collect_missing_keys() != []
msg = report.render(include_install_footer=True)
if expect_ready_engine:
assert f"({expect_ready_engine})" in msg
uv_lines = [line for line in msg.splitlines() if line.startswith("uv pip install ")]
assert bool(uv_lines) is expect_footer
if expect_footer:
for pkg in expected_in_footer:
assert pkg in uv_lines[0]
for opt in ("paddleocr", "ultralytics", "skimage"):
assert opt not in uv_lines[0]
def test_vision_optional_ocr_engines_listed_never_missing():
report = ProbeReport(
version="3.12.0",
packages={
"docling": "present",
"rapidocr": "present",
"onnxruntime": "present",
"css_inline": "present",
"tesseract": "present",
},
groups=[
GroupResult(
"vision",
"Vision Libraries",
packages=_VISION_PACKAGE_KEYS,
optional_keys=_VISION_OPTIONAL_KEYS,
)
],
)
assert report.collect_missing_keys() == []
msg = report.render(include_install_footer=True)
vision_line = next(line for line in msg.splitlines() if line.startswith("Vision Libraries:"))
assert "tesseract" in vision_line
assert "easyocr" not in msg
assert "ocrmac" not in msg
assert "uv pip install " not in msg
@pytest.mark.parametrize(
("backend", "packages", "expect_ready", "expected_lines", "absent_lines"),
[
pytest.param(
"easyocr",
{"docling": "present", "easyocr": "present", "css_inline": "present"},
True,
("OCR: ready (Docling)", "OCR engine: easyocr"),
("Missing (OCR):",),
id="easyocr_present",
),
pytest.param(
"easyocr",
{"docling": "present", "css_inline": "present"},
False,
("OCR: not ready", "OCR engine: easyocr", "Missing (OCR): easyocr", "uv pip install easyocr"),
(),
id="easyocr_missing",
),
pytest.param(
"rapidocr_torch",
{"docling": "present", "rapidocr": "present", "torch": "present", "css_inline": "present"},
True,
("OCR: ready (Docling)", "OCR engine: rapidocr_torch"),
("Missing (OCR):",),
id="rapidocr_torch_present",
),
pytest.param(
"rapidocr_torch",
{"docling": "present", "rapidocr": "present", "css_inline": "present"},
False,
("OCR: not ready", "OCR engine: rapidocr_torch", "Missing (OCR): torch", "uv pip install torch"),
(),
id="rapidocr_torch_missing",
),
pytest.param(
"tesseract",
{"docling": "present", "tesseract": "present", "css_inline": "present"},
True,
("OCR: ready (Docling)", "OCR engine: tesseract"),
("Missing (OCR):",),
id="tesseract_present",
),
pytest.param(
"tesseract",
{"docling": "present", "css_inline": "present"},
False,
("OCR: not ready", "OCR engine: tesseract", "Missing (OCR): tesseract", "Install the Tesseract OCR program"),
("uv pip install",),
id="tesseract_missing",
),
pytest.param(
"nemotron",
{"docling": "present", "nemotron_ocr": "present", "css_inline": "present"},
True,
("OCR: ready (Docling)", "OCR engine: nemotron"),
("Missing (OCR):",),
id="nemotron_present_no_error",
),
pytest.param(
"nemotron",
{
"docling": "present",
"nemotron_ocr": "present",
"css_inline": "present",
_NEMOTRON_RUNTIME_ERROR_KEY: "Nemotron OCR requires CUDA",
},
False,
("OCR: not ready", "OCR engine: nemotron", "Nemotron OCR cannot start in this venv: Nemotron OCR requires CUDA"),
("uv pip install",),
id="nemotron_runtime_error",
),
pytest.param(
"ocrmac",
{"docling": "present", "css_inline": "present"},
False,
("OCR: not ready", "OCR engine: ocrmac", "Missing (OCR): ocrmac", "Apple Vision OCR runs only on macOS"),
("uv pip install",),
id="ocrmac_absent",
),
pytest.param(
"bogus_engine",
{"docling": "present", "css_inline": "present"},
False,
("OCR: not ready", "OCR engine: bogus_engine", "This OCR engine is not known to WriterAgent."),
("Missing (OCR):", "uv pip install"),
id="unknown_engine",
),
pytest.param(
"rapidocr_paddle",
{"docling": "present", "rapidocr": "present", "css_inline": "present"},
False,
("OCR: not ready", "OCR engine: rapidocr_paddle", "Missing (OCR): paddle"),
(),
id="rapidocr_paddle_missing_listed_once",
),
],
)
def test_vision_readiness_by_ocr_backend(backend, packages, expect_ready, expected_lines, absent_lines):
report = ProbeReport(
version="3.12.0",
packages=packages,
groups=[
GroupResult(
"vision",
"Vision Libraries",
packages=_VISION_PACKAGE_KEYS,
optional_keys=_VISION_OPTIONAL_KEYS,
ocr_backend=backend,
)
],
)
if expect_ready:
assert report.collect_missing_keys() == []
msg = report.render(include_install_footer=True)
for fragment in expected_lines:
assert fragment in msg
for fragment in absent_lines:
assert fragment not in msg
if backend == "rapidocr_paddle":
optional_lines = [line for line in msg.splitlines() if line.startswith("Optional (not installed):")]
assert all("paddle" not in line.replace("paddleocr", "") for line in optional_lines)
def test_attach_external_probes_vision_uses_configured_ocr_backend():
from plugin.scripting.venv_diagnostics import _attach_external_probes
report = ProbeReport(version="3.12.0")
with (
patch("plugin.scripting.venv_diagnostics._run_named_json_probe", return_value=({}, None)),
patch("plugin.scripting.venv_diagnostics.merge_vision_params", return_value={"ocr_backend": "easyocr"}),
):
group = _attach_external_probes("/x/python", report, "vision", "Vision Libraries")
assert group.ocr_backend == "easyocr"
@pytest.mark.parametrize(
("packages", "expect_tts_hint", "expect_whisper_hint", "expect_no_mic_hint"),
[
pytest.param(
{"sounddevice": "present", "input_device": "present", "kokoro_onnx": "present", "soundfile": "present", "piper": "present", "faster_whisper": "present"},
False,
False,
False,
id="all_audio_present",
),
pytest.param(
{"sounddevice": "present", "input_device": None, "kokoro_onnx": "present", "soundfile": "present", "piper": "present", "faster_whisper": "present"},
False,
False,
True,
id="no_mic_detected",
),
pytest.param(
{"sounddevice": "present", "input_device": "present", "kokoro_onnx": "present", "soundfile": "present", "piper": "present", "faster_whisper": None},
False,
True,
False,
id="whisper_missing_only",
),
pytest.param(
{"sounddevice": "present", "input_device": "present", "kokoro_onnx": None, "soundfile": "present", "piper": "present", "faster_whisper": "present"},
True,
False,
False,
id="tts_missing_only",
),
],
)
def test_probe_report_audio_structure(
packages: dict[str, str | None],
expect_tts_hint: bool,
expect_whisper_hint: bool,
expect_no_mic_hint: bool,
) -> None:
report = ProbeReport(
version="3.13.0",
packages=packages,
groups=[
GroupResult(
"audio",
"Audio Recording & Speech",
packages=_AUDIO_PACKAGE_KEYS,
optional_keys=_AUDIO_OPTIONAL_KEYS,
)
],
)
msg = report.render(include_install_footer=True)
assert ("Local TTS engines (optional):" in msg) is expect_tts_hint
assert ("Local Whisper (optional):" in msg) is expect_whisper_hint
assert ("No microphone input devices detected." in msg) is expect_no_mic_hint
assert ("input_device" not in msg) is expect_no_mic_hint
uv_lines = [line for line in msg.splitlines() if line.startswith("uv pip install ")]
assert not uv_lines
def test_probe_report_audio_linux_portaudio_hint() -> None:
report = ProbeReport(
version="3.12.0",
packages={"sounddevice": None},
groups=[GroupResult("audio", "Audio Recording & Speech", packages=("sounddevice",))],
)
msg = report.render()
assert ("PortAudio" in msg) is sys.platform.startswith("linux")
def test_run_venv_self_check_with_progress_includes_vision():
mock_mgr = MagicMock()
mock_mgr.execute.return_value = {
"status": "ok",
"result": {
"v": "3.12.0",
"arch": "x86_64",
"p": {},
"sci": [],
"eda": [],
"ui": [],
},
}
vision_probes = {
"docling": None,
"rapidocr": None,
"css_inline": None,
"paddleocr": "present",
"paddle": None,
"ultralytics": None,
"skimage": None,
}
with (
patch("plugin.scripting.venv_worker.PythonWorkerManager.get", return_value=mock_mgr),
patch(
"plugin.scripting.venv_diagnostics._run_named_json_probe",
side_effect=lambda exe, name, timeout=None: (
({"sounddevice": "present", "input_device": "present"}, None)
if name == "audio"
else (
(vision_probes, None)
if name == "vision"
else (({}, None) if name in {"nlp", "vector_search"} else orig_named_probe(exe, name))
)
),
),
):
ok, msg = run_venv_self_check_with_progress("/x/python", lambda text: None)
assert ok is True
assert "Text / NLP Libraries" in msg
assert "Vision Libraries" in msg
assert "Vector Search Libraries" in msg
assert "OCR: not ready" in msg
assert "To install remaining packages:" in msg
assert "uv pip install" in msg
assert "Helpers" not in msg
def test_run_venv_self_check_with_progress_includes_vector_search():
mock_mgr = MagicMock()
mock_mgr.execute.return_value = {
"status": "ok",
"result": {
"v": "3.12.0",
"arch": "x86_64",
"p": {},
"sci": [],
"eda": [],
"ui": [],
},
}
vector_search_probes = {
"envwrap": "present",
"sentence_transformers": None,
"sqlite_vec": "present",
"zvec": None,
"langgraph": None,
"langchain_core": None,
"langchain_text_splitters": None,
}
with (
patch("plugin.scripting.venv_worker.PythonWorkerManager.get", return_value=mock_mgr),
patch(
"plugin.scripting.venv_diagnostics._run_named_json_probe",
side_effect=lambda exe, name, timeout=None: (
(vector_search_probes, None)
if name == "vector_search"
else (({}, None) if name in {"nlp", "vision"} else orig_named_probe(exe, name))
),
),
):
ok, msg = run_venv_self_check_with_progress("/x/python", lambda text: None)
assert ok is True
assert "Vector Search Libraries" in msg
assert "Vector Search Libraries: envwrap, sqlite_vec" in msg
assert "Missing: sentence_transformers" in msg
def test_probe_vision_packages_timeout_reports_failure():
mock_mgr = MagicMock()
mock_mgr.execute.return_value = {
"status": "ok",
"result": {
"v": "3.12.0",
"arch": "x86_64",
"p": {},
"sci": [],
"eda": [],
"ui": [],
},
}
timeout_hint = "Vision probe timed out (Docling import can take 10–30s on first check)."
with (
patch("plugin.scripting.venv_worker.PythonWorkerManager.get", return_value=mock_mgr),
patch(
"plugin.scripting.venv_diagnostics._run_named_json_probe",
side_effect=lambda exe, name, timeout=None: (
({"sounddevice": "present", "input_device": "present"}, None)
if name == "audio"
else (
({}, timeout_hint)
if name == "vision"
else (({}, None) if name in {"nlp", "vector_search"} else orig_named_probe(exe, name))
)
),
),
):
ok, msg = run_venv_self_check_with_progress("/x/python", lambda text: None)
assert ok is True
assert "Vision Libraries" in msg
assert timeout_hint in msg
assert "Missing (OCR): docling" in msg
assert "To install remaining packages:" in msg
@pytest.mark.parametrize("group", ["vector_search", "vision", "nlp"])
def test_probe_packages_subprocess_timeout(group):
with patch(
"plugin.scripting.venv_diagnostics.subprocess.run",
side_effect=subprocess.TimeoutExpired(cmd=["python"], timeout=30),
):
probes, hint = _run_named_json_probe("/x/python", group)
assert probes == {}
assert hint is not None
assert "timed out" in hint.lower()
def test_run_venv_self_check_with_progress_reports_duckdb():
from plugin.scripting.venv_worker import ExecRequest
def fake_execute(req: ExecRequest):
script = req.code or ""
if "platform" in script:
return {"status": "ok", "result": {"v": "3.12.0", "arch": "x86_64"}}
if "pint" in script:
return {"status": "ok", "result": "present"}
return {"status": "ok", "result": None}
mock_mgr = MagicMock()
mock_mgr.execute.side_effect = fake_execute
with (
patch("plugin.scripting.venv_worker.PythonWorkerManager.get", return_value=mock_mgr),
patch(
"plugin.scripting.venv_diagnostics._run_named_json_probe",
side_effect=lambda exe, name, timeout=None: (
({}, None) if name in {"nlp", "vector_search", "vision"} else orig_named_probe(exe, name)
),
),
):
ok, msg = run_venv_self_check_with_progress("/x/python", lambda text: None)
assert ok is True
assert "Data Engineering Libraries: pint" in msg
assert "duckdb" in msg
def test_probe_hints_translate_at_call_time(monkeypatch) -> None:
"""Hints call _() at call time; a module-level _() would freeze the catalog before init_i18n(ctx)."""
import plugin.scripting.venv_diagnostics as diag
def fake_translate(message: str) -> str:
return f"LOCALE:{message}"
monkeypatch.setattr(diag, "_", fake_translate)
monkeypatch.setattr(
diag.subprocess,
"run",
MagicMock(side_effect=subprocess.TimeoutExpired(cmd=["python"], timeout=30)),
)
_probes, hint = diag._run_named_json_probe("/x/python", "nlp")
assert hint is not None
assert hint.startswith("LOCALE:")
assert "timed out" in hint
assert diag._audio_linux_portaudio_hint().startswith("LOCALE:")
def test_attach_external_probes_shares_one_helper(monkeypatch):
from plugin.scripting import venv_diagnostics as vd
monkeypatch.setattr(
vd,
"_run_named_json_probe",
lambda exe, name, timeout=None: ({"sounddevice": True}, None) if name == "audio" else ({}, None),
)
single_report = vd.ProbeReport()
vd._attach_external_probes("/usr/bin/python", single_report, "audio", "Audio")
assert any(g.key == "audio" for g in single_report.groups)
assert not any(g.key in {"ui", "nlp", "vision", "vector_search"} for g in single_report.groups)
report = vd.ProbeReport()
for group in ("audio", "ui", "nlp", "vision", "vector_search"):
vd._attach_external_probes("/usr/bin/python", report, group, group)
assert {g.key for g in report.groups} == {"audio", "ui", "nlp", "vision", "vector_search"}
def test_run_json_probe_ignores_stdout_banner():
with patch(
"plugin.scripting.venv_diagnostics.subprocess.run",
return_value=subprocess.CompletedProcess(
args=["python"],
returncode=0,
stdout='loading paddle\nWA_PROBE_JSON {"docling": "present"}\nbye\n',
stderr="noise",
),
):
probes, hint = _run_named_json_probe("/x/python", "vision")
assert probes.get("docling") == "present"
assert hint is None
def test_run_json_probe_rejects_stdout_without_prefix():
with patch(
"plugin.scripting.venv_diagnostics.subprocess.run",
return_value=subprocess.CompletedProcess(
args=["python"],
returncode=0,
stdout='{"docling": "present"}\n',
stderr="",
),
):
probes, hint = _run_named_json_probe("/x/python", "vision")
assert probes == {}
assert hint is not None
def test_parse_probe_stdout_accepts_marker_glued_to_banner():
res1 = _parse_probe_stdout('banner without newlineWA_PROBE_JSON {"rapidocr": "present"}\n')
assert res1 == {"rapidocr": "present"}
res2 = _parse_probe_stdout('WA_PROBE_JSON {"docling": "present"}\nnoise WA_PROBE_JSON not-json\n')
assert res2 == {"docling": "present"}
def test_run_json_probe_uses_utf8():
from plugin.scripting.venv_diagnostics import _run_json_probe
captured_kwargs: dict[str, Any] = {}
def _fake_run(*args, **kwargs):
captured_kwargs.update(kwargs)
return subprocess.CompletedProcess(
args=["python"],
returncode=0,
stdout='café\nWA_PROBE_JSON {"docling": "present"}\n',
stderr="",
)
with patch("plugin.scripting.venv_diagnostics.subprocess.run", side_effect=_fake_run):
probes, hint = _run_json_probe(
sys.executable,
"print(1)\n",
30,
timeout_hint="t",
fail_hint="f",
log_label="t",
)
assert captured_kwargs.get("encoding") == "utf-8"
assert captured_kwargs.get("errors") == "replace"
assert "text" not in captured_kwargs
assert probes == {"docling": "present"}
assert hint is None
def test_probe_scripts_compile_and_ui_probe_round_trips():
scripts = [
_AUDIO_PROBE_SCRIPT,
_NLP_PROBE_SCRIPT,
_VISION_PROBE_SCRIPT,
_VECTOR_SEARCH_PROBE_SCRIPT,
_UI_PROBE_SCRIPT,
_DUCKDB_PROBE_SCRIPT,
]
for script in scripts:
compile(script, "<test_probe_script>", "exec")
proc = subprocess.run(
[sys.executable, "-c", _UI_PROBE_SCRIPT],
capture_output=True,
encoding="utf-8",
timeout=30,
)
assert proc.returncode == 0, proc.stderr
parsed = _parse_probe_stdout(proc.stdout)
assert parsed is not None
assert set(_UI_PACKAGE_KEYS) <= set(parsed)
vision_proc = subprocess.run(
[sys.executable, "-c", _VISION_PROBE_SCRIPT],
capture_output=True,
encoding="utf-8",
timeout=30,
)
assert vision_proc.returncode == 0, vision_proc.stderr
vision_parsed = _parse_probe_stdout(vision_proc.stdout)
assert vision_parsed is not None
assert set(_OCR_ENGINE_KEYS) <= set(vision_parsed)
from plugin.vision.vision_common import OCR_BACKENDS, ocr_module_package
expected_engine_pkgs = {ocr_module_package(e) for row in OCR_BACKENDS.values() for e in row.modules}
assert expected_engine_pkgs <= set(vision_parsed)
def test_run_json_probe_keeps_payload_on_nonzero_exit():
completed = subprocess.CompletedProcess(
args=["python"],
returncode=1,
stdout='WA_PROBE_JSON {"docling": "present"}\n',
stderr="atexit failed",
)
with patch("plugin.scripting.venv_diagnostics.subprocess.run", return_value=completed):
probes, hint = _run_named_json_probe("/x/python", "vision")
assert probes == {"docling": "present"}
assert hint is None
def test_run_json_probe_nonzero_exit_without_payload_fails():
completed = subprocess.CompletedProcess(
args=["python"],
returncode=1,
stdout="",
stderr="atexit failed",
)
with patch("plugin.scripting.venv_diagnostics.subprocess.run", return_value=completed):
probes, hint = _run_named_json_probe("/x/python", "vision")
assert probes == {}
assert hint is not None
def test_probe_import_guard_survives_system_exit(tmp_path):
(tmp_path / "wa_k157_exit.py").write_text("raise SystemExit(7)\n")
script = _import_probe_script(
_import_try_block("wa_k157_exit", "wa_k157_exit"),
_import_try_block("json", "json"),
)
proc = subprocess.run(
[sys.executable, "-c", script],
capture_output=True,
encoding="utf-8",
timeout=60,
env={**os.environ, "PYTHONPATH": str(tmp_path) + os.pathsep + os.environ.get("PYTHONPATH", "")},
)
assert proc.returncode == 0
assert _parse_probe_stdout(proc.stdout) == {"wa_k157_exit": None, "json": "present"}
def test_run_json_probe_watches_the_flatpak_bus():
recorded_kwargs: dict[str, Any] = {}
def fake_wrap(cmd, **kwargs):
recorded_kwargs.update(kwargs)
return cmd
completed = subprocess.CompletedProcess(
args=["python"],
returncode=0,
stdout='WA_PROBE_JSON {"docling": "present"}\n',
stderr="",
)
with patch("plugin.scripting.venv_diagnostics.wrap_command_for_sandbox", side_effect=fake_wrap):
with patch("plugin.scripting.venv_diagnostics.subprocess.run", return_value=completed):
_run_named_json_probe("/x/python", "vision")
assert recorded_kwargs.get("watch_bus") is True
def test_probe_venv_path_messages_are_translated(tmp_path, monkeypatch):
monkeypatch.setattr("plugin.scripting.venv_diagnostics._", lambda message: f"L:{message}")
with patch("plugin.scripting.venv_diagnostics.resolve_libreoffice_python", return_value=None):
ok, msg = probe_venv_path_with_progress("", lambda unused: None)
assert ok is False
assert msg.startswith("L:No process interpreter:")
ok, msg = probe_venv_path_with_progress(str(tmp_path), lambda unused: None)
assert ok is False
assert msg.startswith("L:No python found.")
ok, msg = probe_venv_path_with_progress(str(tmp_path / "missing"), lambda unused: None)
assert ok is False
assert msg.startswith("L:Path not found: ")
ok, msg = probe_venv_path_with_progress(__file__, lambda unused: None)
assert ok is False
assert msg.startswith("L:Not a Python executable: ")