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

Use single server mock lib #47

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
20 changes: 0 additions & 20 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -189,31 +189,11 @@
<artifactId>powsybl-iidm-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-guava</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,31 @@
*/
package org.gridsuite.voltageinit.server;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
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.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
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.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import static org.junit.Assert.assertEquals;

/**
* @author Hugo Marcellin <hugo.marcelin at rte-france.com>
*/
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest
public class SupervisionControllerTest {
class SupervisionControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
public void testResultCount() throws Exception {
void testResultCount() throws Exception {
//get the result timeline uuid of the calculation
MvcResult mvcResult = mockMvc.perform(get("/v1/supervision/results-count"))
.andExpect(status().isOk())
Expand All @@ -43,7 +39,6 @@ public void testResultCount() throws Exception {

String resultCount = mvcResult.getResponse().getContentAsString();
assertEquals("0", resultCount);

}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
package org.gridsuite.voltageinit.server;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import com.powsybl.commons.PowsyblException;
import com.powsybl.computation.CompletableFutureTask;
import com.powsybl.computation.ComputationManager;
Expand All @@ -27,12 +30,6 @@
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;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.gridsuite.voltageinit.server.dto.VoltageInitResult;
import org.gridsuite.voltageinit.server.dto.VoltageInitStatus;
import org.gridsuite.voltageinit.server.dto.parameters.FilterEquipments;
Expand All @@ -44,55 +41,55 @@
import org.gridsuite.voltageinit.server.service.UuidGeneratorService;
import org.gridsuite.voltageinit.server.service.parameters.FilterService;
import org.gridsuite.voltageinit.server.util.annotations.PostCompletionAdapter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
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.boot.test.mock.mockito.MockBean;
import org.springframework.cloud.stream.binder.test.OutputDestination;
import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration;
import org.springframework.http.MediaType;
import org.springframework.messaging.Message;
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;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ForkJoinPool;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
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.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* @author Etienne Homer <etienne.homer at rte-france.com>
*/
@RunWith(SpringRunner.class)
@ExtendWith({ MockitoExtension.class })
@WireMockTest
@AutoConfigureMockMvc
@ContextConfigurationWithTestChannel
@SpringBootTest
@ContextHierarchy({@ContextConfiguration(classes = {VoltageInitApplication.class, TestChannelBinderConfiguration.class})})
public class VoltageInitControllerTest {

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");
Expand Down Expand Up @@ -130,21 +127,15 @@ public class VoltageInitControllerTest {
@MockBean
private UuidGeneratorService uuidGeneratorService;

private final RestTemplateConfig restTemplateConfig = new RestTemplateConfig();
private final ObjectMapper mapper = restTemplateConfig.objectMapper();
@Autowired
private ObjectMapper mapper;

private Network network;
private Network network1;
private Network networkForMergingView;
private Network otherNetworkForMergingView;
OpenReacParameters openReacParameters;
OpenReacResult openReacResult;
CompletableFutureTask<OpenReacResult> completableFutureResultsTask;
private OpenReacResult openReacResult;
private CompletableFutureTask<OpenReacResult> completableFutureResultsTask;

private MockWebServer server;

private OpenReacResult buildOpenReacResult() {
OpenReacAmplIOFiles openReacAmplIOFiles = new OpenReacAmplIOFiles(openReacParameters, network, false);
private void buildOpenReacResult() {
OpenReacAmplIOFiles openReacAmplIOFiles = new OpenReacAmplIOFiles(new OpenReacParameters(), network, false);

GeneratorModification.Modifs m1 = new GeneratorModification.Modifs();
m1.setTargetV(228.);
Expand All @@ -161,10 +152,9 @@ private OpenReacResult buildOpenReacResult() {
openReacAmplIOFiles.getNetworkModifications().getShuntModifications().add(new ShuntCompensatorModification("SHUNT_1", true, 1));

openReacResult = new OpenReacResult(OpenReacStatus.OK, openReacAmplIOFiles, INDICATORS);
return openReacResult;
}

private VoltageInitParametersEntity buildVoltageInitParametersEntity() {
private static VoltageInitParametersEntity buildVoltageInitParametersEntity() {
return VoltageInitParametersInfos.builder()
.voltageLimitsModification(List.of(VoltageLimitInfos.builder()
.priority(0)
Expand Down Expand Up @@ -199,17 +189,10 @@ private VoltageInitParametersEntity buildVoltageInitParametersEntity() {
.build().toEntity();
}

@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);

server = new MockWebServer();
server.start();

HttpUrl baseHttpUrl = server.url("");
String baseUrl = baseHttpUrl.toString().substring(0, baseHttpUrl.toString().length() - 1);
networkModificationService.setNetworkModificationServerBaseUri(baseUrl);
filterService.setFilterServerBaseUri(baseUrl);
@BeforeEach
public void setUp(final WireMockRuntimeInfo wmRuntimeInfo) {
networkModificationService.setNetworkModificationServerBaseUri(wmRuntimeInfo.getHttpBaseUrl());
filterService.setFilterServerBaseUri(wmRuntimeInfo.getHttpBaseUrl());

// network store service mocking
network = EurostagTutorialExample1Factory.createWithMoreGenerators(new NetworkFactoryImpl());
Expand All @@ -221,38 +204,18 @@ public void setUp() throws Exception {
given(networkStoreService.getNetwork(NETWORK_UUID, PreloadingStrategy.COLLECTION)).willReturn(network);
given(networkStoreService.getNetwork(OTHER_NETWORK_UUID, PreloadingStrategy.ALL_COLLECTIONS_NEEDED_FOR_BUS_VIEW)).willThrow(new PowsyblException("Not found"));

network1 = EurostagTutorialExample1Factory.createWithMoreGenerators(new NetworkFactoryImpl());
network1.getVariantManager().cloneVariant(VariantManagerConstants.INITIAL_VARIANT_ID, VARIANT_2_ID);

// OpenReac run mocking
openReacParameters = new OpenReacParameters();
openReacResult = buildOpenReacResult();

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/.*") && request.getMethod().equals("DELETE")) {
return new MockResponse().setResponseCode(200)
.addHeader("Content-Type", "application/json; charset=utf-8");
} 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=.*")) {
return new MockResponse().setResponseCode(200).setBody(FILTER_EQUIPMENT_JSON)
.addHeader("Content-Type", "application/json; charset=utf-8");
}
return new MockResponse().setResponseCode(418);
}
};
server.setDispatcher(dispatcher);
final WireMock server = wmRuntimeInfo.getWireMock();
server.register(WireMock.delete(urlPathMatching("/v1/groups/.+")).willReturn(okJson("")));
server.register(WireMock.post(urlPathEqualTo("/v1/groups/modification")).willReturn(okJson("\"" + MODIFICATIONS_GROUP_UUID + "\"")));
server.register(WireMock.any(urlMatching("/v1/filters/export\\?networkUuid=" + NETWORK_UUID + "&variantId=" + VARIANT_2_ID + "&ids=.+")).willReturn(okJson(FILTER_EQUIPMENT_JSON)));
server.register(WireMock.any(WireMock.anyUrl()).atPriority(Integer.MAX_VALUE).willReturn(WireMock.serviceUnavailable()));

// purge messages
while (output.receive(1000, "voltageinit.result") != null) {
Expand All @@ -268,15 +231,14 @@ public MockResponse dispatch(RecordedRequest request) {
}
}

@SneakyThrows
@After
public void tearDown() {
@AfterEach
public void tearDown() throws Exception {
mockMvc.perform(delete("/" + VERSION + "/results"))
.andExpect(status().isOk());
}

@Test
public void runTest() throws Exception {
void runTest() throws Exception {
try (MockedStatic<OpenReacRunner> 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);
Expand Down Expand Up @@ -339,7 +301,7 @@ public void runTest() throws Exception {
}

@Test
public void runWrongNetworkTest() throws Exception {
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"))
Expand All @@ -360,7 +322,7 @@ public void runWrongNetworkTest() throws Exception {
}

@Test
public void runWithReportTest() throws Exception {
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"))
Expand All @@ -370,7 +332,7 @@ public void runWithReportTest() throws Exception {
}

@Test
public void stopTest() throws Exception {
void stopTest() throws Exception {
try (MockedStatic<OpenReacRunner> 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);
Expand All @@ -396,9 +358,8 @@ public void stopTest() throws Exception {
}
}

@SneakyThrows
@Test
public void getStatusTest() {
void getStatusTest() throws Exception {
MvcResult result = mockMvc.perform(get(
"/" + VERSION + "/results/{resultUuid}/status", RESULT_UUID))
.andExpect(status().isOk())
Expand All @@ -416,9 +377,8 @@ public void getStatusTest() {
assertEquals(VoltageInitStatus.NOT_DONE.name(), result.getResponse().getContentAsString());
}

@SneakyThrows
@Test
public void postCompletionAdapterTest() {
void postCompletionAdapterTest() {
CompletableFutureTask<OpenReacResult> task = CompletableFutureTask.runAsync(() -> openReacResult, ForkJoinPool.commonPool());
PostCompletionAdapter adapter = new PostCompletionAdapter();
adapter.execute(task);
Expand Down
Loading