Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(commands): it is now impossible to create a study with an empty id #1531

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion antarest/study/business/area_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,11 @@ def remove_layer(self, study: RawStudy, layer_id: str) -> None:
def create_area(
self, study: Study, area_creation_info: AreaCreationDTO
) -> AreaInfoDTO:
area_id = transform_name_to_id(area_creation_info.name)
if area_id == "":
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Je recommande if not area_id.

raise ValueError(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Si tu lèves une exception de type ValueError, cela va causer une erreur 500, ce qui ne serait pas très utile. Il serait préférable d'utiliser une exception spécifique comme ValidationError (de Pydantic), qui générerait une erreur 422. En général, il est préférable d'éviter d'utiliser des exceptions de la bibliothèque standard et plutôt utiliser une sous-classe de Exception. Pour les managers, nous avons pris l'habitude de lever des exceptions de type HTTPException. Étant donné que les managers ne sont utilisés que par les fonctions qui implémentent un endpoint, utiliser une sous-classe de HTTPException est tout à fait acceptable, donc nous pouvons partir là-dessus.

f"Area name : {area_creation_info.name} only contains forbidden characters"
)
file_study = self.storage_service.get_storage(study).get_raw(study)
command = CreateArea(
area_name=area_creation_info.name,
Expand All @@ -342,7 +347,6 @@ def create_area(
execute_or_add_commands(
study, file_study, [command], self.storage_service
)
area_id = transform_name_to_id(area_creation_info.name)
patch = self.patch_service.get(study)
patch.areas = patch.areas or {}
patch.areas[area_id] = area_creation_info.metadata or PatchArea()
Expand Down
22 changes: 15 additions & 7 deletions antarest/study/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -1918,14 +1918,22 @@ def create_area(
study = self.get_study(uuid)
assert_permission(params.user, study, StudyPermissionType.WRITE)
self._assert_study_unarchived(study)
new_area = self.areas.create_area(study, area_creation_dto)
self.event_bus.push(
Event(
type=EventType.STUDY_DATA_EDITED,
payload=study.to_json_summary(),
permissions=PermissionInfo.from_study(study),
try:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Il n'est pas vraiment nécessaire d'utiliser un gestionnaire d'exception ici uniquement pour enregistrer un message d'erreur, car les exceptions non gérées sont déjà signalées lors de la gestion de l'erreur 500.

new_area = self.areas.create_area(study, area_creation_dto)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

À mon avis, pour vérifier le format du nom de la zone, on pourrait utiliser une regex, par exemple :

class AreaCreationDTO(BaseModel):
    name: Field(regex=r"[\w(),&-][ \w(),&-]*")
    type: AreaType
    metadata: Optional[PatchArea]
    set: Optional[List[str]]

En procédant ainsi, la validation se ferra directement au niveau du end point.

except Exception as e:
logger.error(
f"Exception occurs while creating the area : {e}",
exc_info=True,
)
raise
else:
self.event_bus.push(
Event(
type=EventType.STUDY_DATA_EDITED,
payload=study.to_json_summary(),
permissions=PermissionInfo.from_study(study),
)
)
)
return new_area

def create_link(
Expand Down
11 changes: 9 additions & 2 deletions antarest/study/storage/variantstudy/model/command/create_area.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,21 @@ def _apply_config(
raise ValueError()

area_id = transform_name_to_id(self.area_name)

if area_id == "":
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

À remplacer par if not area_id

return (
CommandOutput(
status=False,
message=f"Area name '{self.area_name}' only contains forbidden characters",
),
{},
)
if area_id in study_data.areas.keys():
return (
CommandOutput(
status=False,
message=f"Area '{self.area_name}' already exists and could not be created",
),
dict(),
{},
)

study_data.areas[area_id] = Area(
Expand Down
18 changes: 18 additions & 0 deletions tests/integration/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,24 @@ def test_area_management(app: FastAPI):
"exception": "CommandApplicationError",
}

res = client.post(
f"/v1/studies/{study_id}/commands",
headers={
"Authorization": f'Bearer {admin_credentials["access_token"]}'
},
json=[
{
"action": CommandName.CREATE_AREA.value,
"args": {"area_name": "%%%"},
}
],
)
assert res.status_code == 500
assert res.json() == {
"description": "Area name '%%%' only contains forbidden characters",
"exception": "CommandApplicationError",
}

client.post(
f"/v1/studies/{study_id}/areas",
headers={
Expand Down
7 changes: 7 additions & 0 deletions tests/storage/business/test_arealink_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,13 @@ def test_area_crud(
],
RequestParameters(DEFAULT_ADMIN_USER),
)
with pytest.raises(
ValueError,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Proposer une autre exception.

match="Area name : %% only contains forbidden characters",
):
area_manager.create_area(
study, AreaCreationDTO(name="%%", type=AreaType.AREA)
)


def test_get_all_area():
Expand Down