From fc7e221b9344db04306fa176df3bf74c251fc222 Mon Sep 17 00:00:00 2001 From: Tristan Chuine Date: Fri, 22 Mar 2024 12:26:36 +0100 Subject: [PATCH] clean PR --- pom.xml | 5 + .../service/VoltageInitResultContext.java | 26 ++--- .../server/service/VoltageInitService.java | 9 +- .../VoltageInitParametersService.java | 88 ++++++--------- .../server/SupervisionControllerTest.java | 15 ++- .../server/VoltageInitControllerTest.java | 80 +++++++------ .../server/VoltageInitParametersTest.java | 105 +++++++++++------- .../service/ReportServiceTest.java | 24 ++-- 8 files changed, 196 insertions(+), 156 deletions(-) diff --git a/pom.xml b/pom.xml index 91cc6c2..3d7db5e 100644 --- a/pom.xml +++ b/pom.xml @@ -199,6 +199,11 @@ assertj-guava test + + org.junit.vintage + junit-vintage-engine + test + org.mockito mockito-core diff --git a/src/main/java/org/gridsuite/voltageinit/server/service/VoltageInitResultContext.java b/src/main/java/org/gridsuite/voltageinit/server/service/VoltageInitResultContext.java index cb0cbcc..f072c67 100644 --- a/src/main/java/org/gridsuite/voltageinit/server/service/VoltageInitResultContext.java +++ b/src/main/java/org/gridsuite/voltageinit/server/service/VoltageInitResultContext.java @@ -45,12 +45,11 @@ public VoltageInitResultContext(UUID resultUuid, VoltageInitRunContext runContex } private static String getNonNullHeader(MessageHeaders headers, String name) { - final String header = headers.get(name, String.class); + String header = (String) headers.get(name); if (header == null) { throw new PowsyblException("Header '" + name + "' not found"); - } else { - return header; } + return header; } public static VoltageInitResultContext fromMessage(Message message) { @@ -58,16 +57,17 @@ public static VoltageInitResultContext fromMessage(Message message) { MessageHeaders headers = message.getHeaders(); UUID resultUuid = UUID.fromString(getNonNullHeader(headers, "resultUuid")); UUID networkUuid = UUID.fromString(getNonNullHeader(headers, "networkUuid")); - String variantId = headers.get(VARIANT_ID_HEADER, String.class); - String receiver = headers.get(HEADER_RECEIVER, String.class); - String userId = headers.get(HEADER_USER_ID, String.class); - @SuppressWarnings("unchecked") - Map voltageLevelsIdsRestricted = headers.get(VOLTAGE_LEVELS_IDS_RESTRICTED, Map.class); - UUID parametersUuid = headers.containsKey(PARAMETERS_UUID_HEADER) ? UUID.fromString(headers.get(PARAMETERS_UUID_HEADER, String.class)) : null; - UUID reportUuid = headers.containsKey(REPORT_UUID_HEADER) ? UUID.fromString(headers.get(REPORT_UUID_HEADER, String.class)) : null; - String reporterId = headers.containsKey(REPORTER_ID_HEADER) ? headers.get(REPORTER_ID_HEADER, String.class) : null; - String reportType = headers.containsKey(REPORT_TYPE_HEADER) ? headers.get(REPORT_TYPE_HEADER, String.class) : null; - return new VoltageInitResultContext(resultUuid, new VoltageInitRunContext(networkUuid, variantId, receiver, reportUuid, reporterId, reportType, userId, parametersUuid, voltageLevelsIdsRestricted)); + String variantId = (String) headers.get(VARIANT_ID_HEADER); + String receiver = (String) headers.get(HEADER_RECEIVER); + String userId = (String) headers.get(HEADER_USER_ID); + Map voltageLevelsIdsRestricted = (Map) headers.get(VOLTAGE_LEVELS_IDS_RESTRICTED); + + UUID parametersUuid = headers.containsKey(PARAMETERS_UUID_HEADER) ? UUID.fromString((String) headers.get(PARAMETERS_UUID_HEADER)) : null; + UUID reportUuid = headers.containsKey(REPORT_UUID_HEADER) ? UUID.fromString((String) headers.get(REPORT_UUID_HEADER)) : null; + String reporterId = headers.containsKey(REPORTER_ID_HEADER) ? (String) headers.get(REPORTER_ID_HEADER) : null; + String reportType = headers.containsKey(REPORT_TYPE_HEADER) ? (String) headers.get(REPORT_TYPE_HEADER) : null; + VoltageInitRunContext runContext = new VoltageInitRunContext(networkUuid, variantId, receiver, reportUuid, reporterId, reportType, userId, parametersUuid, voltageLevelsIdsRestricted); + return new VoltageInitResultContext(resultUuid, runContext); } public Message toMessage() { diff --git a/src/main/java/org/gridsuite/voltageinit/server/service/VoltageInitService.java b/src/main/java/org/gridsuite/voltageinit/server/service/VoltageInitService.java index 74bddb7..b0090f4 100644 --- a/src/main/java/org/gridsuite/voltageinit/server/service/VoltageInitService.java +++ b/src/main/java/org/gridsuite/voltageinit/server/service/VoltageInitService.java @@ -6,12 +6,15 @@ */ package org.gridsuite.voltageinit.server.service; +import com.powsybl.network.store.client.NetworkStoreService; + import org.gridsuite.voltageinit.server.dto.ReactiveSlack; import org.gridsuite.voltageinit.server.dto.VoltageInitResult; import org.gridsuite.voltageinit.server.dto.VoltageInitStatus; import org.gridsuite.voltageinit.server.entities.VoltageInitResultEntity; import org.gridsuite.voltageinit.server.repository.VoltageInitResultRepository; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -22,6 +25,7 @@ /** * @author Etienne Homer */ +@ComponentScan(basePackageClasses = {NetworkStoreService.class}) @Service public class VoltageInitService { @Autowired @@ -45,8 +49,9 @@ public VoltageInitService(NotificationService notificationService, } public UUID runAndSaveResult(UUID networkUuid, String variantId, String receiver, UUID reportUuid, String reporterId, String userId, String reportType, UUID parametersUuid) { - final VoltageInitRunContext runContext = new VoltageInitRunContext(networkUuid, variantId, receiver, reportUuid, reporterId, reportType, userId, parametersUuid); - final UUID resultUuid = uuidGeneratorService.generate(); + VoltageInitRunContext runContext = new VoltageInitRunContext(networkUuid, variantId, receiver, reportUuid, reporterId, reportType, userId, parametersUuid, new HashMap<>()); + Objects.requireNonNull(runContext); + var resultUuid = uuidGeneratorService.generate(); // update status to running status setStatus(List.of(resultUuid), VoltageInitStatus.RUNNING.name()); diff --git a/src/main/java/org/gridsuite/voltageinit/server/service/parameters/VoltageInitParametersService.java b/src/main/java/org/gridsuite/voltageinit/server/service/parameters/VoltageInitParametersService.java index 13500a4..9f3b09a 100644 --- a/src/main/java/org/gridsuite/voltageinit/server/service/parameters/VoltageInitParametersService.java +++ b/src/main/java/org/gridsuite/voltageinit/server/service/parameters/VoltageInitParametersService.java @@ -54,13 +54,13 @@ public UUID createParameters(VoltageInitParametersInfos parametersInfos) { } public Optional duplicateParameters(UUID sourceParametersId) { - return voltageInitParametersRepository.findById(sourceParametersId) - .map(VoltageInitParametersEntity::toVoltageInitParametersInfos) - .map(VoltageInitParametersEntity::new) - .map(entity -> { - voltageInitParametersRepository.save(entity); - return entity.getId(); - }); + Optional sourceVoltageInitParametersInfos = voltageInitParametersRepository.findById(sourceParametersId).map(VoltageInitParametersEntity::toVoltageInitParametersInfos); + if (sourceVoltageInitParametersInfos.isPresent()) { + VoltageInitParametersEntity entity = new VoltageInitParametersEntity(sourceVoltageInitParametersInfos.get()); + voltageInitParametersRepository.save(entity); + return Optional.of(entity.getId()); + } + return Optional.empty(); } public VoltageInitParametersInfos getParameters(UUID parametersUuid) { @@ -101,10 +101,8 @@ private static void fillSpecificVoltageLimits(List specifi Map voltageLevelDefaultLimits, VoltageLevel voltageLevel, Map voltageLevelsIdsRestricted) { - if (voltageLevelDefaultLimits.containsKey(voltageLevel.getId()) || voltageLevelModificationLimits.containsKey(voltageLevel.getId())) { - setLowVoltageLimit(specificVoltageLimits, voltageLevelModificationLimits, voltageLevelDefaultLimits, voltageLevel, voltageLevelsIdsRestricted); - setHighVoltageLimit(specificVoltageLimits, voltageLevelModificationLimits, voltageLevelDefaultLimits, voltageLevel); - } + setLowVoltageLimit(specificVoltageLimits, voltageLevelModificationLimits, voltageLevelDefaultLimits, voltageLevel, voltageLevelsIdsRestricted); + setHighVoltageLimit(specificVoltageLimits, voltageLevelModificationLimits, voltageLevelDefaultLimits, voltageLevel); } private static void setLowVoltageLimit(List specificVoltageLimits, @@ -112,31 +110,28 @@ private static void setLowVoltageLimit(List specificVoltag Map voltageLevelDefaultLimits, VoltageLevel voltageLevel, Map voltageLevelsIdsRestricted) { - final String voltageLevelId = voltageLevel.getId(); - final boolean isLowVoltageLimitModificationSet = voltageLevelModificationLimits.containsKey(voltageLevelId) && voltageLevelModificationLimits.get(voltageLevelId).getLowVoltageLimit() != null; - final double lowVoltageLimit = voltageLevel.getLowVoltageLimit(); + boolean isLowVoltageLimitModificationSet = voltageLevelModificationLimits.containsKey(voltageLevel.getId()) && voltageLevelModificationLimits.get(voltageLevel.getId()).getLowVoltageLimit() != null; + boolean isLowVoltageLimitDefaultSet = voltageLevelDefaultLimits.containsKey(voltageLevel.getId()) && voltageLevelDefaultLimits.get(voltageLevel.getId()).getLowVoltageLimit() != null; double newLowVoltageLimit; - if (!Double.isNaN(lowVoltageLimit) && isLowVoltageLimitModificationSet) { - double lowVoltageLimitModification = voltageLevelModificationLimits.get(voltageLevelId).getLowVoltageLimit(); - if (lowVoltageLimit + lowVoltageLimitModification < 0) { - newLowVoltageLimit = lowVoltageLimit * -1; - voltageLevelsIdsRestricted.put(voltageLevelId, newLowVoltageLimit); + if (!Double.isNaN(voltageLevel.getLowVoltageLimit()) && isLowVoltageLimitModificationSet) { + double lowVoltageLimitModification = voltageLevelModificationLimits.get(voltageLevel.getId()).getLowVoltageLimit(); + if (voltageLevel.getLowVoltageLimit() + lowVoltageLimitModification < 0) { + newLowVoltageLimit = voltageLevel.getLowVoltageLimit() * -1; + voltageLevelsIdsRestricted.put(voltageLevel.getId(), newLowVoltageLimit); } else { newLowVoltageLimit = lowVoltageLimitModification; } - specificVoltageLimits.add(new VoltageLimitOverride(voltageLevelId, VoltageLimitType.LOW_VOLTAGE_LIMIT, true, newLowVoltageLimit)); + specificVoltageLimits.add(new VoltageLimitOverride(voltageLevel.getId(), VoltageLimitType.LOW_VOLTAGE_LIMIT, true, newLowVoltageLimit)); - } else if (Double.isNaN(lowVoltageLimit) - && voltageLevelDefaultLimits.containsKey(voltageLevelId) - && voltageLevelDefaultLimits.get(voltageLevelId).getLowVoltageLimit() != null) { - double voltageLimit = voltageLevelDefaultLimits.get(voltageLevelId).getLowVoltageLimit() + (isLowVoltageLimitModificationSet ? voltageLevelModificationLimits.get(voltageLevelId).getLowVoltageLimit() : 0.); + } else if (Double.isNaN(voltageLevel.getLowVoltageLimit()) && isLowVoltageLimitDefaultSet) { + double voltageLimit = voltageLevelDefaultLimits.get(voltageLevel.getId()).getLowVoltageLimit() + (isLowVoltageLimitModificationSet ? voltageLevelModificationLimits.get(voltageLevel.getId()).getLowVoltageLimit() : 0.); if (voltageLimit < 0) { newLowVoltageLimit = 0.0; - voltageLevelsIdsRestricted.put(voltageLevelId, newLowVoltageLimit); + voltageLevelsIdsRestricted.put(voltageLevel.getId(), newLowVoltageLimit); } else { newLowVoltageLimit = voltageLimit; } - specificVoltageLimits.add(new VoltageLimitOverride(voltageLevelId, VoltageLimitType.LOW_VOLTAGE_LIMIT, false, newLowVoltageLimit)); + specificVoltageLimits.add(new VoltageLimitOverride(voltageLevel.getId(), VoltageLimitType.LOW_VOLTAGE_LIMIT, false, newLowVoltageLimit)); } } @@ -144,25 +139,12 @@ private static void setHighVoltageLimit(List specificVolta Map voltageLevelModificationLimits, Map voltageLevelDefaultLimits, VoltageLevel voltageLevel) { - final String voltageLevelId = voltageLevel.getId(); - final boolean isHighVoltageLimitModificationSet = voltageLevelModificationLimits.containsKey(voltageLevelId) && voltageLevelModificationLimits.get(voltageLevelId).getHighVoltageLimit() != null; - final double highVoltageLimit = voltageLevel.getHighVoltageLimit(); - if (!Double.isNaN(highVoltageLimit) && isHighVoltageLimitModificationSet) { - specificVoltageLimits.add(new VoltageLimitOverride( - voltageLevelId, - VoltageLimitType.HIGH_VOLTAGE_LIMIT, - true, - voltageLevelModificationLimits.get(voltageLevelId).getHighVoltageLimit() - )); - } else if (Double.isNaN(highVoltageLimit) - && voltageLevelDefaultLimits.containsKey(voltageLevelId) - && voltageLevelDefaultLimits.get(voltageLevelId).getHighVoltageLimit() != null) { - specificVoltageLimits.add(new VoltageLimitOverride( - voltageLevelId, - VoltageLimitType.HIGH_VOLTAGE_LIMIT, - false, - voltageLevelDefaultLimits.get(voltageLevelId).getHighVoltageLimit() + (isHighVoltageLimitModificationSet ? voltageLevelModificationLimits.get(voltageLevelId).getHighVoltageLimit() : 0.) - )); + boolean isHighVoltageLimitModificationSet = voltageLevelModificationLimits.containsKey(voltageLevel.getId()) && voltageLevelModificationLimits.get(voltageLevel.getId()).getHighVoltageLimit() != null; + boolean isHighVoltageLimitDefaultSet = voltageLevelDefaultLimits.containsKey(voltageLevel.getId()) && voltageLevelDefaultLimits.get(voltageLevel.getId()).getHighVoltageLimit() != null; + if (!Double.isNaN(voltageLevel.getHighVoltageLimit()) && isHighVoltageLimitModificationSet) { + specificVoltageLimits.add(new VoltageLimitOverride(voltageLevel.getId(), VoltageLimitType.HIGH_VOLTAGE_LIMIT, true, voltageLevelModificationLimits.get(voltageLevel.getId()).getHighVoltageLimit())); + } else if (Double.isNaN(voltageLevel.getHighVoltageLimit()) && isHighVoltageLimitDefaultSet) { + specificVoltageLimits.add(new VoltageLimitOverride(voltageLevel.getId(), VoltageLimitType.HIGH_VOLTAGE_LIMIT, false, voltageLevelDefaultLimits.get(voltageLevel.getId()).getHighVoltageLimit() + (isHighVoltageLimitModificationSet ? voltageLevelModificationLimits.get(voltageLevel.getId()).getHighVoltageLimit() : 0.))); } } @@ -255,14 +237,14 @@ public OpenReacParameters buildOpenReacParameters(VoltageInitRunContext context, private List toEquipmentIdsList(UUID networkUuid, String variantId, List filters) { if (filters == null || filters.isEmpty()) { return List.of(); - } else { - return filterService.exportFilters(filters.stream().map(FilterEquipmentsEmbeddable::getFilterId).toList(), networkUuid, variantId) - .stream() - .map(FilterEquipments::getIdentifiableAttributes) - .flatMap(List::stream) - .map(IdentifiableAttributes::getId) - .distinct() - .toList(); } + List equipments = filterService.exportFilters(filters.stream().map(FilterEquipmentsEmbeddable::getFilterId).toList(), networkUuid, variantId); + Set ids = new HashSet<>(); + equipments.forEach(filterEquipment -> + filterEquipment.getIdentifiableAttributes().forEach(identifiableAttribute -> + ids.add(identifiableAttribute.getId()) + ) + ); + return new ArrayList<>(ids); } } diff --git a/src/test/java/org/gridsuite/voltageinit/server/SupervisionControllerTest.java b/src/test/java/org/gridsuite/voltageinit/server/SupervisionControllerTest.java index f51e389..b5beb59 100644 --- a/src/test/java/org/gridsuite/voltageinit/server/SupervisionControllerTest.java +++ b/src/test/java/org/gridsuite/voltageinit/server/SupervisionControllerTest.java @@ -6,31 +6,35 @@ */ package org.gridsuite.voltageinit.server; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.junit.Assert.assertEquals; + /** * @author Hugo Marcellin */ +@RunWith(SpringRunner.class) @AutoConfigureMockMvc @SpringBootTest -class SupervisionControllerTest { +public class SupervisionControllerTest { @Autowired private MockMvc mockMvc; @Test - void testResultCount() throws Exception { + public void testResultCount() throws Exception { //get the result timeline uuid of the calculation MvcResult mvcResult = mockMvc.perform(get("/v1/supervision/results-count")) .andExpect(status().isOk()) @@ -39,6 +43,7 @@ void testResultCount() throws Exception { String resultCount = mvcResult.getResponse().getContentAsString(); assertEquals("0", resultCount); + } } diff --git a/src/test/java/org/gridsuite/voltageinit/server/VoltageInitControllerTest.java b/src/test/java/org/gridsuite/voltageinit/server/VoltageInitControllerTest.java index d8b906a..638667d 100644 --- a/src/test/java/org/gridsuite/voltageinit/server/VoltageInitControllerTest.java +++ b/src/test/java/org/gridsuite/voltageinit/server/VoltageInitControllerTest.java @@ -27,6 +27,7 @@ import com.powsybl.openreac.parameters.input.OpenReacParameters; import com.powsybl.openreac.parameters.output.OpenReacResult; import com.powsybl.openreac.parameters.output.OpenReacStatus; +import lombok.SneakyThrows; import okhttp3.HttpUrl; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; @@ -44,13 +45,13 @@ import org.gridsuite.voltageinit.server.service.parameters.FilterService; import org.gridsuite.voltageinit.server.util.annotations.PostCompletionAdapter; import org.jgrapht.alg.util.Pair; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; @@ -59,10 +60,9 @@ import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration; import org.springframework.http.MediaType; import org.springframework.messaging.Message; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -76,8 +76,8 @@ import static com.powsybl.network.store.model.NetworkStoreApi.VERSION; import static org.gridsuite.voltageinit.server.service.NotificationService.CANCEL_MESSAGE; import static org.gridsuite.voltageinit.server.service.NotificationService.HEADER_USER_ID; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -88,12 +88,12 @@ /** * @author Etienne Homer */ -@ExtendWith({ MockitoExtension.class }) -@SpringBootTest +@RunWith(SpringRunner.class) @AutoConfigureMockMvc -@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) +@SpringBootTest @ContextHierarchy({@ContextConfiguration(classes = {VoltageInitApplication.class, TestChannelBinderConfiguration.class})}) -class VoltageInitControllerTest { +public class VoltageInitControllerTest { + private static final UUID NETWORK_UUID = UUID.fromString("7928181c-7977-4592-ba19-88027e4254e4"); private static final UUID OTHER_NETWORK_UUID = UUID.fromString("06824085-db85-4883-9458-8c5c9f1585d6"); private static final UUID RESULT_UUID = UUID.fromString("0c8de370-3e6c-4d72-b292-d355a97e0d5d"); @@ -131,17 +131,18 @@ class VoltageInitControllerTest { @MockBean private UuidGeneratorService uuidGeneratorService; - @Autowired - private ObjectMapper mapper; + private final RestTemplateConfig restTemplateConfig = new RestTemplateConfig(); + private final ObjectMapper mapper = restTemplateConfig.objectMapper(); private Network network; - private OpenReacResult openReacResult; - private CompletableFutureTask completableFutureResultsTask; + OpenReacParameters openReacParameters; + OpenReacResult openReacResult; + CompletableFutureTask completableFutureResultsTask; - public MockWebServer server; + private MockWebServer server; - private void buildOpenReacResult() { - OpenReacAmplIOFiles openReacAmplIOFiles = new OpenReacAmplIOFiles(new OpenReacParameters(), network, false); + private OpenReacResult buildOpenReacResult() { + OpenReacAmplIOFiles openReacAmplIOFiles = new OpenReacAmplIOFiles(openReacParameters, network, false); GeneratorModification.Modifs m1 = new GeneratorModification.Modifs(); m1.setTargetV(228.); @@ -164,9 +165,10 @@ private void buildOpenReacResult() { voltageProfile.put("SHUNT_1_busId1", Pair.of(100., 100.)); openReacResult = new OpenReacResult(OpenReacStatus.OK, openReacAmplIOFiles, INDICATORS); + return openReacResult; } - private static VoltageInitParametersEntity buildVoltageInitParametersEntity() { + private VoltageInitParametersEntity buildVoltageInitParametersEntity() { return VoltageInitParametersInfos.builder() .voltageLimitsModification(List.of(VoltageLimitInfos.builder() .priority(0) @@ -201,8 +203,10 @@ private static VoltageInitParametersEntity buildVoltageInitParametersEntity() { .build().toEntity(); } - @BeforeEach + @Before public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + server = new MockWebServer(); server.start(); @@ -237,20 +241,24 @@ public void setUp() throws Exception { given(networkStoreService.getNetwork(OTHER_NETWORK_UUID, PreloadingStrategy.ALL_COLLECTIONS_NEEDED_FOR_BUS_VIEW)).willThrow(new PowsyblException("Not found")); // OpenReac run mocking - buildOpenReacResult(); + openReacParameters = new OpenReacParameters(); + openReacResult = buildOpenReacResult(); + completableFutureResultsTask = CompletableFutureTask.runAsync(() -> openReacResult, ForkJoinPool.commonPool()); // UUID service mocking to always generate the same result UUID given(uuidGeneratorService.generate()).willReturn(RESULT_UUID); final Dispatcher dispatcher = new Dispatcher() { + @SneakyThrows @Override public MockResponse dispatch(RecordedRequest request) { String path = Objects.requireNonNull(request.getPath()); - if (path.matches("/v1/groups/.*") && "DELETE".equals(request.getMethod())) { + + if (path.matches("/v1/groups/.*") && request.getMethod().equals("DELETE")) { return new MockResponse().setResponseCode(200) .addHeader("Content-Type", "application/json; charset=utf-8"); - } else if (path.matches("/v1/groups/modification") && "POST".equals(request.getMethod())) { + } else if (path.matches("/v1/groups/modification") && request.getMethod().equals("POST")) { return new MockResponse().setResponseCode(200).setBody("\"" + MODIFICATIONS_GROUP_UUID + "\"") .addHeader("Content-Type", "application/json; charset=utf-8"); } else if (path.matches("/v1/filters/export\\?networkUuid=" + NETWORK_UUID + "&variantId=" + VARIANT_2_ID + "&ids=.*")) { @@ -276,13 +284,15 @@ public MockResponse dispatch(RecordedRequest request) { } } - @AfterEach - public void tearDown() throws Exception { - server.shutdown(); + @SneakyThrows + @After + public void tearDown() { + mockMvc.perform(delete("/" + VERSION + "/results")) + .andExpect(status().isOk()); } @Test - void runTest() throws Exception { + public void runTest() throws Exception { try (MockedStatic openReacRunnerMockedStatic = Mockito.mockStatic(OpenReacRunner.class)) { openReacRunnerMockedStatic.when(() -> OpenReacRunner.runAsync(eq(network), eq(VARIANT_2_ID), any(OpenReacParameters.class), any(OpenReacConfig.class), any(ComputationManager.class))) .thenReturn(completableFutureResultsTask); @@ -345,7 +355,7 @@ void runTest() throws Exception { } @Test - void runWrongNetworkTest() throws Exception { + public void runWrongNetworkTest() throws Exception { MvcResult result = mockMvc.perform(post( "/" + VERSION + "/networks/{networkUuid}/run-and-save?receiver=me&variantId=" + VARIANT_2_ID, OTHER_NETWORK_UUID) .header(HEADER_USER_ID, "userId")) @@ -366,7 +376,7 @@ void runWrongNetworkTest() throws Exception { } @Test - void runWithReportTest() throws Exception { + public void runWithReportTest() throws Exception { MvcResult result = mockMvc.perform(post( "/" + VERSION + "/networks/{networkUuid}/run-and-save?receiver=me&variantId={variantId}&reportType=VoltageInit&reportUuid=" + REPORT_UUID + "&reporterId=" + UUID.randomUUID(), NETWORK_UUID, VARIANT_2_ID) .header(HEADER_USER_ID, "userId")) @@ -376,7 +386,7 @@ void runWithReportTest() throws Exception { } @Test - void stopTest() throws Exception { + public void stopTest() throws Exception { try (MockedStatic openReacRunnerMockedStatic = Mockito.mockStatic(OpenReacRunner.class)) { openReacRunnerMockedStatic.when(() -> OpenReacRunner.runAsync(eq(network), eq(VARIANT_2_ID), any(OpenReacParameters.class), any(OpenReacConfig.class), any(ComputationManager.class))) .thenReturn(completableFutureResultsTask); @@ -402,8 +412,9 @@ void stopTest() throws Exception { } } + @SneakyThrows @Test - void getStatusTest() throws Exception { + public void getStatusTest() { MvcResult result = mockMvc.perform(get( "/" + VERSION + "/results/{resultUuid}/status", RESULT_UUID)) .andExpect(status().isOk()) @@ -421,8 +432,9 @@ void getStatusTest() throws Exception { assertEquals(VoltageInitStatus.NOT_DONE.name(), result.getResponse().getContentAsString()); } + @SneakyThrows @Test - void postCompletionAdapterTest() { + public void postCompletionAdapterTest() { CompletableFutureTask task = CompletableFutureTask.runAsync(() -> openReacResult, ForkJoinPool.commonPool()); PostCompletionAdapter adapter = new PostCompletionAdapter(); adapter.execute(task); diff --git a/src/test/java/org/gridsuite/voltageinit/server/VoltageInitParametersTest.java b/src/test/java/org/gridsuite/voltageinit/server/VoltageInitParametersTest.java index 72237d9..758479b 100644 --- a/src/test/java/org/gridsuite/voltageinit/server/VoltageInitParametersTest.java +++ b/src/test/java/org/gridsuite/voltageinit/server/VoltageInitParametersTest.java @@ -19,7 +19,7 @@ import com.powsybl.openreac.parameters.input.OpenReacParameters; import com.powsybl.openreac.parameters.input.VoltageLimitOverride; import com.powsybl.openreac.parameters.input.VoltageLimitOverride.VoltageLimitType; -import org.apache.commons.lang3.builder.ToStringBuilder; +import lombok.extern.slf4j.Slf4j; import org.assertj.core.api.Condition; import org.assertj.core.api.ListAssert; import org.gridsuite.voltageinit.server.dto.parameters.FilterEquipments; @@ -60,7 +60,6 @@ import java.util.Objects; import java.util.UUID; import java.util.function.Consumer; -import java.util.stream.Collectors; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; @@ -75,9 +74,10 @@ * @author Ayoub LABIDI */ @SpringBootTest -@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) +@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) @AutoConfigureMockMvc @Transactional +@Slf4j class VoltageInitParametersTest { private static final String URI_PARAMETERS_BASE = "/v1/parameters"; private static final String URI_PARAMETERS_GET_PUT = URI_PARAMETERS_BASE + "/"; @@ -144,73 +144,101 @@ public void setup() { @Test void testCreate() throws Exception { VoltageInitParametersInfos parametersToCreate = buildParameters(); - mockMvc.perform(post(URI_PARAMETERS_BASE).content(mapper.writeValueAsString(parametersToCreate)).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andReturn(); - assertThat(parametersRepository.findAll().get(0).toVoltageInitParametersInfos()) - .as("created parameters") - .recursivelyEquals(parametersToCreate); + String parametersToCreateJson = mapper.writeValueAsString(parametersToCreate); + + mockMvc.perform(post(URI_PARAMETERS_BASE).content(parametersToCreateJson).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andReturn(); + + VoltageInitParametersInfos createdParameters = parametersRepository.findAll().get(0).toVoltageInitParametersInfos(); + + assertThat(createdParameters).recursivelyEquals(parametersToCreate); } @Test void testRead() throws Exception { VoltageInitParametersInfos parametersToRead = buildParameters(); + UUID parametersUuid = saveAndReturnId(parametersToRead); + MvcResult mvcResult = mockMvc.perform(get(URI_PARAMETERS_GET_PUT + parametersUuid)) - .andExpect(status().isOk()).andReturn(); + .andExpect(status().isOk()).andReturn(); String resultAsString = mvcResult.getResponse().getContentAsString(); - assertThat(mapper.readValue(resultAsString, new TypeReference() { })) - .as("received parameters") - .recursivelyEquals(parametersToRead); + VoltageInitParametersInfos receivedParameters = mapper.readValue(resultAsString, new TypeReference<>() { + }); + + assertThat(receivedParameters).recursivelyEquals(parametersToRead); } @Test void testUpdate() throws Exception { - UUID parametersUuid = saveAndReturnId(buildParameters()); - VoltageInitParametersInfos parametersToUpdate = buildParametersUpdate(); - mockMvc.perform(put(URI_PARAMETERS_GET_PUT + parametersUuid).content(mapper.writeValueAsString(parametersToUpdate)).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - assertThat(parametersRepository.findById(parametersUuid).get().toVoltageInitParametersInfos()) - .as("updated parameters") - .recursivelyEquals(parametersToUpdate); + VoltageInitParametersInfos parametersToUpdate = buildParameters(); + + UUID parametersUuid = saveAndReturnId(parametersToUpdate); + + parametersToUpdate = buildParametersUpdate(); + + String parametersToUpdateJson = mapper.writeValueAsString(parametersToUpdate); + + mockMvc.perform(put(URI_PARAMETERS_GET_PUT + parametersUuid).content(parametersToUpdateJson).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + VoltageInitParametersInfos updatedParameters = parametersRepository.findById(parametersUuid).get().toVoltageInitParametersInfos(); + + assertThat(updatedParameters).recursivelyEquals(parametersToUpdate); } @Test void testDelete() throws Exception { - UUID parametersUuid = saveAndReturnId(buildParameters()); + VoltageInitParametersInfos parametersToDelete = buildParameters(); + + UUID parametersUuid = saveAndReturnId(parametersToDelete); + mockMvc.perform(delete(URI_PARAMETERS_GET_PUT + parametersUuid)).andExpect(status().isOk()).andReturn(); assertThat(parametersRepository.count()).as("parameters repository items count").isZero(); } @Test void testGetAll() throws Exception { - saveAndReturnId(buildParameters()); - saveAndReturnId(buildParametersUpdate()); + VoltageInitParametersInfos parameters1 = buildParameters(); + + VoltageInitParametersInfos parameters2 = buildParametersUpdate(); + + saveAndReturnId(parameters1); + + saveAndReturnId(parameters2); + MvcResult mvcResult = mockMvc.perform(get(URI_PARAMETERS_BASE)) - .andExpect(status().isOk()).andReturn(); + .andExpect(status().isOk()).andReturn(); String resultAsString = mvcResult.getResponse().getContentAsString(); - assertThat(mapper.readValue(resultAsString, new TypeReference>() { })) - .as("received parameters") - .hasSize(2); + List receivedParameters = mapper.readValue(resultAsString, new TypeReference<>() { + }); + + assertThat(receivedParameters).hasSize(2); } @Test void testDuplicate() throws Exception { - mockMvc.perform(post(URI_PARAMETERS_BASE).content(mapper.writeValueAsString(buildParameters())).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andReturn(); + VoltageInitParametersInfos parametersToCreate = buildParameters(); + String parametersToCreateJson = mapper.writeValueAsString(parametersToCreate); + mockMvc.perform(post(URI_PARAMETERS_BASE).content(parametersToCreateJson).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andReturn(); VoltageInitParametersInfos createdParameters = parametersRepository.findAll().get(0).toVoltageInitParametersInfos(); - mockMvc.perform(post(URI_PARAMETERS_BASE).param("duplicateFrom", UUID.randomUUID().toString())) - .andExpect(status().isNotFound()); - mockMvc.perform(post(URI_PARAMETERS_BASE).param("duplicateFrom", createdParameters.getUuid().toString())) - .andExpect(status().isOk()); - assertThat(parametersRepository.findAll().get(1).toVoltageInitParametersInfos()) - .as("duplicated parameters") - .recursivelyEquals(createdParameters); + + mockMvc.perform(post(URI_PARAMETERS_BASE) + .param("duplicateFrom", UUID.randomUUID().toString())) + .andExpect(status().isNotFound()); + + mockMvc.perform(post(URI_PARAMETERS_BASE) + .param("duplicateFrom", createdParameters.getUuid().toString())) + .andExpect(status().isOk()); + + VoltageInitParametersInfos duplicatedParameters = parametersRepository.findAll().get(1).toVoltageInitParametersInfos(); + assertThat(duplicatedParameters).recursivelyEquals(createdParameters); } /** Save parameters into the repository and return its UUID. */ private UUID saveAndReturnId(VoltageInitParametersInfos parametersInfos) { - parametersRepository.save(parametersInfos.toEntity()); - return parametersRepository.findAll().get(0).getId(); + return parametersRepository.save(parametersInfos.toEntity()).getId(); } private static VoltageInitParametersInfos buildParameters() { @@ -295,8 +323,7 @@ List dynamicTestsBuildSpecificVoltageLimits() { ); final VoltageInitRunContext context = new VoltageInitRunContext(NETWORK_UUID, VARIANT_ID_1, null, REPORT_UUID, null, "", "", voltageInitParameters.getId()); final OpenReacParameters openReacParameters = voltageInitParametersService.buildOpenReacParameters(context, network); - /*TODO*/System.out.println(parametersRepository.findAll().stream().map(ToStringBuilder::reflectionToString).collect(Collectors.joining())); - /*TODO*/System.out.println(mapper.writeValueAsString(context.getRootReporter())); + log.debug("openReac build parameters report: {}", mapper.writeValueAsString(context.getRootReporter())); JSONAssert.assertEquals("build parameters logs", TestUtils.resourceToString(reportFilename), mapper.writeValueAsString(context.getRootReporter()), REPORTER_COMPARATOR); return assertThat(openReacParameters.getSpecificVoltageLimits()).as("SpecificVoltageLimits"); }; diff --git a/src/test/java/org/gridsuite/voltageinit/service/ReportServiceTest.java b/src/test/java/org/gridsuite/voltageinit/service/ReportServiceTest.java index ef17a22..878c082 100644 --- a/src/test/java/org/gridsuite/voltageinit/service/ReportServiceTest.java +++ b/src/test/java/org/gridsuite/voltageinit/service/ReportServiceTest.java @@ -13,13 +13,15 @@ import com.powsybl.commons.reporter.ReporterModel; import org.gridsuite.voltageinit.server.service.ReportService; import org.gridsuite.voltageinit.utils.ContextConfigurationWithTestChannel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.*; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @@ -30,6 +32,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.gridsuite.voltageinit.utils.TestUtils.resourceToString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -37,8 +40,9 @@ * @author Anis TOURI */ @SpringBootTest +@RunWith(SpringRunner.class) @ContextConfigurationWithTestChannel -class ReportServiceTest { +public class ReportServiceTest { private static final UUID REPORT_UUID = UUID.fromString("7928181c-7977-4592-ba19-88027e4254e4"); private static final String BASE_URI = "http://localhost:"; @@ -60,7 +64,7 @@ private void configureWireMockServer(String reportJson) { } - @BeforeEach + @Before public void setUp() throws IOException, URISyntaxException { String reportJson = resourceToString("report.json"); server = new WireMockServer(WireMockConfiguration.wireMockConfig().dynamicPort()); @@ -72,23 +76,23 @@ public void setUp() throws IOException, URISyntaxException { reportService.setReportServiceBaseUri("http://localhost:" + server.port()); } - @AfterEach + @After public void tearDown() { server.stop(); } @Test - void testSendReport() { + public void testSendReport() { Reporter reporter = new ReporterModel("test", "test"); URI expectedUri = UriComponentsBuilder .fromPath(DELIMITER + REPORT_API_VERSION + "/reports/{reportUuid}") .build(REPORT_UUID); reportService.sendReport(REPORT_UUID, reporter); - verify(restTemplate, times(1)).put(BASE_URI + server.port() + expectedUri, reporter); + verify(restTemplate, times(1)).put(eq(BASE_URI + server.port() + expectedUri), eq(reporter)); } @Test - void testDeleteReport() { + public void testDeleteReport() { reportService.deleteReport(REPORT_UUID, "VoltageInit"); URI expectedUri = UriComponentsBuilder .fromPath(DELIMITER + REPORT_API_VERSION + "/reports/{reportUuid}") @@ -97,6 +101,6 @@ void testDeleteReport() { .build(REPORT_UUID); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); - verify(restTemplate, times(1)).exchange(BASE_URI + server.port() + expectedUri, HttpMethod.DELETE, new HttpEntity<>(headers), Void.class); + verify(restTemplate, times(1)).exchange(eq(BASE_URI + server.port() + expectedUri), eq(HttpMethod.DELETE), eq(new HttpEntity<>(headers)), eq(Void.class)); } }