Skip to content

Commit

Permalink
Merge branch 'main' into read_links_local
Browse files Browse the repository at this point in the history
  • Loading branch information
killian-scalian authored Dec 10, 2024
2 parents ca0300c + f24a078 commit 9a1bd1b
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 86 deletions.
15 changes: 12 additions & 3 deletions src/antares/model/study.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from antares.api_conf.api_conf import APIconf
from antares.api_conf.request_wrapper import RequestWrapper
from antares.config.local_configuration import LocalConfiguration
from antares.exceptions.exceptions import APIError, StudyCreationError
from antares.exceptions.exceptions import APIError, LinkCreationError, StudyCreationError
from antares.model.area import Area, AreaProperties, AreaUi
from antares.model.binding_constraint import BindingConstraint, BindingConstraintProperties, ConstraintTerm
from antares.model.link import Link, LinkProperties, LinkUi
Expand Down Expand Up @@ -267,9 +267,18 @@ def create_link(
area_to: str,
properties: Optional[LinkProperties] = None,
ui: Optional[LinkUi] = None,
existing_areas: Optional[MappingProxyType[str, Area]] = None,
) -> Link:
link = self._link_service.create_link(area_from, area_to, properties, ui, existing_areas)
missing_areas = [area for area in [area_from, area_to] if area not in self._areas]
if missing_areas:
raise LinkCreationError(area_from, area_to, f"{', '.join(missing_areas)} does not exist")

existing_link = next(
(link for link in self._links.values() if link.area_from == area_from and link.area_to == area_to), None
)
if existing_link:
raise LinkCreationError(area_from, area_to, f"A link from {area_from} to {area_to} already exists")

link = self._link_service.create_link(area_from, area_to, properties, ui)
self._links[link.name] = link
return link

Expand Down
4 changes: 0 additions & 4 deletions src/antares/service/api_services/link_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
#
# This file is part of the Antares project.

from types import MappingProxyType
from typing import Optional

import pandas as pd
Expand All @@ -24,7 +23,6 @@
LinkPropertiesUpdateError,
LinkUiUpdateError,
)
from antares.model.area import Area
from antares.model.link import Link, LinkProperties, LinkUi
from antares.service.base_services import BaseLinkService

Expand All @@ -43,15 +41,13 @@ def create_link(
area_to: str,
properties: Optional[LinkProperties] = None,
ui: Optional[LinkUi] = None,
existing_areas: Optional[MappingProxyType[str, Area]] = None,
) -> Link:
"""
Args:
area_from: area where the link goes from
area_to: area where the link goes to
properties: link's properties. If not provided, AntaresWeb will use its own default values.
ui: link's ui characteristics. If not provided, AntaresWeb will use its own default values.
existing_areas: existing areas from study
Returns:
The created link
Expand Down
2 changes: 0 additions & 2 deletions src/antares/service/base_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
# This file is part of the Antares project.

from abc import ABC, abstractmethod
from types import MappingProxyType
from typing import TYPE_CHECKING, Dict, List, Optional

import pandas as pd
Expand Down Expand Up @@ -322,7 +321,6 @@ def create_link(
area_to: str,
properties: Optional[LinkProperties] = None,
ui: Optional[LinkUi] = None,
existing_areas: Optional[MappingProxyType[str, Area]] = None,
) -> Link:
"""
Args:
Expand Down
14 changes: 1 addition & 13 deletions src/antares/service/local_services/link_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,12 @@
import os

from configparser import DuplicateSectionError
from types import MappingProxyType
from typing import Any, Dict, Optional

import pandas as pd

from antares.config.local_configuration import LocalConfiguration
from antares.exceptions.exceptions import LinkCreationError
from antares.model.area import Area
from antares.model.link import Link, LinkProperties, LinkPropertiesLocal, LinkUi, LinkUiLocal
from antares.service.base_services import BaseLinkService
from antares.tools.contents_tool import sort_ini_sections
Expand All @@ -42,7 +40,6 @@ def create_link(
area_to: str,
properties: Optional[LinkProperties] = None,
ui: Optional[LinkUi] = None,
existing_areas: Optional[MappingProxyType[str, Area]] = None,
) -> Link:
"""
Args:
Expand All @@ -58,16 +55,7 @@ def create_link(
Raises:
LinkCreationError if an area doesn't exist or existing areas have not been provided
"""
areas = dict(sorted({area_from: area_from, area_to: area_to}.items()))

if existing_areas is not None:
for area in areas.keys():
if area not in existing_areas:
raise LinkCreationError(area_from, area_to, f"{area} does not exist.")
else:
raise LinkCreationError(area_from, area_to, "Cannot verify existing areas.")

area_from, area_to = areas.values()
area_from, area_to = sorted([area_from, area_to])

link_dir = self.config.study_path / "input/links" / area_from
os.makedirs(link_dir, exist_ok=True)
Expand Down
84 changes: 74 additions & 10 deletions tests/antares/services/api_services/test_study_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
# SPDX-License-Identifier: MPL-2.0
#
# This file is part of the Antares project.


