File size: 2,318 Bytes
9410704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import subprocess
import sys

import pytest

from elevenlabs import play as play_module


def _fake_ffplay(monkeypatch, exit_code, stderr=""):
    """Run a real subprocess in place of ffplay: it reads the audio from stdin,
    writes ``stderr`` and exits with ``exit_code``."""
    received = {}
    real_popen = subprocess.Popen

    def fake_popen(args, **kwargs):
        received["args"] = args
        script = (
            "import sys; data = sys.stdin.buffer.read(); "
            f"sys.stderr.write({stderr!r}); "
            f"sys.exit({exit_code})"
        )
        return real_popen([sys.executable, "-c", script], **kwargs)

    monkeypatch.setattr(play_module, "is_installed", lambda name: True)
    monkeypatch.setattr(play_module.subprocess, "Popen", fake_popen)
    return received


def test_play_returns_when_ffplay_succeeds(monkeypatch):
    received = _fake_ffplay(monkeypatch, exit_code=0)

    play_module.play(b"audio bytes")

    assert received["args"][0] == "ffplay"


def test_play_raises_when_ffplay_fails(monkeypatch):
    _fake_ffplay(monkeypatch, exit_code=1, stderr="error while loading shared libraries: libavdevice.so.61")

    with pytest.raises(ValueError, match="ffplay exited with status 1") as excinfo:
        play_module.play(b"audio bytes")

    assert "libavdevice.so.61" in str(excinfo.value)


def test_play_raises_without_error_output(monkeypatch):
    _fake_ffplay(monkeypatch, exit_code=2)

    with pytest.raises(ValueError, match=r"ffplay exited with status 2 and did not play the audio\.$"):
        play_module.play(b"audio bytes")


def test_play_joins_an_iterator_before_piping_it(monkeypatch):
    _fake_ffplay(monkeypatch, exit_code=0)

    play_module.play(iter([b"audio ", b"bytes"]))


def test_play_joins_a_list_of_chunks(monkeypatch):
    received = _fake_ffplay(monkeypatch, exit_code=0)

    play_module.play([b"audio ", b"bytes"])

    assert received["args"][0] == "ffplay"


def test_save_joins_a_list_of_chunks(tmp_path):
    target = tmp_path / "out.mp3"

    play_module.save([b"audio ", b"bytes"], str(target))

    assert target.read_bytes() == b"audio bytes"


def test_save_writes_bytes_unchanged(tmp_path):
    target = tmp_path / "out.mp3"

    play_module.save(b"audio bytes", str(target))

    assert target.read_bytes() == b"audio bytes"