-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_reed.py
More file actions
1953 lines (1429 loc) · 65 KB
/
test_reed.py
File metadata and controls
1953 lines (1429 loc) · 65 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
"""Tests for reed interactive mode and core functions (TDD)."""
import argparse
import io
import types
from pathlib import Path
import pytest
import reed as _reed
from reed import ReedConfig
def _make_args(**overrides):
defaults = dict(
text=[],
file=None,
pages=None,
clipboard=False,
model=Path(__file__).parent / "en_US-kristin-medium.onnx",
speed=1.0,
volume=1.0,
output=None,
silence=0.3,
)
defaults.update(overrides)
return argparse.Namespace(**defaults)
def _make_config(**overrides):
defaults = dict(
model=Path(__file__).parent / "en_US-kristin-medium.onnx",
speed=1.0,
volume=1.0,
silence=0.3,
output=None,
)
defaults.update(overrides)
return ReedConfig(**defaults)
def _capture_main(**kwargs):
from rich.console import Console as RichConsole
cap_console = RichConsole(file=io.StringIO(), force_terminal=False)
code = _reed.main(print_fn=cap_console.print, **kwargs)
output = cap_console.file.getvalue()
return code, output
def _fake_spine(html_list):
"""Create a fake spine: list of (href, FakeZf) from HTML byte strings."""
class FakeZf:
def __init__(self, data_map):
self._data = data_map
def read(self, href):
return self._data[href]
def close(self):
pass
data = {f"ch{i}.xhtml": html for i, html in enumerate(html_list)}
zf = FakeZf(data)
return [(href, zf) for href in data]
def _make_prompt_fn(lines: list[str]):
"""Create a prompt_fn that yields lines then raises EOFError."""
it = iter(lines)
def prompt_fn() -> str:
try:
return next(it)
except StopIteration:
raise EOFError
return prompt_fn
# ─── interactive_loop tests ───────────────────────────────────────────
class TestInteractiveLoop:
def test_speaks_each_line_immediately(self):
from reed import interactive_loop
spoken: list[str] = []
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
prompt_fn=_make_prompt_fn(["hello", "world", "/quit"]),
)
assert spoken == ["hello", "world"]
assert result == 0
def test_eof_exits_cleanly(self):
from reed import interactive_loop
spoken: list[str] = []
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
prompt_fn=_make_prompt_fn(["hello"]),
)
assert spoken == ["hello"]
assert result == 0
def test_blank_lines_ignored(self):
from reed import interactive_loop
spoken: list[str] = []
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
prompt_fn=_make_prompt_fn(["", " ", "hello", "/quit"]),
)
assert spoken == ["hello"]
assert result == 0
def test_quit_commands_case_insensitive(self):
from reed import interactive_loop
spoken: list[str] = []
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
prompt_fn=_make_prompt_fn(["Hello", "/EXIT"]),
)
assert spoken == ["Hello"]
assert result == 0
def test_exit_command(self):
from reed import interactive_loop
spoken: list[str] = []
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
prompt_fn=_make_prompt_fn(["/exit"]),
)
assert spoken == []
assert result == 0
def test_help_command(self):
from reed import interactive_loop
spoken: list[str] = []
def print_fn(*args, **kwargs):
None
interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=print_fn,
prompt_fn=_make_prompt_fn(["/help", "/quit"]),
)
assert spoken == []
def test_clear_command(self):
from reed import interactive_loop
spoken: list[str] = []
cleared: list[bool] = []
def print_fn(*args, **kwargs):
None
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=print_fn,
clear_fn=lambda: cleared.append(True),
prompt_fn=_make_prompt_fn(["/clear", "/quit"]),
)
assert spoken == []
assert cleared == [True]
assert result == 0
def test_replay_command(self):
from reed import interactive_loop
spoken: list[str] = []
def print_fn(*args, **kwargs):
None
interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=print_fn,
prompt_fn=_make_prompt_fn(["first line", "/replay", "/quit"]),
)
assert len(spoken) == 2
assert spoken[0] == spoken[1] == "first line"
def test_replay_with_no_prior_text(self):
from reed import interactive_loop
spoken: list[str] = []
printed: list[object] = []
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: printed.append(args[0] if args else None),
prompt_fn=_make_prompt_fn(["/replay", "/quit"]),
)
assert spoken == []
assert any("No text to replay" in str(item) for item in printed)
assert result == 0
def test_multiline_paste_batched(self):
from reed import interactive_loop
spoken: list[str] = []
interactive_loop(
speak_line=lambda t: spoken.append(t),
prompt_fn=_make_prompt_fn(["line one\nline two\nline three", "/quit"]),
)
assert len(spoken) == 1
assert "line one" in spoken[0]
assert "line two" in spoken[0]
assert "line three" in spoken[0]
def test_ctrl_c_handled_gracefully(self):
from reed import interactive_loop
spoken: list[str] = []
call_count = 0
def raising_prompt() -> str:
nonlocal call_count
call_count += 1
if call_count == 1:
return "first"
raise KeyboardInterrupt
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
prompt_fn=raising_prompt,
)
assert spoken == ["first"]
assert result == 0
def test_banner_printed(self):
from reed import interactive_loop
printed: list[object] = []
result = interactive_loop(
speak_line=lambda t: None,
print_fn=lambda *args, **kwargs: printed.append(args[0] if args else None),
prompt_fn=_make_prompt_fn(["/quit"]),
)
assert result == 0
assert any("reed" in str(item) for item in printed)
def test_load_command_with_valid_pdf(self, tmp_path, monkeypatch):
from reed import interactive_loop
# Create a mock PDF file
pdf_path = tmp_path / "test.pdf"
pdf_path.write_text("%PDF-1.4") # Minimal PDF header
spoken: list[str] = []
printed: list[object] = []
def mock_iter_pdf_pages(path, selection):
yield (1, 1, "Test PDF content")
monkeypatch.setattr(_reed, "_iter_pdf_pages", mock_iter_pdf_pages)
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: printed.append(args[0] if args else None),
prompt_fn=_make_prompt_fn(["/load " + str(pdf_path), "/quit"]),
)
assert result == 0
assert "Test PDF content" in spoken
def test_pdf_command_alias(self, tmp_path, monkeypatch):
from reed import interactive_loop
pdf_path = tmp_path / "test.pdf"
pdf_path.write_text("%PDF-1.4")
spoken: list[str] = []
def mock_iter_pdf_pages(path, selection):
yield (1, 1, "Test PDF content")
monkeypatch.setattr(_reed, "_iter_pdf_pages", mock_iter_pdf_pages)
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: None,
prompt_fn=_make_prompt_fn(["/load " + str(pdf_path), "/quit"]),
)
assert result == 0
assert "Test PDF content" in spoken
def test_load_command_file_not_found(self, tmp_path):
from reed import interactive_loop
non_existent = tmp_path / "missing.pdf"
printed: list[object] = []
result = interactive_loop(
speak_line=lambda t: None,
print_fn=lambda *args, **kwargs: printed.append(args[0] if args else None),
prompt_fn=_make_prompt_fn(["/load " + str(non_existent), "/quit"]),
)
assert result == 0
assert any("File not found" in str(item) for item in printed)
def test_load_command_unsupported_type(self, tmp_path):
from reed import interactive_loop
txt_path = tmp_path / "test.txt"
txt_path.write_text("Some text")
printed: list[object] = []
result = interactive_loop(
speak_line=lambda t: None,
print_fn=lambda *args, **kwargs: printed.append(args[0] if args else None),
prompt_fn=_make_prompt_fn(["/load " + str(txt_path), "/quit"]),
)
assert result == 0
assert any("Unsupported file type" in str(item) for item in printed)
def test_load_command_windows_path_preserves_backslashes(self, monkeypatch):
from reed import interactive_loop
windows_pdf = r"C:\Users\runneradmin\book.pdf"
spoken: list[str] = []
class FakePath:
def __init__(self, raw: str):
self.raw = raw
def exists(self) -> bool:
return self.raw == windows_pdf
@property
def suffix(self) -> str:
return ".pdf" if self.raw.lower().endswith(".pdf") else ""
def mock_iter_pdf_pages(path, selection):
assert path.raw == windows_pdf
yield (1, 1, "Windows path PDF content")
monkeypatch.setattr(_reed, "Path", FakePath)
monkeypatch.setattr(_reed, "_iter_pdf_pages", mock_iter_pdf_pages)
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: None,
prompt_fn=_make_prompt_fn([f"/load {windows_pdf}", "/quit"]),
)
assert result == 0
assert "Windows path PDF content" in spoken
def test_drag_drop_windows_path_with_escaped_spaces(self, monkeypatch):
from reed import interactive_loop
windows_pdf = r"C:\Users\runneradmin\My Book.pdf"
escaped_input = r"C:\Users\runneradmin\My\ Book.pdf"
spoken: list[str] = []
class FakePath:
def __init__(self, raw: str):
self.raw = raw
def exists(self) -> bool:
return self.raw == windows_pdf
@property
def suffix(self) -> str:
return ".pdf" if self.raw.lower().endswith(".pdf") else ""
def mock_iter_pdf_pages(path, selection):
assert path.raw == windows_pdf
yield (1, 1, "Windows escaped-space PDF content")
monkeypatch.setattr(_reed, "Path", FakePath)
monkeypatch.setattr(_reed, "_iter_pdf_pages", mock_iter_pdf_pages)
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: None,
prompt_fn=_make_prompt_fn([escaped_input, "/quit"]),
)
assert result == 0
assert "Windows escaped-space PDF content" in spoken
def test_drag_drop_pdf_file_path(self, tmp_path, monkeypatch):
from reed import interactive_loop
pdf_path = tmp_path / "book.pdf"
pdf_path.write_text("%PDF-1.4")
spoken: list[str] = []
def mock_iter_pdf_pages(path, selection):
yield (1, 1, "Dragged PDF content")
monkeypatch.setattr(_reed, "_iter_pdf_pages", mock_iter_pdf_pages)
# Simulate drag-drop by passing the file path as input
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: None,
prompt_fn=_make_prompt_fn([str(pdf_path), "/quit"]),
)
assert result == 0
assert "Dragged PDF content" in spoken
def test_drag_drop_pdf_with_quotes(self, tmp_path, monkeypatch):
from reed import interactive_loop
pdf_path = tmp_path / "book.pdf"
pdf_path.write_text("%PDF-1.4")
spoken: list[str] = []
def mock_iter_pdf_pages(path, selection):
yield (1, 1, "Quoted PDF content")
monkeypatch.setattr(_reed, "_iter_pdf_pages", mock_iter_pdf_pages)
# Simulate drag-drop with quotes (common in terminals)
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: None,
prompt_fn=_make_prompt_fn(['"' + str(pdf_path) + '"', "/quit"]),
)
assert result == 0
assert "Quoted PDF content" in spoken
def test_drag_drop_epub_file(self, tmp_path, monkeypatch):
from reed import interactive_loop
epub_path = tmp_path / "book.epub"
epub_path.write_text("EPUB content placeholder")
spoken: list[str] = []
def mock_iter_epub_chapters(path, selection):
yield (1, 1, "EPUB chapter content")
monkeypatch.setattr(_reed, "_iter_epub_chapters", mock_iter_epub_chapters)
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: None,
prompt_fn=_make_prompt_fn([str(epub_path), "/quit"]),
)
assert result == 0
assert "EPUB chapter content" in spoken
def test_non_existent_file_path_not_treated_as_file(self, tmp_path):
from reed import interactive_loop
# A path that ends with .pdf but doesn't exist should be treated as text
fake_path = tmp_path / "missing.pdf"
spoken: list[str] = []
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: None,
prompt_fn=_make_prompt_fn([str(fake_path), "/quit"]),
)
assert result == 0
# Should try to speak it as text since file doesn't exist
assert len(spoken) == 1
def test_drag_drop_pdf_with_spaces_in_path(self, tmp_path, monkeypatch):
from reed import interactive_loop
# Create a PDF with spaces in the filename
pdf_path = tmp_path / "My Document.pdf"
pdf_path.write_text("%PDF-1.4")
spoken: list[str] = []
def mock_iter_pdf_pages(path, selection):
yield (1, 1, "PDF with spaces in path")
monkeypatch.setattr(_reed, "_iter_pdf_pages", mock_iter_pdf_pages)
# Simulate pasted path with backslash escapes for spaces
escaped_path = str(pdf_path).replace(" ", "\\ ")
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: None,
prompt_fn=_make_prompt_fn([escaped_path, "/quit"]),
)
assert result == 0
assert "PDF with spaces in path" in spoken
def test_drag_drop_epub_with_spaces_in_path(self, tmp_path, monkeypatch):
from reed import interactive_loop
# Create an EPUB with spaces in the filename
epub_path = tmp_path / "My Book.epub"
epub_path.write_text("EPUB content")
spoken: list[str] = []
def mock_iter_epub_chapters(path, selection):
yield (1, 1, "EPUB with spaces in path")
monkeypatch.setattr(_reed, "_iter_epub_chapters", mock_iter_epub_chapters)
# Simulate pasted path with backslash escapes for spaces
escaped_path = str(epub_path).replace(" ", "\\ ")
result = interactive_loop(
speak_line=lambda t: spoken.append(t),
print_fn=lambda *args, **kwargs: None,
prompt_fn=_make_prompt_fn([escaped_path, "/quit"]),
)
assert result == 0
assert "EPUB with spaces in path" in spoken
# ─── build_piper_cmd tests ────────────────────────────────────────────
class TestBuildPiperCmd:
def test_basic_command(self):
from reed import build_piper_cmd
cmd = build_piper_cmd(
model=Path("/models/test.onnx"),
speed=1.0,
volume=1.0,
silence=0.3,
output=None,
)
assert cmd[1:3] == ["-m", "piper"]
assert "--model" in cmd
assert str(Path("/models/test.onnx")) in cmd
assert "--length-scale" in cmd
assert "--volume" in cmd
assert "--sentence-silence" in cmd
def test_with_output_file(self):
from reed import build_piper_cmd
cmd = build_piper_cmd(
model=Path("/models/test.onnx"),
speed=1.0,
volume=1.0,
silence=0.3,
output=Path("/out.wav"),
)
assert "--output-file" in cmd
idx = cmd.index("--output-file")
assert cmd[idx + 1] == str(Path("/out.wav"))
# ─── speak_text tests ────────────────────────────────────────────────
class TestSpeakText:
def test_play_path_calls_piper_then_player(self, monkeypatch):
from reed import _default_play_cmd, speak_text
monkeypatch.setattr("reed.platform.system", lambda: "Darwin")
calls = []
def fake_run(cmd, **kwargs):
calls.append((cmd, kwargs))
return types.SimpleNamespace(returncode=0, stderr="")
config = _make_config()
speak_text("hi", config, run=fake_run)
assert len(calls) == 2
assert calls[0][0][1:3] == ["-m", "piper"]
assert calls[0][1].get("input") == "hi"
play_cmd = _default_play_cmd()
assert calls[1][0][: len(play_cmd)] == play_cmd
def test_output_path_no_afplay(self):
from reed import speak_text
calls = []
def fake_run(cmd, **kwargs):
calls.append((cmd, kwargs))
return types.SimpleNamespace(returncode=0, stderr="")
def print_fn(*args, **kwargs):
None
config = _make_config(output=Path("/tmp/out.wav"))
speak_text("hi", config, run=fake_run, print_fn=print_fn)
assert len(calls) == 1
def test_piper_error_raises(self):
from reed import ReedError, speak_text
def fake_run(cmd, **kwargs):
return types.SimpleNamespace(returncode=1, stderr="boom")
config = _make_config()
with pytest.raises(ReedError, match="boom"):
speak_text("hi", config, run=fake_run)
def test_playback_error_raises(self, monkeypatch):
from reed import ReedError, speak_text
monkeypatch.setattr("reed.platform.system", lambda: "Darwin")
call_count = 0
def fake_run(cmd, **kwargs):
nonlocal call_count
call_count += 1
if call_count == 1:
return types.SimpleNamespace(returncode=0, stderr="")
return types.SimpleNamespace(returncode=1, stderr="")
config = _make_config()
with pytest.raises(ReedError, match="playback error"):
speak_text("hi", config, run=fake_run)
# ─── main integration tests ──────────────────────────────────────────
class TestMainInteractiveFlag:
def test_no_input_defaults_to_interactive(self, monkeypatch):
from reed import ReedError, main
loop_called = []
class FakeTtyStdin:
def isatty(self):
return True
def readline(self):
return ""
def fileno(self):
raise io.UnsupportedOperation("no fileno")
def fake_loop(**kwargs):
loop_called.append(True)
return 0
def no_player() -> list[str]:
raise ReedError("No supported audio player found")
monkeypatch.setattr("reed._default_play_cmd", no_player)
code = main(
argv=["-m", __file__],
interactive_loop_fn=fake_loop,
run=lambda *a, **k: types.SimpleNamespace(returncode=0, stderr=""),
stdin=FakeTtyStdin(),
)
assert loop_called
assert code == 0
# ─── _should_enter_interactive tests ─────────────────────────────────
class TestShouldEnterInteractive:
def test_text_provided(self):
from reed import _should_enter_interactive
args = _make_args(text=["hello"])
assert _should_enter_interactive(args, io.StringIO()) is False
def test_file_provided(self):
from reed import _should_enter_interactive
args = _make_args(file="/tmp/test.txt")
assert _should_enter_interactive(args, io.StringIO()) is False
def test_clipboard(self):
from reed import _should_enter_interactive
args = _make_args(clipboard=True)
assert _should_enter_interactive(args, io.StringIO()) is False
def test_pages_provided(self):
from reed import _should_enter_interactive
class FakeTty:
def isatty(self):
return True
args = _make_args(pages="1-2")
assert _should_enter_interactive(args, FakeTty()) is False
def test_tty_stdin_no_args(self):
from reed import _should_enter_interactive
class FakeTty:
def isatty(self):
return True
args = _make_args()
assert _should_enter_interactive(args, FakeTty()) is True
def test_non_tty_stdin_no_args(self):
from reed import _should_enter_interactive
args = _make_args()
assert _should_enter_interactive(args, io.StringIO()) is False
def test_none_stdin(self):
from reed import _should_enter_interactive
args = _make_args()
assert _should_enter_interactive(args, None) is False
# ─── _default_play_cmd tests ──────────────────────────────────────────
class TestDefaultPlayCmd:
def test_macos_returns_afplay(self, monkeypatch):
from reed import _default_play_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Darwin")
assert _default_play_cmd() == ["afplay"]
def test_linux_paplay(self, monkeypatch):
from reed import _default_play_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Linux")
monkeypatch.setattr(
"reed.shutil.which",
lambda cmd: "/usr/bin/paplay" if cmd == "paplay" else None,
)
assert _default_play_cmd() == ["paplay"]
def test_linux_aplay_fallback(self, monkeypatch):
from reed import _default_play_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Linux")
monkeypatch.setattr(
"reed.shutil.which",
lambda cmd: "/usr/bin/aplay" if cmd == "aplay" else None,
)
assert _default_play_cmd() == ["aplay"]
def test_linux_ffplay_fallback(self, monkeypatch):
from reed import _default_play_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Linux")
monkeypatch.setattr(
"reed.shutil.which",
lambda cmd: "/usr/bin/ffplay" if cmd == "ffplay" else None,
)
assert _default_play_cmd() == ["ffplay", "-nodisp", "-autoexit"]
def test_linux_no_player_raises(self, monkeypatch):
from reed import ReedError, _default_play_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Linux")
monkeypatch.setattr("reed.shutil.which", lambda cmd: None)
with pytest.raises(ReedError, match="No supported audio player found"):
_default_play_cmd()
def test_windows_powershell(self, monkeypatch):
from reed import _default_play_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Windows")
monkeypatch.setattr(
"reed.shutil.which",
lambda cmd: (
r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
if cmd == "powershell"
else None
),
)
result = _default_play_cmd()
assert result[0] == "powershell"
assert "-c" in result
assert "System.Media.SoundPlayer" in " ".join(result)
def test_windows_ffplay_fallback(self, monkeypatch):
from reed import _default_play_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Windows")
monkeypatch.setattr(
"reed.shutil.which",
lambda cmd: r"C:\ffmpeg\bin\ffplay.exe" if cmd == "ffplay" else None,
)
assert _default_play_cmd() == ["ffplay", "-nodisp", "-autoexit", "-hide_banner"]
def test_windows_no_player_raises(self, monkeypatch):
from reed import ReedError, _default_play_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Windows")
monkeypatch.setattr("reed.shutil.which", lambda cmd: None)
with pytest.raises(ReedError, match="No supported audio player found"):
_default_play_cmd()
def test_unknown_platform_raises(self, monkeypatch):
from reed import ReedError, _default_play_cmd
monkeypatch.setattr("reed.platform.system", lambda: "FreeBSD")
with pytest.raises(ReedError, match="No supported audio player found"):
_default_play_cmd()
# ─── _default_clipboard_cmd tests ────────────────────────────────────
class TestDefaultClipboardCmd:
def test_macos_returns_pbpaste(self, monkeypatch):
from reed import _default_clipboard_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Darwin")
assert _default_clipboard_cmd() == ["pbpaste"]
def test_linux_wl_paste(self, monkeypatch):
from reed import _default_clipboard_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Linux")
monkeypatch.setattr(
"reed.shutil.which",
lambda cmd: "/usr/bin/wl-paste" if cmd == "wl-paste" else None,
)
assert _default_clipboard_cmd() == ["wl-paste"]
def test_linux_xclip_fallback(self, monkeypatch):
from reed import _default_clipboard_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Linux")
monkeypatch.setattr(
"reed.shutil.which",
lambda cmd: "/usr/bin/xclip" if cmd == "xclip" else None,
)
assert _default_clipboard_cmd() == ["xclip", "-selection", "clipboard", "-o"]
def test_linux_xsel_fallback(self, monkeypatch):
from reed import _default_clipboard_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Linux")
monkeypatch.setattr(
"reed.shutil.which", lambda cmd: "/usr/bin/xsel" if cmd == "xsel" else None
)
assert _default_clipboard_cmd() == ["xsel", "--clipboard", "--output"]
def test_linux_no_clipboard_raises(self, monkeypatch):
from reed import ReedError, _default_clipboard_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Linux")
monkeypatch.setattr("reed.shutil.which", lambda cmd: None)
with pytest.raises(ReedError, match="No supported clipboard tool found"):
_default_clipboard_cmd()
def test_windows_clipboard(self, monkeypatch):
from reed import _default_clipboard_cmd
monkeypatch.setattr("reed.platform.system", lambda: "Windows")
assert _default_clipboard_cmd() == ["powershell", "-Command", "Get-Clipboard"]
def test_unknown_platform_raises(self, monkeypatch):
from reed import ReedError, _default_clipboard_cmd
monkeypatch.setattr("reed.platform.system", lambda: "FreeBSD")
with pytest.raises(ReedError, match="No supported clipboard tool found"):
_default_clipboard_cmd()
# ─── get_text clipboard with run injection test ──────────────────────
class TestGetTextClipboard:
def test_clipboard_uses_injected_run(self, monkeypatch):
from reed import get_text
monkeypatch.setattr("reed.platform.system", lambda: "Darwin")
def fake_run(cmd, **kwargs):
return types.SimpleNamespace(
returncode=0, stdout="clipboard text", stderr=""
)
class FakeTty:
def isatty(self):
return True
args = _make_args(clipboard=True)
result = get_text(args, stdin=FakeTty(), run=fake_run)
assert result == "clipboard text"
def test_clipboard_error_raises(self, monkeypatch):
from reed import ReedError, get_text
monkeypatch.setattr("reed.platform.system", lambda: "Darwin")
def fake_run(cmd, **kwargs):
return types.SimpleNamespace(returncode=1, stdout="", stderr="fail")
class FakeTty:
def isatty(self):
return True
args = _make_args(clipboard=True)
with pytest.raises(ReedError, match="Failed to read clipboard"):
get_text(args, stdin=FakeTty(), run=fake_run)
# ─── get_text with stdin injection tests ─────────────────────────────
class TestGetTextStdin:
def test_piped_stdin_read(self):
from reed import get_text
stdin = io.StringIO("hello from pipe")
args = _make_args()
result = get_text(args, stdin=stdin)
assert result == "hello from pipe"
def test_text_args_joined(self):
from reed import get_text
class FakeTty:
def isatty(self):
return True
args = _make_args(text=["hello", "world"])
result = get_text(args, stdin=FakeTty())
assert result == "hello world"
class TestIterPdfPages:
def test_pdf_reads_all_pages_when_no_pages_flag(self, monkeypatch):
from reed import _iter_pdf_pages
class FakePage:
def __init__(self, text):
self._text = text
def extract_text(self):
return self._text
class FakeReader:
def __init__(self, path):
self.pages = [FakePage("page one"), FakePage("page two")]
monkeypatch.setattr("reed.PdfReader", FakeReader)
result = list(_iter_pdf_pages(Path("book.pdf"), None))
assert result == [(1, 2, "page one"), (2, 2, "page two")]
def test_pdf_reads_selected_pages(self, monkeypatch):
from reed import _iter_pdf_pages
class FakePage:
def __init__(self, text):
self._text = text
def extract_text(self):
return self._text
class FakeReader:
def __init__(self, path):
self.pages = [
FakePage("page one"),
FakePage("page two"),
FakePage("page three"),
FakePage("page four"),
]
monkeypatch.setattr("reed.PdfReader", FakeReader)
result = list(_iter_pdf_pages(Path("book.pdf"), "2,4"))
assert result == [(2, 4, "page two"), (4, 4, "page four")]
def test_pdf_page_out_of_bounds_raises(self, monkeypatch):
from reed import ReedError, _iter_pdf_pages
class FakePage:
def __init__(self, text):
self._text = text
def extract_text(self):
return self._text
class FakeReader:
def __init__(self, path):
self.pages = [FakePage("page one"), FakePage("page two")]
monkeypatch.setattr("reed.PdfReader", FakeReader)
with pytest.raises(ReedError, match="out of range"):
list(_iter_pdf_pages(Path("book.pdf"), "3"))
def test_pdf_invalid_pages_format_raises(self, monkeypatch):
from reed import ReedError, _iter_pdf_pages
class FakePage:
def __init__(self, text):