aboutsummaryrefslogtreecommitdiff
path: root/app/tests/test_backends_envs.py
blob: 82d903ab2a21fb43023d36cd805fba21f701245d (plain)
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
"""Tests for the managed Python environment (backends/envs.py)."""

import sys
import unittest
from pathlib import Path
from unittest.mock import patch

from backends import envs


class EnvPathTests(unittest.TestCase):
    """Platform-aware path helpers (no venv actually created)."""

    def test_env_dir_under_envs_tts(self):
        self.assertEqual(envs.ENV_DIR.name, "tts")
        self.assertEqual(envs.ENV_DIR.parent.name, "envs")

    def test_env_python_posix(self):
        with patch.object(envs, "_is_windows", return_value=False):
            self.assertEqual(envs.env_python(),
                             envs.ENV_DIR / "bin" / "python")

    def test_env_python_windows(self):
        with patch.object(envs, "_is_windows", return_value=True):
            self.assertEqual(envs.env_python(),
                             envs.ENV_DIR / "Scripts" / "python.exe")

    def test_env_script_posix(self):
        with patch.object(envs, "_is_windows", return_value=False):
            self.assertEqual(envs.env_script("qwen-tts-demo"),
                             envs.ENV_DIR / "bin" / "qwen-tts-demo")

    def test_env_script_windows(self):
        with patch.object(envs, "_is_windows", return_value=True):
            self.assertEqual(envs.env_script("qwen-tts-demo"),
                             envs.ENV_DIR / "Scripts" / "qwen-tts-demo.exe")

    def test_env_exists_false_when_python_missing(self):
        with patch.object(envs, "env_python",
                          return_value=Path("/no/such/path/python")):
            self.assertFalse(envs.env_exists())

    def test_is_managed_env_compares_resolved_executable(self):
        fake_env_python = Path("/tmp/opencode/managed-env/bin/python")
        with patch.object(envs, "env_python", return_value=fake_env_python), \
                patch.object(sys, "executable", str(fake_env_python)):
            self.assertTrue(envs.is_managed_env())
        with patch.object(envs, "env_python", return_value=fake_env_python), \
                patch.object(sys, "executable", "/usr/bin/python3"):
            self.assertFalse(envs.is_managed_env())


class CreateEnvTests(unittest.TestCase):
    def test_create_env_invokes_venv_module(self):
        with patch.object(envs.common, "run_console_subprocess",
                          return_value=0) as run:
            rc = envs.create_env()
        self.assertEqual(rc, 0)
        argv = run.call_args[0][0]
        self.assertEqual(argv[0], sys.executable)
        self.assertEqual(argv[1], "-m")
        self.assertEqual(argv[2], "venv")
        self.assertEqual(argv[3], str(envs.ENV_DIR))

    def test_create_env_reports_remediation_on_failure(self):
        with patch.object(envs.common, "run_console_subprocess",
                          return_value=1):
            rc = envs.create_env()
        self.assertEqual(rc, 1)


class PipInstallTests(unittest.TestCase):
    def test_creates_env_first_when_missing(self):
        calls = []

        def fake_run(argv, **kwargs):
            calls.append(list(argv))
            return 0

        with patch.object(envs, "env_exists", return_value=False), \
                patch.object(envs, "create_env", return_value=0) as mk, \
                patch.object(envs.common, "run_console_subprocess",
                             side_effect=fake_run):
            rc = envs.pip_install(["qwen-tts"])
        self.assertEqual(rc, 0)
        mk.assert_called_once_with()
        # The actual pip call targets the venv's python.
        self.assertEqual(calls[0][0], str(envs.env_python()))
        self.assertIn("pip", calls[0])
        self.assertIn("qwen-tts", calls[0])

    def test_skips_create_when_env_exists(self):
        with patch.object(envs, "env_exists", return_value=True), \
                patch.object(envs, "create_env") as mk, \
                patch.object(envs.common, "run_console_subprocess",
                             return_value=0):
            envs.pip_install(["qwen-tts"])
        mk.assert_not_called()

    def test_returns_nonzero_when_create_fails(self):
        with patch.object(envs, "env_exists", return_value=False), \
                patch.object(envs, "create_env", return_value=1), \
                patch.object(envs.common, "run_console_subprocess") as run:
            rc = envs.pip_install(["qwen-tts"])
        self.assertEqual(rc, 1)
        run.assert_not_called()


