forked from OpenHands/OpenHands
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_cli_commands.py
More file actions
368 lines (301 loc) · 14.8 KB
/
Copy pathtest_cli_commands.py
File metadata and controls
368 lines (301 loc) · 14.8 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
import asyncio
from io import StringIO
from unittest.mock import AsyncMock, Mock, patch
import pytest
from prompt_toolkit.application import create_app_session
from prompt_toolkit.input import create_pipe_input
from prompt_toolkit.output import create_output
from openhands.core.cli import main
from openhands.core.config import AppConfig
from openhands.core.schema import AgentState
from openhands.events.action import ChangeAgentStateAction, MessageAction
from openhands.events.event import EventSource
from openhands.events.observation import AgentStateChangedObservation
class MockEventStream:
def __init__(self):
self._subscribers = {}
self.cur_id = 0
self.events = []
def subscribe(self, subscriber_id, callback, callback_id=None):
if subscriber_id not in self._subscribers:
self._subscribers[subscriber_id] = {}
self._subscribers[subscriber_id][callback_id] = callback
return callback_id
def unsubscribe(self, subscriber_id, callback_id):
if (
subscriber_id in self._subscribers
and callback_id in self._subscribers[subscriber_id]
):
del self._subscribers[subscriber_id][callback_id]
def add_event(self, event, source):
event._id = self.cur_id
self.cur_id += 1
event._source = source
event._timestamp = '2023-01-01T00:00:00'
self.events.append((event, source))
for subscriber_id in self._subscribers:
for callback_id, callback in self._subscribers[subscriber_id].items():
if asyncio.iscoroutinefunction(callback):
asyncio.create_task(callback(event))
else:
callback(event)
@pytest.fixture
def mock_agent():
with patch('openhands.core.cli.create_agent') as mock_create_agent:
mock_agent_instance = AsyncMock()
mock_agent_instance.name = 'test-agent'
mock_agent_instance.llm = AsyncMock()
mock_agent_instance.llm.config = AsyncMock()
mock_agent_instance.llm.config.model = 'test-model'
mock_agent_instance.llm.config.base_url = 'http://test'
mock_agent_instance.llm.config.max_message_chars = 1000
mock_agent_instance.config = AsyncMock()
mock_agent_instance.config.disabled_microagents = []
mock_agent_instance.sandbox_plugins = []
mock_agent_instance.prompt_manager = AsyncMock()
mock_create_agent.return_value = mock_agent_instance
yield mock_agent_instance
@pytest.fixture
def mock_controller():
with patch('openhands.core.cli.create_controller') as mock_create_controller:
mock_controller_instance = AsyncMock()
mock_controller_instance.state.agent_state = None
# Mock run_until_done to finish immediately
mock_controller_instance.run_until_done = AsyncMock(return_value=None)
mock_create_controller.return_value = (mock_controller_instance, None)
yield mock_controller_instance
@pytest.fixture
def mock_config():
with patch('openhands.core.cli.parse_arguments') as mock_parse_args:
args = Mock()
args.file = None
args.task = None
args.directory = None
mock_parse_args.return_value = args
with patch('openhands.core.cli.setup_config_from_args') as mock_setup_config:
mock_config = AppConfig()
mock_config.cli_multiline_input = False
mock_config.security = Mock()
mock_config.security.confirmation_mode = False
mock_config.sandbox = Mock()
mock_config.sandbox.selected_repo = None
mock_config.workspace_base = '/test'
mock_config.runtime = 'local' # Important for /init test
mock_setup_config.return_value = mock_config
yield mock_config
@pytest.fixture
def mock_memory():
with patch('openhands.core.cli.create_memory') as mock_create_memory:
mock_memory_instance = AsyncMock()
mock_create_memory.return_value = mock_memory_instance
yield mock_memory_instance
@pytest.fixture
def mock_read_task():
with patch('openhands.core.cli.read_task') as mock_read_task:
mock_read_task.return_value = None
yield mock_read_task
@pytest.fixture
def mock_runtime():
with patch('openhands.core.cli.create_runtime') as mock_create_runtime:
mock_runtime_instance = AsyncMock()
mock_event_stream = MockEventStream()
mock_runtime_instance.event_stream = mock_event_stream
mock_runtime_instance.connect = AsyncMock()
# Ensure status_callback is None
mock_runtime_instance.status_callback = None
# Mock get_microagents_from_selected_repo
mock_runtime_instance.get_microagents_from_selected_repo = Mock(return_value=[])
mock_create_runtime.return_value = mock_runtime_instance
yield mock_runtime_instance
@pytest.mark.asyncio
async def test_help_command(
mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
):
buffer = StringIO()
with patch('openhands.core.cli.manage_openhands_file', return_value=True):
with patch(
'openhands.core.cli.check_folder_security_agreement', return_value=True
):
with patch('openhands.core.cli.read_prompt_input') as mock_prompt:
# Setup to return /help first, then simulate an exit
mock_prompt.side_effect = ['/help', '/exit']
with create_app_session(
input=create_pipe_input(), output=create_output(stdout=buffer)
):
mock_controller.status_callback = None
main_task = asyncio.create_task(main(asyncio.get_event_loop()))
agent_ready_event = AgentStateChangedObservation(
agent_state=AgentState.AWAITING_USER_INPUT,
content='Agent is ready for user input',
)
mock_runtime.event_stream.add_event(
agent_ready_event, EventSource.AGENT
)
await asyncio.sleep(0.1)
try:
await asyncio.wait_for(main_task, timeout=0.5)
except asyncio.TimeoutError:
main_task.cancel()
try:
await main_task
except asyncio.CancelledError:
pass
buffer.seek(0)
output = buffer.read()
# Verify help output was displayed
assert 'OpenHands CLI' in output
assert 'Things that you can try' in output
assert 'Interactive commands' in output
assert '/help' in output
assert '/exit' in output
# Verify the help command didn't add a MessageAction to the event stream
message_actions = [
event
for event, _ in mock_runtime.event_stream.events
if isinstance(event, MessageAction)
]
assert len(message_actions) == 0
@pytest.mark.asyncio
async def test_exit_command(
mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
):
buffer = StringIO()
with patch('openhands.core.cli.manage_openhands_file', return_value=True):
with patch(
'openhands.core.cli.check_folder_security_agreement', return_value=True
):
with patch('openhands.core.cli.read_prompt_input') as mock_prompt:
# First prompt call returns /exit
mock_prompt.side_effect = ['/exit']
with patch('openhands.core.cli.shutdown') as mock_shutdown:
with create_app_session(
input=create_pipe_input(), output=create_output(stdout=buffer)
):
mock_controller.status_callback = None
main_task = asyncio.create_task(main(asyncio.get_event_loop()))
agent_ready_event = AgentStateChangedObservation(
agent_state=AgentState.AWAITING_USER_INPUT,
content='Agent is ready for user input',
)
mock_runtime.event_stream.add_event(
agent_ready_event, EventSource.AGENT
)
await asyncio.sleep(0.1)
try:
await asyncio.wait_for(main_task, timeout=0.5)
except asyncio.TimeoutError:
main_task.cancel()
try:
await main_task
except asyncio.CancelledError:
pass
# Verify that the exit command sent a STOPPED state change event
state_change_events = [
event
for event, source in mock_runtime.event_stream.events
if isinstance(event, ChangeAgentStateAction)
and event.agent_state == AgentState.STOPPED
and source == EventSource.ENVIRONMENT
]
assert len(state_change_events) == 1
# Verify shutdown was called
mock_shutdown.assert_called_once()
@pytest.mark.asyncio
async def test_init_command(
mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
):
buffer = StringIO()
with patch('openhands.core.cli.manage_openhands_file', return_value=True):
with patch(
'openhands.core.cli.check_folder_security_agreement', return_value=True
):
with patch('openhands.core.cli.read_prompt_input') as mock_prompt:
# First prompt call returns /init, second call returns /exit
mock_prompt.side_effect = ['/init', '/exit']
with patch('openhands.core.cli.init_repository') as mock_init_repo:
with create_app_session(
input=create_pipe_input(), output=create_output(stdout=buffer)
):
mock_controller.status_callback = None
main_task = asyncio.create_task(main(asyncio.get_event_loop()))
agent_ready_event = AgentStateChangedObservation(
agent_state=AgentState.AWAITING_USER_INPUT,
content='Agent is ready for user input',
)
mock_runtime.event_stream.add_event(
agent_ready_event, EventSource.AGENT
)
await asyncio.sleep(0.1)
try:
await asyncio.wait_for(main_task, timeout=0.5)
except asyncio.TimeoutError:
main_task.cancel()
try:
await main_task
except asyncio.CancelledError:
pass
# Verify init_repository was called with the correct directory
mock_init_repo.assert_called_once_with('/test')
# Verify that a MessageAction was sent with the repository creation prompt
message_events = [
event
for event, source in mock_runtime.event_stream.events
if isinstance(event, MessageAction)
and 'Please explore this repository' in event.content
and source == EventSource.USER
]
assert len(message_events) == 1
@pytest.mark.asyncio
async def test_init_command_non_local_runtime(
mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
):
buffer = StringIO()
# Set runtime to non-local for this test
mock_config.runtime = 'remote'
with patch('openhands.core.cli.manage_openhands_file', return_value=True):
with patch(
'openhands.core.cli.check_folder_security_agreement', return_value=True
):
with patch('openhands.core.cli.read_prompt_input') as mock_prompt:
# First prompt call returns /init, second call returns /exit
mock_prompt.side_effect = ['/init', '/exit']
with patch('openhands.core.cli.init_repository') as mock_init_repo:
with create_app_session(
input=create_pipe_input(), output=create_output(stdout=buffer)
):
mock_controller.status_callback = None
main_task = asyncio.create_task(main(asyncio.get_event_loop()))
# Send AgentStateChangedObservation to trigger prompt
agent_ready_event = AgentStateChangedObservation(
agent_state=AgentState.AWAITING_USER_INPUT,
content='Agent is ready for user input',
)
mock_runtime.event_stream.add_event(
agent_ready_event, EventSource.AGENT
)
await asyncio.sleep(0.1)
try:
await asyncio.wait_for(main_task, timeout=0.5)
except asyncio.TimeoutError:
main_task.cancel()
try:
await main_task
except asyncio.CancelledError:
pass
buffer.seek(0)
output = buffer.read()
# Verify error message was displayed
assert (
'Repository initialization through the CLI is only supported for local runtime'
in output
)
# Verify init_repository was not called
mock_init_repo.assert_not_called()
# Verify no MessageAction was sent for repository creation
message_events = [
event
for event, _ in mock_runtime.event_stream.events
if isinstance(event, MessageAction)
and 'Please explore this repository' in event.content
]
assert len(message_events) == 0