summaryrefslogtreecommitdiff
path: root/tests/test_cli.py
blob: f6ebb8e5d28f86d3b7efdd371cd0a23416c27922 (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
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
"""CLI behaviour: argument parsing, wiring, and error reporting.

No network access: the provider is stubbed where a run is needed.
"""

import sys

import pytest

from agentux import __version__
from agentux.cli import build_parser, main, resolve_config
from agentux.errors import AuthenticationError
from agentux.tools.filesystem import FilesystemTool
from agentux.tools.project import ProjectTool
from agentux.tools.shell import ShellTool


def test_parser_accepts_a_prompt():
    args = build_parser().parse_args(["fix the failing tests"])
    assert args.prompt == "fix the failing tests"


def test_parser_prompt_is_optional():
    assert build_parser().parse_args([]).prompt is None


def test_parser_flags():
    args = build_parser().parse_args(
        ["--model", "m", "--base-url", "http://x/v1", "--no-tools",
         "--read-only", "--max-steps", "3", "--timeout", "5", "--cwd", "/tmp", "-v"]
    )
    assert args.model == "m"
    assert args.base_url == "http://x/v1"
    assert args.no_tools is True
    assert args.read_only is True
    assert args.max_steps == 3
    assert args.timeout == 5
    assert args.cwd == "/tmp"
    assert args.verbose is True


def test_help_exits_zero(capsys):
    with pytest.raises(SystemExit) as exit_info:
        build_parser().parse_args(["--help"])
    assert exit_info.value.code == 0
    assert "agentux" in capsys.readouterr().out


def test_version_flag_prints_version(capsys):
    with pytest.raises(SystemExit) as exit_info:
        main(["--version"])
    assert exit_info.value.code == 0
    assert __version__ in capsys.readouterr().out


def test_missing_api_key_is_reported(monkeypatch, capsys):
    monkeypatch.delenv("AGENTUX_API_KEY", raising=False)
    assert main(["say hello"]) == 1
    assert "Configuration error" in capsys.readouterr().err


def test_invalid_base_url_is_reported(monkeypatch, capsys):
    monkeypatch.setenv("AGENTUX_API_KEY", "k")
    monkeypatch.setenv("AGENTUX_BASE_URL", "not-a-url")
    assert main(["hello"]) == 1
    assert "Configuration error" in capsys.readouterr().err


def test_flags_override_environment(monkeypatch, tmp_path):
    monkeypatch.setenv("AGENTUX_API_KEY", "env-key")
    monkeypatch.setenv("AGENTUX_MODEL", "env-model")
    monkeypatch.delenv("AGENTUX_MAX_STEPS", raising=False)

    args = build_parser().parse_args(["--model", "flag-model", "--max-steps", "7", "--cwd", str(tmp_path)])
    config = resolve_config(args)

    assert config.model == "flag-model"
    assert config.max_steps == 7
    assert config.working_dir == str(tmp_path)


def test_config_falls_back_to_environment(monkeypatch):
    monkeypatch.setenv("AGENTUX_API_KEY", "env-key")
    monkeypatch.setenv("AGENTUX_MODEL", "env-model")
    config = resolve_config(build_parser().parse_args(["hello"]))
    assert config.model == "env-model"


def test_no_api_key_is_ever_printed(monkeypatch, capsys):
    """A secret in the environment must not leak into CLI output."""
    monkeypatch.setenv("AGENTUX_API_KEY", "sk-super-secret-value")
    with pytest.raises(SystemExit):
        main(["--version"])
    assert "sk-super-secret-value" not in capsys.readouterr().out
    assert "sk-super-secret-value" not in capsys.readouterr().err


def test_build_agent_wires_tools(monkeypatch, tmp_path):
    from agentux.cli import build_agent

    monkeypatch.setenv("AGENTUX_API_KEY", "k")
    args = build_parser().parse_args(["--cwd", str(tmp_path)])
    agent = build_agent(resolve_config(args), args)

    assert isinstance(agent.registry.get("shell"), ShellTool)
    assert isinstance(agent.registry.get("filesystem"), FilesystemTool)
    assert isinstance(agent.registry.get("project"), ProjectTool)
    assert agent.provider is not None


def test_no_tools_flag_registers_nothing(monkeypatch, tmp_path):
    from agentux.cli import build_agent

    monkeypatch.setenv("AGENTUX_API_KEY", "k")
    args = build_parser().parse_args(["--no-tools", "--cwd", str(tmp_path)])
    agent = build_agent(resolve_config(args), args)

    assert len(agent.registry) == 0


def test_read_only_flag_propagates(monkeypatch, tmp_path):
    from agentux.cli import build_agent

    monkeypatch.setenv("AGENTUX_API_KEY", "k")
    args = build_parser().parse_args(["--read-only", "--cwd", str(tmp_path)])
    agent = build_agent(resolve_config(args), args)

    assert agent.registry.get("filesystem").read_only is True


def test_shell_tool_confirms_by_default(monkeypatch, tmp_path):
    from agentux.cli import build_agent

    monkeypatch.setenv("AGENTUX_API_KEY", "k")
    args = build_parser().parse_args(["--cwd", str(tmp_path)])
    agent = build_agent(resolve_config(args), args)

    assert agent.registry.get("shell").confirm is not None


def test_allow_destructive_disables_the_prompt(monkeypatch, tmp_path):
    from agentux.cli import build_agent

    monkeypatch.setenv("AGENTUX_API_KEY", "k")
    args = build_parser().parse_args(["--allow-destructive", "--cwd", str(tmp_path)])
    agent = build_agent(resolve_config(args), args)

    assert agent.registry.get("shell").allow_destructive is True


def test_single_prompt_runs_and_prints(monkeypatch, capsys):
    """End-to-end through main(), with only the model stubbed out."""
    import asyncio

    from agentux.models import Message

    monkeypatch.setenv("AGENTUX_API_KEY", "k")

    async def fake_run(self, prompt, interactive=False):
        self.history.append(Message(role="assistant", content="All done."))
        return "All done."

    monkeypatch.setattr("agentux.agent.Agent.run", fake_run)

    assert main(["do a thing"]) == 0
    assert "All done." in capsys.readouterr().out


def test_provider_errors_are_reported_and_exit_nonzero(monkeypatch, capsys):
    monkeypatch.setenv("AGENTUX_API_KEY", "k")

    async def fake_run(self, prompt, interactive=False):
        raise AuthenticationError("bad key")

    monkeypatch.setattr("agentux.agent.Agent.run", fake_run)

    assert main(["do a thing"]) == 1
    assert "Authentication failed" in capsys.readouterr().err


def test_unexpected_errors_do_not_traceback(monkeypatch, capsys):
    monkeypatch.setenv("AGENTUX_API_KEY", "k")

    async def fake_run(self, prompt, interactive=False):
        raise ValueError("something odd")

    monkeypatch.setattr("agentux.agent.Agent.run", fake_run)

    assert main(["do a thing"]) == 1
    assert "Unexpected error" in capsys.readouterr().err


def test_explain_error_covers_each_type():
    """Every error class must render without raising."""
    from agentux.cli import explain_error
    from agentux.errors import (
        AgentuxError, MaxStepsError, NetworkError, ProviderError,
        RateLimitError, SafetyError,
    )

    for exc in (
        AuthenticationError("x"), RateLimitError("x"), NetworkError("x"),
        MaxStepsError("x"), SafetyError("x"), ProviderError("x"),
        AgentuxError("x"), ValueError("x"),
    ):
        explain_error(exc)


def test_make_confirmer_denies_on_eof(monkeypatch):
    from agentux.cli import make_confirmer

    confirm = make_confirmer()
    monkeypatch.setattr("rich.console.Console.input", lambda *a, **k: (_ for _ in ()).throw(EOFError()))
    assert confirm("rm -rf /", ["recursive delete"]) is False


def test_make_confirmer_accepts_yes(monkeypatch):
    from agentux.cli import make_confirmer

    confirm = make_confirmer()
    monkeypatch.setattr("rich.console.Console.input", lambda *a, **k: "y")
    assert confirm("rm -rf /", ["recursive delete"]) is True


def test_make_confirmer_denies_on_empty(monkeypatch):
    from agentux.cli import make_confirmer

    confirm = make_confirmer()
    monkeypatch.setattr("rich.console.Console.input", lambda *a, **k: "")
    assert confirm("rm -rf /", ["recursive delete"]) is False


def test_module_entry_point_exists():
    """``python -m agentux`` must be wired up."""
    import importlib

    module = importlib.import_module("agentux.__main__")
    assert callable(module.cli)


# ------------------------------------------------------------- --list-models
def test_list_models_flag_is_parsed():
    assert build_parser().parse_args(["--list-models"]).list_models is True


def test_list_models_prints_models(monkeypatch, capsys):
    monkeypatch.setenv("AGENTUX_API_KEY", "ollama")
    monkeypatch.setenv("AGENTUX_BASE_URL", "http://localhost:11434/v1")

    async def fake_detailed(self):
        return [{"name": "granite4.1:3b", "capabilities": ["completion", "tools"]}]

    monkeypatch.setattr(
        "agentux.providers.openai_compatible.OpenAICompatibleProvider.list_models_detailed",
        fake_detailed,
    )

    assert main(["--list-models"]) == 0
    assert "granite4.1:3b" in capsys.readouterr().out


def test_list_models_warns_about_models_without_tools(monkeypatch, capsys):
    monkeypatch.setenv("AGENTUX_API_KEY", "ollama")

    async def fake_detailed(self):
        return [{"name": "smollm:135m", "capabilities": ["completion"]}]

    monkeypatch.setattr(
        "agentux.providers.openai_compatible.OpenAICompatibleProvider.list_models_detailed",
        fake_detailed,
    )

    assert main(["--list-models"]) == 0
    out = capsys.readouterr().out
    assert "smollm:135m" in out
    assert "tool support" in out


def test_list_models_reports_an_unreachable_server(monkeypatch, capsys):
    from agentux.errors import NetworkError

    monkeypatch.setenv("AGENTUX_API_KEY", "ollama")

    async def boom(self):
        raise NetworkError("Could not reach the provider. Is Ollama running? Try: ollama serve")

    monkeypatch.setattr(
        "agentux.providers.openai_compatible.OpenAICompatibleProvider.list_models_detailed",
        boom,
    )

    assert main(["--list-models"]) == 1
    assert "Network error" in capsys.readouterr().err


def test_list_models_handles_no_models(monkeypatch, capsys):
    monkeypatch.setenv("AGENTUX_API_KEY", "ollama")

    async def empty(self):
        return []

    monkeypatch.setattr(
        "agentux.providers.openai_compatible.OpenAICompatibleProvider.list_models_detailed",
        empty,
    )

    assert main(["--list-models"]) == 1


def test_local_ollama_needs_no_api_key(monkeypatch, capsys):
    """The headline Ollama workflow: two env vars, no credential."""
    monkeypatch.delenv("AGENTUX_API_KEY", raising=False)
    monkeypatch.setenv("AGENTUX_BASE_URL", "http://localhost:11434/v1")
    monkeypatch.setenv("AGENTUX_MODEL", "granite4.1:3b")

    async def fake_detailed(self):
        return [{"name": "granite4.1:3b", "capabilities": ["completion", "tools"]}]

    monkeypatch.setattr(
        "agentux.providers.openai_compatible.OpenAICompatibleProvider.list_models_detailed",
        fake_detailed,
    )

    assert main(["--list-models"]) == 0