class PipUninstallTests(unittest.TestCase):
    def test_missing_env_is_success_without_running_pip(self):
        with patch.object(envs, "env_exists", return_value=False), \
                patch.object(envs.common, "run_console_subprocess") as run:
            rc = envs.pip_uninstall(["qwen-tts"])
        self.assertEqual(rc, 0)
        run.assert_not_called()

    def test_runs_pip_uninstall_against_the_venv_python(self):
        calls = []

        def fake_run(argv, **kwargs):
            calls.append(list(argv))
            return 0

        with patch.object(envs, "env_exists", return_value=True), \
                patch.object(envs.common, "run_console_subprocess",
                             side_effect=fake_run):
            rc = envs.pip_uninstall(["qwen-tts"])
        self.assertEqual(rc, 0)
        # The uninstall targets the venv's python.
        self.assertEqual(calls[0][0], str(envs.env_python()))
        self.assertIn("uninstall", calls[0])
        self.assertIn("-y", calls[0])
        self.assertIn("qwen-tts", calls[0])

    def test_streams_to_emit_when_given(self):
        with patch.object(envs, "env_exists", return_value=True), \
                patch.object(envs.common, "run_console_subprocess",
                             return_value=0) as run:
            rc = envs.pip_uninstall(["qwen-tts"], emit="EMIT")
        self.assertEqual(rc, 0)
        # The task view's emit is forwarded so pip never touches the
        # terminal behind curses.
        self.assertEqual(run.call_args.kwargs.get("emit"), "EMIT")

    def test_console_path_passes_no_emit(self):
        with patch.object(envs, "env_exists", return_value=True), \
                patch.object(envs.common, "run_console_subprocess",
                             return_value=0) as run:
            rc = envs.pip_uninstall(["qwen-tts"])
        self.assertEqual(rc, 0)
        self.assertIsNone(run.call_args.kwargs.get("emit"))


class ModuleAvailableTests(unittest.TestCase):
    def test_false_when_env_missing(self):
        with patch.object(envs, "env_exists", return_value=False):
            self.assertFalse(envs.module_available("qwen_tts"))

    def test_true_when_subprocess_exits_zero(self):
        import subprocess
        fake = subprocess.CompletedProcess(args=["x"], returncode=0)
        with patch.object(envs, "env_exists", return_value=True), \
                patch("subprocess.run", return_value=fake) as run:
            self.assertTrue(envs.module_available("qwen_tts"))
        argv = run.call_args[0][0]
        self.assertEqual(argv[0], str(envs.env_python()))
        self.assertIn("import qwen_tts", argv[2])

    def test_false_when_subprocess_exits_nonzero(self):
        import subprocess
        fake = subprocess.CompletedProcess(args=["x"], returncode=1)
        with patch.object(envs, "env_exists", return_value=True), \
                patch("subprocess.run", return_value=fake):
            self.assertFalse(envs.module_available("qwen_tts"))

    def test_false_on_timeout(self):
        import subprocess
        with patch.object(envs, "env_exists", return_value=True), \
                patch("subprocess.run",
                      side_effect=subprocess.TimeoutExpired(cmd="x", timeout=1)):
            self.assertFalse(envs.module_available("qwen_tts"))


class EnsureAppEnvTests(unittest.TestCase):
    def test_creates_env_then_installs_when_marker_invalid(self):
        with patch.object(envs, "env_exists", return_value=False), \
                patch.object(envs, "create_env", return_value=0), \
                patch.object(envs, "_marker_valid", return_value=False), \
                patch.object(envs, "install_requirements", return_value=0), \
                patch.object(envs, "_write_marker") as mk:
            envs.ensure_app_env()
        mk.assert_called_once_with()

    def test_raises_when_create_fails(self):
        with patch.object(envs, "env_exists", return_value=False), \
                patch.object(envs, "create_env", return_value=1):
            with self.assertRaises(RuntimeError):
                envs.ensure_app_env()

    def test_raises_when_install_fails(self):
        with patch.object(envs, "env_exists", return_value=True), \
                patch.object(envs, "_marker_valid", return_value=False), \
                patch.object(envs, "install_requirements", return_value=1):
            with self.assertRaises(RuntimeError):
                envs.ensure_app_env()

    def test_skips_install_when_marker_valid(self):
        with patch.object(envs, "env_exists", return_value=True), \
                patch.object(envs, "_marker_valid", return_value=True), \
                patch.object(envs, "install_requirements") as mk:
            envs.ensure_app_env()
        mk.assert_not_called()


class BootstrapTests(unittest.TestCase):
    def test_noop_when_already_managed(self):
        with patch.object(envs, "is_managed_env", return_value=True), \
                patch.object(envs, "ensure_app_env") as mk, \
                patch("os.execv") as ex:
            envs.bootstrap("/path/to/audiobook.py")
        mk.assert_not_called()
        ex.assert_not_called()

    def test_ensures_env_then_execvs(self):
        with patch.object(envs, "is_managed_env", return_value=False), \
                patch.object(envs, "ensure_app_env") as mk_env, \
                patch("os.execv") as ex, \
                patch.object(sys, "argv", ["audiobook.py", "--backend", "qwen"]):
            envs.bootstrap("/path/to/audiobook.py")
        mk_env.assert_called_once_with()
        py = str(envs.env_python())
        args = ex.call_args[0]
        self.assertEqual(args[0], py)
        self.assertEqual(args[1][0], py)
        self.assertTrue(args[1][1].endswith("audiobook.py"))
        self.assertEqual(args[1][2:], ["--backend", "qwen"])

    def test_exits_when_ensure_raises(self):
        with patch.object(envs, "is_managed_env", return_value=False), \
                patch.object(envs, "ensure_app_env",
                             side_effect=RuntimeError("boom")), \
                patch("os.execv") as ex, \
                self.assertRaises(SystemExit):
            envs.bootstrap("/path/to/audiobook.py")
        ex.assert_not_called()


if __name__ == "__main__":
    unittest.main()