-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtest_run.py
More file actions
450 lines (376 loc) · 15.5 KB
/
test_run.py
File metadata and controls
450 lines (376 loc) · 15.5 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
# type: ignore
import os
from contextlib import asynccontextmanager
from unittest.mock import AsyncMock, Mock, patch
import pytest
from click.testing import CliRunner
from uipath._cli import cli
from uipath._cli.middlewares import MiddlewareResult
def _middleware_continue():
return MiddlewareResult(
should_continue=True,
error_message=None,
should_include_stacktrace=False,
)
async def _empty_async_gen(*args, **kwargs):
"""An async generator that yields nothing (simulates empty runtime.stream)."""
if False: # pragma: no cover
yield
def _make_mock_factory(entrypoints: list[str]):
"""Create a mock runtime factory with given entrypoints."""
mock_factory = Mock()
mock_factory.discover_entrypoints.return_value = entrypoints
mock_factory.get_settings = AsyncMock(return_value=None)
mock_factory.dispose = AsyncMock()
mock_runtime = Mock()
mock_runtime.execute = AsyncMock(return_value=Mock(status="SUCCESSFUL"))
mock_runtime.stream = Mock(side_effect=_empty_async_gen)
mock_runtime.dispose = AsyncMock()
mock_factory.new_runtime = AsyncMock(return_value=mock_runtime)
return mock_factory
@asynccontextmanager
async def _mock_resource_overwrites_context(*args, **kwargs):
yield
@pytest.fixture
def entrypoint():
return "main"
@pytest.fixture
def simple_script() -> str:
if os.path.isfile("mocks/simple_script.py"):
with open("mocks/simple_script.py", "r") as file:
data = file.read()
else:
with open("tests/cli/mocks/simple_script.py", "r") as file:
data = file.read()
return data
@pytest.fixture
def mock_env_vars():
return {
"UIPATH_CONFIG_PATH": "test_config.json",
"UIPATH_JOB_KEY": "test-job-id",
"UIPATH_TRACE_ID": "test-trace-id",
"UIPATH_TRACING_ENABLED": "true",
"UIPATH_PARENT_SPAN_ID": "test-parent-span",
"UIPATH_ROOT_SPAN_ID": "test-root-span",
"UIPATH_ORGANIZATION_ID": "test-org-id",
"UIPATH_TENANT_ID": "test-tenant-id",
"UIPATH_PROCESS_UUID": "test-process-id",
"UIPATH_FOLDER_KEY": "test-folder-key",
"LOG_LEVEL": "DEBUG",
}
def create_uipath_json(script_path: str, entrypoint_name: str = "main"):
"""Helper to create uipath.json with functions."""
return {"functions": {entrypoint_name: f"{script_path}:main"}}
class TestRun:
class TestFileInput:
def test_run_input_file_not_found(
self,
runner: CliRunner,
temp_dir: str,
entrypoint: str,
):
with runner.isolated_filesystem(temp_dir=temp_dir):
script_file = "entrypoint.py"
file_path = os.path.join(temp_dir, script_file)
with open(file_path, "w") as f:
f.write("def main(input): return input")
# Create uipath.json
with open("uipath.json", "w") as f:
import json
json.dump(create_uipath_json(script_file), f)
result = runner.invoke(
cli, ["run", entrypoint, "--file", "not-here.json"]
)
assert result.exit_code != 0
assert "Error: Invalid value for '-f' / '--file'" in result.output
def test_run_invalid_input_file(
self,
runner: CliRunner,
temp_dir: str,
entrypoint: str,
):
file_name = "not-json.txt"
with runner.isolated_filesystem(temp_dir=temp_dir):
script_file = "entrypoint.py"
script_file_path = os.path.join(temp_dir, script_file)
with open(script_file_path, "w") as f:
f.write("def main(input): return input")
file_path = os.path.join(temp_dir, file_name)
with open(file_path, "w") as f:
f.write("file content")
# Create uipath.json
with open("uipath.json", "w") as f:
import json
json.dump(create_uipath_json(script_file_path), f)
result = runner.invoke(cli, ["run", "main", "--file", file_path])
assert result.exit_code == 1
assert "Invalid Input File Extension" in result.output
def test_run_input_file_success(
self,
runner: CliRunner,
temp_dir: str,
entrypoint: str,
):
file_name = "input.json"
json_content = """
{
"input_key": "input_value"
}"""
with runner.isolated_filesystem(temp_dir=temp_dir):
script_file = "entrypoint.py"
script_file_path = os.path.join(temp_dir, script_file)
with open(script_file_path, "w") as f:
f.write("def main(input): return input")
file_path = os.path.join(temp_dir, file_name)
with open(file_path, "w") as f:
f.write(json_content)
# Create uipath.json
with open("uipath.json", "w") as f:
import json
json.dump(create_uipath_json(script_file), f)
with patch("uipath._cli.cli_run.Middlewares.next") as mock_middleware:
mock_middleware.return_value = MiddlewareResult(
should_continue=False,
info_message="Execution succeeded",
error_message=None,
should_include_stacktrace=False,
)
result = runner.invoke(
cli, ["run", entrypoint, "--file", file_path]
)
assert result.exit_code == 0
assert "Successful execution." in result.output
class TestMiddleware:
def test_autodiscover_entrypoint(self, runner: CliRunner, temp_dir: str):
"""When exactly one entrypoint exists, it is auto-resolved."""
with runner.isolated_filesystem(temp_dir=temp_dir):
mock_factory = _make_mock_factory(["my_agent"])
with (
patch(
"uipath._cli.cli_run.Middlewares.next",
return_value=_middleware_continue(),
),
patch(
"uipath._cli.cli_run.UiPathRuntimeFactoryRegistry.get",
return_value=mock_factory,
),
patch(
"uipath._cli.cli_run.ResourceOverwritesContext",
side_effect=_mock_resource_overwrites_context,
),
):
result = runner.invoke(cli, ["run"])
assert result.exit_code == 0, (
f"output: {result.output!r}, exception: {result.exception}"
)
assert "Successful execution." in result.output
mock_factory.new_runtime.assert_awaited_once()
assert mock_factory.new_runtime.call_args[0][0] == "my_agent"
def test_no_entrypoint_multiple_available(
self, runner: CliRunner, temp_dir: str
):
"""When multiple entrypoints exist and none specified, show usage help."""
with runner.isolated_filesystem(temp_dir=temp_dir):
mock_factory = _make_mock_factory(["agent_a", "agent_b"])
with (
patch(
"uipath._cli.cli_run.Middlewares.next",
return_value=_middleware_continue(),
),
patch(
"uipath._cli.cli_run.UiPathRuntimeFactoryRegistry.get",
return_value=mock_factory,
),
):
result = runner.invoke(cli, ["run"])
assert result.exit_code == 0
assert "Available entrypoints:" in result.output
assert "agent_a" in result.output
assert "agent_b" in result.output
assert "Usage: uipath run" in result.output
mock_factory.new_runtime.assert_not_awaited()
def test_no_entrypoint_none_available(self, runner: CliRunner, temp_dir: str):
"""When no entrypoints exist and none specified, show usage help."""
with runner.isolated_filesystem(temp_dir=temp_dir):
mock_factory = _make_mock_factory([])
with (
patch(
"uipath._cli.cli_run.Middlewares.next",
return_value=_middleware_continue(),
),
patch(
"uipath._cli.cli_run.UiPathRuntimeFactoryRegistry.get",
return_value=mock_factory,
),
):
result = runner.invoke(cli, ["run"])
assert result.exit_code == 0
assert "No entrypoints found" in result.output
assert "Usage: uipath run" in result.output
mock_factory.new_runtime.assert_not_awaited()
def test_script_not_found(
self, runner: CliRunner, temp_dir: str, entrypoint: str
):
with runner.isolated_filesystem(temp_dir=temp_dir):
# Create uipath.json but no actual script file
with open("uipath.json", "w") as f:
import json
json.dump(create_uipath_json("nonexistent.py"), f)
result = runner.invoke(cli, ["run", entrypoint])
assert result.exit_code == 1
assert "not found" in result.output.lower()
def test_successful_execution(
self,
runner: CliRunner,
temp_dir: str,
entrypoint: str,
mock_env_vars: dict,
simple_script: str,
):
input_file_name = "input.json"
output_file_name = "output.json"
input_json_content = """
{
"message": "Hello world",
"repeat": 2
}"""
with runner.isolated_filesystem(temp_dir=temp_dir):
# create input file
input_file_path = os.path.join(temp_dir, input_file_name)
output_file_path = os.path.join(temp_dir, output_file_name)
with open(input_file_path, "w") as f:
f.write(input_json_content)
# Create test script
script_file = "entrypoint.py"
script_file_path = os.path.join(temp_dir, script_file)
with open(script_file_path, "w") as f:
f.write(simple_script)
# create uipath.json
with open("uipath.json", "w") as f:
import json
json.dump(create_uipath_json(script_file_path), f)
result = runner.invoke(
cli,
[
"run",
"main",
"--input-file",
input_file_path,
"--output-file",
output_file_path,
],
)
assert result.exit_code == 0
assert "Successful execution." in result.output
assert result.output.count("Hello world") >= 2
assert os.path.exists(output_file_path)
with open(output_file_path, "r") as f:
output = f.read()
assert output.count("Hello world") >= 2
def test_no_main_function_found(
self,
runner: CliRunner,
temp_dir: str,
entrypoint: str,
mock_env_vars: dict,
):
input_file_name = "input.json"
input_json_content = """
{
"message": "Hello world",
"repeat": 2
}"""
with runner.isolated_filesystem(temp_dir=temp_dir):
# create input file
input_file_path = os.path.join(temp_dir, input_file_name)
with open(input_file_path, "w") as f:
f.write(input_json_content)
# Create test script without main function
script_file = "entrypoint.py"
script_file_path = os.path.join(temp_dir, script_file)
with open(script_file_path, "w") as f:
f.write("print(0)")
# create uipath.json
with open("uipath.json", "w") as f:
import json
json.dump(create_uipath_json(script_file), f)
result = runner.invoke(cli, ["run", entrypoint, "{}"])
assert result.exit_code == 1
assert (
"not found" in result.output.lower()
or "missing" in result.output.lower()
)
def test_pydantic_model_execution(
self,
runner: CliRunner,
temp_dir: str,
entrypoint: str,
mock_env_vars: dict,
):
"""Test successful execution with Pydantic models."""
pydantic_script = """
from pydantic import BaseModel, Field
class PersonIn(BaseModel):
name: str
age: int
email: str | None = None
class PersonOut(BaseModel):
name: str
age: int
email: str | None = None
is_adult: bool
greeting: str
def main(input_data: PersonIn) -> PersonOut:
return PersonOut(
name=input_data.name,
age=input_data.age,
email=input_data.email,
is_adult=input_data.age >= 18,
greeting=f"Hello, {input_data.name}!"
)
"""
input_file_name = "input.json"
output_file_name = "output.json"
input_json_content = """
{
"name": "John Doe",
"age": 25,
"email": "john@example.com"
}"""
with runner.isolated_filesystem(temp_dir=temp_dir):
# create input file
input_file_path = os.path.join(temp_dir, input_file_name)
output_file_path = os.path.join(temp_dir, output_file_name)
with open(input_file_path, "w") as f:
f.write(input_json_content)
# Create test script
script_file = "entrypoint.py"
script_file_path = os.path.join(temp_dir, script_file)
with open(script_file_path, "w") as f:
f.write(pydantic_script)
# create uipath.json
with open("uipath.json", "w") as f:
import json
json.dump(create_uipath_json(script_file_path), f)
result = runner.invoke(
cli,
[
"run",
"main",
"--input-file",
input_file_path,
"--output-file",
output_file_path,
],
)
assert result.exit_code == 0
assert "Successful execution." in result.output
assert os.path.exists(output_file_path)
with open(output_file_path, "r") as f:
import json
output_data = json.load(f)
assert output_data["name"] == "John Doe"
assert output_data["age"] == 25
assert output_data["email"] == "john@example.com"
assert output_data["is_adult"] is True
assert output_data["greeting"] == "Hello, John Doe!"