Skip to content

Commit 3d4514d

Browse files
committed
improve monitor validation message for syntax error
1 parent 5621c7f commit 3d4514d

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

src/components/http_server/monitor_routes.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,9 @@ async def monitor_validate(request: Request) -> Response:
190190
"error": e.get_error_message(include_monitor_name=False),
191191
}
192192
return web.json_response(error_response, status=400)
193+
except SyntaxError as e:
194+
error_response = {"status": "error", "error": f"'{e.args[1][3]}' {e.msg}"}
195+
return web.json_response(error_response, status=400)
193196
except Exception as e:
194197
error_response = {"status": "error", "error": str(e)}
195198
_logger.error(traceback.format_exc().strip())

tests/components/http_server/test_monitor_routes.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -381,22 +381,32 @@ async def test_monitor_validate_check_fail():
381381
}
382382

383383

384+
async def test_monitor_validate_syntax_error(mocker):
385+
"""The 'monitor validate' route should return an error if the provided module code has any
386+
errors"""
387+
request_payload = {
388+
"monitor_code": "print('a",
389+
}
390+
391+
url = BASE_URL + "/validate"
392+
async with aiohttp.ClientSession() as session:
393+
async with session.post(url, json=request_payload) as response:
394+
assert await response.json() == {
395+
"status": "error",
396+
"error": "'print('a' unterminated string literal (detected at line 1)",
397+
}
398+
399+
384400
@pytest.mark.parametrize(
385401
"monitor_code, expected_error",
386402
[
387403
("something", "name 'something' is not defined"),
388404
("import time;\n\ntime.abc()", "module 'time' has no attribute 'abc'"),
389-
(
390-
"print('a",
391-
"unterminated string literal (detected at line 1) ({monitor_name}.py, line 1)",
392-
),
393405
],
394406
)
395407
async def test_monitor_validate_invalid_monitor_code(mocker, monitor_code, expected_error):
396408
"""The 'monitor validate' route should return an error if the provided module code has any
397409
errors"""
398-
check_monitor_spy: MagicMock = mocker.spy(monitors_loader, "check_monitor")
399-
400410
request_payload = {
401411
"monitor_code": monitor_code,
402412
}
@@ -406,7 +416,7 @@ async def test_monitor_validate_invalid_monitor_code(mocker, monitor_code, expec
406416
async with session.post(url, json=request_payload) as response:
407417
assert await response.json() == {
408418
"status": "error",
409-
"error": expected_error.format(monitor_name=check_monitor_spy.call_args.args[0]),
419+
"error": expected_error,
410420
}
411421

412422

0 commit comments

Comments
 (0)