import pytest
import requests_mock

import re

from unittest.mock import Mock

from antares.api_conf.api_conf import APIconf
from antares.exceptions.exceptions import (
AreaCreationError,
Expand Down Expand Up @@ -134,27 +134,46 @@ def test_create_link_success(self):
base_url = f"https://antares.com/api/v1/studies/{self.study_id}"
url = f"{base_url}/links"
mocker.post(url, status_code=200)
area = "area"
area_to = "area_to"
self.study._areas["area"] = Area(
"area",
self.study._area_service,
Mock(),
Mock(),
Mock(),
)
self.study._areas["area_to"] = Area(
"area_to",
self.study._area_service,
Mock(),
Mock(),
Mock(),
)

raw_url = f"{base_url}/raw?path=input/links/{area}/properties/{area_to}"
raw_url = f"{base_url}/raw?path=input/links/area/properties/area_to"
json_response = {**LinkProperties().model_dump(by_alias=True), **LinkUi().model_dump(by_alias=True)}
mocker.get(raw_url, json=json_response, status_code=200)
link = self.study.create_link(area_from=area, area_to=area_to)
link = self.study.create_link(area_from="area", area_to="area_to")
assert isinstance(link, Link)

def test_create_link_fails(self):
with requests_mock.Mocker() as mocker:
url = f"https://antares.com/api/v1/studies/{self.study_id}/links"
mocker.post(url, json={"description": self.antares_web_description_msg}, status_code=404)
area_from = "area_from"
area_to = "area_to"

self.study._areas["area_from"] = Area(
"area_from",
Mock(),
Mock(),
Mock(),
Mock(),
)
area_to = "area_final"

with pytest.raises(
LinkCreationError,
match=f"Could not create the link {area_from} / {area_to}: {self.antares_web_description_msg}",
match=f"Could not create the link area_from / {area_to}: {area_to} does not exist",
):
self.study.create_link(area_from=area_from, area_to=area_to)
self.study.create_link(area_from="area_from", area_to=area_to)

def test_create_binding_constraint_success(self):
with requests_mock.Mocker() as mocker:
Expand Down Expand Up @@ -268,3 +287,48 @@ def test_create_variant_fails(self):

with pytest.raises(StudyVariantCreationError, match=error_message):
create_variant_api(self.api, self.study_id, variant_name)

def test_create_duplicated_link(self):
area_from = "area_1"
area_to = "area_2"

self.study._areas[area_from] = Area(
area_from,
self.study._area_service,
Mock(),
Mock(),
Mock(),
)
self.study._areas[area_to] = Area(
area_to,
self.study._area_service,
Mock(),
Mock(),
Mock(),
)

self.study._links[f"{area_from}/{area_to}"] = Link(area_from, area_to, Mock())

with pytest.raises(
LinkCreationError,
match=f"Could not create the link {area_from} / {area_to}: A link from {area_from} to {area_to} already exists",
):
self.study.create_link(area_from=area_from, area_to=area_to)

def test_create_link_unknown_area(self):
area_from = "area_fr"
area_to = "area_missing"

self.study._areas[area_from] = Area(
area_from,
self.study._area_service,
Mock(),
Mock(),
Mock(),
)

with pytest.raises(
LinkCreationError,
match=f"Could not create the link {area_from} / {area_to}: {area_to} does not exist",
):
self.study.create_link(area_from=area_from, area_to=area_to)
4 changes: 1 addition & 3 deletions tests/antares/services/local_services/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ def local_study_w_links(tmp_path, local_study_w_areas):
links_to_create = ["fr_at", "at_it", "fr_it"]
for link in links_to_create:
area_from, area_to = link.split("_")
local_study_w_areas.create_link(
area_from=area_from, area_to=area_to, existing_areas=local_study_w_areas.get_areas()
)
local_study_w_areas.create_link(area_from=area_from, area_to=area_to)

return local_study_w_areas

Expand Down
57 changes: 6 additions & 51 deletions tests/antares/services/local_services/test_study.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@
from antares.model.settings.study_settings import DefaultStudySettings, StudySettingsLocal
from antares.model.settings.thematic_trimming import DefaultThematicTrimmingParameters, ThematicTrimmingParametersLocal
from antares.model.study import create_study_local
from antares.service.local_services.link_local import LinkLocalService
from antares.tools.ini_tool import IniFileTypes


Expand Down Expand Up @@ -1622,7 +1621,6 @@ def test_create_link(self, tmp_path, local_study_w_areas):
link_created = local_study_w_areas.create_link(
area_from=area_from,
area_to=area_to,
existing_areas=local_study_w_areas.get_areas(),
)

assert isinstance(link_created, Link)
Expand All @@ -1640,28 +1638,7 @@ def test_unknown_area_errors(self, tmp_path, local_study_w_areas):
LinkCreationError,
match=f"Could not create the link {area_from} / {area_to}: {area_from} does not exist",
):
local_study_w_areas.create_link(
area_from=area_from, area_to=area_to, existing_areas=local_study_w_areas.get_areas()
)

