Skip to content

Commit

Permalink
Merge branch 'dev' into fix/ANT-2543-fix-user-name-display-in-commands
Browse files Browse the repository at this point in the history
  • Loading branch information
sylvlecl authored Jan 15, 2025
2 parents 8e9d56e + 81c5672 commit dc60b8a
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 19 deletions.
3 changes: 1 addition & 2 deletions antarest/core/tasks/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,11 +488,10 @@ def _run_task(

try:
with db():
result_msg = f"{err_msg}\nSee the logs for detailed information and the error traceback."
db.session.query(TaskJob).filter(TaskJob.id == task_id).update(
{
TaskJob.status: TaskStatus.FAILED.value,
TaskJob.result_msg: result_msg,
TaskJob.result_msg: str(exc),
TaskJob.result_status: False,
TaskJob.completion_date: datetime.datetime.utcnow(),
}
Expand Down
15 changes: 10 additions & 5 deletions antarest/study/storage/variantstudy/variant_study_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
from antarest.core.filetransfer.model import FileDownloadTaskDTO
from antarest.core.interfaces.cache import ICache
from antarest.core.interfaces.eventbus import Event, EventChannelDirectory, EventType, IEventBus
from antarest.core.jwt import DEFAULT_ADMIN_USER, JWTUser
from antarest.core.jwt import DEFAULT_ADMIN_USER
from antarest.core.model import JSON, PermissionInfo, PublicMode, StudyPermissionType
from antarest.core.requests import RequestParameters, UserHasNotPermissionError
from antarest.core.serialization import to_json_string
Expand Down Expand Up @@ -971,20 +971,25 @@ def _safe_generation(self, metadata: VariantStudy, timeout: int = DEFAULT_AWAIT_
task_id = self.generate_task(metadata)
self.task_service.await_task(task_id, timeout)
result = self.task_service.status_task(task_id, RequestParameters(DEFAULT_ADMIN_USER))
if result.result and result.result.success:
if not result.result:
raise ValueError("No task result")
if result.result.success:
# OK, the study has been generated
return
raise ValueError("No task result or result failed")
# The variant generation failed, we have to raise a clear exception.
error_msg = result.result.message
stripped_msg = error_msg.removeprefix(f"417: Failed to generate variant study {metadata.id}")
raise ValueError(stripped_msg)

except concurrent.futures.TimeoutError as e:
# Raise a REQUEST_TIMEOUT error (408)
logger.error(f"⚡ Timeout while generating variant study {metadata.id}", exc_info=e)
raise VariantGenerationTimeoutError(f"Timeout while generating {metadata.id}") from None
raise VariantGenerationTimeoutError(f"Timeout while generating variant {metadata.id}") from None

except Exception as e:
# raise a EXPECTATION_FAILED error (417)
logger.error(f"⚡ Fail to generate variant study {metadata.id}", exc_info=e)
raise VariantGenerationError(f"Error while generating {metadata.id}") from None
raise VariantGenerationError(f"Error while generating variant {metadata.id} {e}") from None

@staticmethod
def _get_snapshot_last_executed_command_index(
Expand Down
5 changes: 1 addition & 4 deletions tests/core/test_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,7 @@ def action_fail(notifier: ITaskNotifier) -> TaskResult:
assert failed_task is not None
assert failed_task.status == TaskStatus.FAILED.value
assert failed_task.result_status is False
assert failed_task.result_msg == (
f"Task {failed_id} failed: Unhandled exception this action failed"
f"\nSee the logs for detailed information and the error traceback."
)
assert failed_task.result_msg == "this action failed"
assert failed_task.completion_date is not None

# Test Case: add a task that succeeds and wait for it
Expand Down
12 changes: 9 additions & 3 deletions tests/integration/raw_studies_blueprint/test_fetch_raw_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ def _check_endpoint_response(
assert task["status"] == TaskStatus.FAILED.value
assert not task["result"]["success"]
assert expected_msg in task["result"]["message"]
# Check the message users will see inside the front-end (GET /comments endpoint will fail)
res = client.get(f"/v1/studies/{study_id}/comments")
assert res.status_code == 417
response = res.json()
assert response["exception"] == "VariantGenerationError"
assert response["description"] == f"Error while generating variant {study_id} : {expected_msg}"
# We have to delete the command to make the variant "clean" again.
res = client.get(f"/v1/studies/{study_id}/commands")
cmd_id = res.json()[-1]["id"]
Expand Down Expand Up @@ -365,7 +371,7 @@ def test_delete_raw(

# try to delete expansion folder
res = client.delete(f"/v1/studies/{internal_study_id}/raw?path=/user/expansion")
expected_msg = "you are not allowed to delete this resource"
expected_msg = "you are not allowed to delete this resource : expansion"
_check_endpoint_response(study_type, res, client, internal_study_id, expected_msg, "ResourceDeletionNotAllowed")

# try to delete a file which isn't inside the 'User' folder
Expand Down Expand Up @@ -447,13 +453,13 @@ def test_create_folder(

# try to create a folder inside the 'expansion` folder
expansion_folder = "user/expansion/wrong_folder"
expected_msg = "you are not allowed to create a resource here"
expected_msg = "you are not allowed to create a resource here: expansion/wrong_folder"
res = client.put(raw_url, params={"path": expansion_folder, **additional_params})
_check_endpoint_response(study_type, res, client, internal_study_id, expected_msg, "FolderCreationNotAllowed")

# try to create an already existing folder
existing_folder = "user/folder_1"
expected_msg = "the given resource already exists"
expected_msg = "the given resource already exists: folder_1"
res = client.put(raw_url, params={"path": existing_folder, **additional_params})
_check_endpoint_response(study_type, res, client, internal_study_id, expected_msg, "FolderCreationNotAllowed")

Expand Down
7 changes: 2 additions & 5 deletions tests/storage/business/test_variant_study_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,6 @@ def test_get(tmp_path: str, project_path) -> None:
data = {"titi": 43}
sub_route = "settings"

path = path_study / "settings"
key = "titi"

study = Mock()
study.get.return_value = data
study_factory = Mock()
Expand Down Expand Up @@ -98,13 +95,13 @@ def task_status(*args):
status=TaskStatus.COMPLETED,
creation_date_utc="",
completion_date_utc=None,
result=TaskResult(success=False, message=""),
result=TaskResult(success=False, message="error message"),
),
]:
yield t

study_service.task_service.status_task.side_effect = task_status()
with pytest.raises(VariantGenerationError, match="Error while generating study2.py"):
with pytest.raises(VariantGenerationError, match="Error while generating variant study2.py error message"):
study_service.get(metadata=metadata, url=sub_route, depth=2)
study_service.task_service.await_task.assert_called()

Expand Down

0 comments on commit dc60b8a

Please sign in to comment.