def test_study_areas_not_provided_errors(self, tmp_path, local_study_w_areas):
# With
area_from = "fr"
area_to = "it"
test_service = LinkLocalService(
local_study_w_areas.service.config,
local_study_w_areas.name,
)

with pytest.raises(
LinkCreationError,
match=f"Could not create the link {area_from} / {area_to}: Cannot verify existing areas.",
):
test_service.create_link(
area_from=area_from,
area_to=area_to,
existing_areas=None,
)
local_study_w_areas.create_link(area_from=area_from, area_to=area_to)

def test_create_link_alphabetically(self, tmp_path, local_study):
# Given
Expand All @@ -1675,7 +1652,6 @@ def test_create_link_alphabetically(self, tmp_path, local_study):
link_created = local_study.create_link(
area_from=area_from,
area_to=area_to,
existing_areas=local_study.get_areas(),
)

assert link_created.area_from == "at"
Expand Down Expand Up @@ -1707,7 +1683,6 @@ def test_create_link_sets_ini_content(self, tmp_path, local_study_w_areas):
local_study_w_areas.create_link(
area_from="fr",
area_to="it",
existing_areas=local_study_w_areas.get_areas(),
)

ini_file = tmp_path / local_study_w_areas.name / "input/links" / area_from / "properties.ini"
Expand Down Expand Up @@ -1744,7 +1719,6 @@ def test_created_link_has_default_local_properties(self, tmp_path, local_study_w
created_link = local_study_w_areas.create_link(
area_from="fr",
area_to="it",
existing_areas=local_study_w_areas.get_areas(),
)
ini_file = tmp_path / local_study_w_areas.name / "input/links" / area_from / "properties.ini"
actual_ini = ConfigParser()
Expand Down Expand Up @@ -1789,12 +1763,7 @@ def test_created_link_has_custom_properties(self, tmp_path, local_study_w_areas)

# When
area_from, area_to = link_to_create.split("_")
link_created = local_study_w_areas.create_link(
area_from="fr",
area_to="it",
properties=link_properties,
existing_areas=local_study_w_areas.get_areas(),
)
link_created = local_study_w_areas.create_link(area_from="fr", area_to="it", properties=link_properties)
created_ini_file = tmp_path / local_study_w_areas.name / "input/links" / area_from / "properties.ini"
actual_ini = ConfigParser()
with open(created_ini_file, "r") as file:
Expand Down Expand Up @@ -1850,11 +1819,7 @@ def test_multiple_links_created_from_same_area(self, tmp_path, local_study_w_are
# When
for link in links_to_create:
area_from, area_to = link.split("_")
local_study_w_areas.create_link(
area_from=area_from,
area_to=area_to,
existing_areas=local_study_w_areas.get_areas(),
)
local_study_w_areas.create_link(area_from=area_from, area_to=area_to)

# Then
actual_ini = ConfigParser()
Expand Down Expand Up @@ -1911,11 +1876,7 @@ def test_multiple_links_created_from_same_area_are_alphabetical(self, tmp_path,
# When
for link in links_to_create:
area_from, area_to = link.split("_")
local_study_w_areas.create_link(
area_from=area_from,
area_to=area_to,
existing_areas=local_study_w_areas.get_areas(),
)
local_study_w_areas.create_link(area_from=area_from, area_to=area_to)

# Then
actual_ini = ConfigParser()
Expand All @@ -1937,12 +1898,11 @@ def test_duplicate_links_raises_error(self, tmp_path, local_study_w_links):
# Then
with pytest.raises(
LinkCreationError,
match=f"Could not create the link {area_from} / {area_to}: Link exists already between '{area_from}' and '{area_to}'.",
match=f"Could not create the link {area_from} / {area_to}: A link from {area_from} to {area_to} already exists",
):
local_study_w_links.create_link(
area_from=area_from,
area_to=area_to,
existing_areas=local_study_w_links.get_areas(),
)

def test_created_link_has_default_ui_values(self, tmp_path, local_study_w_areas):
Expand Down Expand Up @@ -1971,11 +1931,7 @@ def test_created_link_has_default_ui_values(self, tmp_path, local_study_w_areas)

# When
area_from, area_to = link_to_create.split(" / ")
local_study_w_areas.create_link(
area_from=area_from,
area_to=area_to,
existing_areas=local_study_w_areas.get_areas(),
)
local_study_w_areas.create_link(area_from=area_from, area_to=area_to)
with open(actual_ini_file, "r") as file:
actual_ini.read_file(file)
file.seek(0)
Expand Down Expand Up @@ -2024,7 +1980,6 @@ def test_created_link_with_custom_ui_values(self, tmp_path, local_study_w_areas)
area_to=area_to,
properties=expected_properties,
ui=expected_ui,
existing_areas=local_study_w_areas.get_areas(),
)
with open(actual_ini_file, "r") as file:
actual_ini.read_file(file)
Expand Down

0 comments on commit 9a1bd1b

Please sign in to comment.