Skip to content

Commit

Permalink
add UserProfile test class
Browse files Browse the repository at this point in the history
Signed-off-by: David BRAQUART <[email protected]>
  • Loading branch information
dbraquart committed Mar 28, 2024
1 parent 87fbf39 commit 62e2037
Show file tree
Hide file tree
Showing 4 changed files with 244 additions and 8 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -171,5 +171,10 @@
<artifactId>spring-cloud-stream-test-binder</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
package org.gridsuite.useradmin.server.service;

import jakarta.validation.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
Expand Down Expand Up @@ -35,15 +34,16 @@ public class DirectoryService {
private static final String ELEMENTS_SERVER_ROOT_PATH = DELIMITER + DIRECTORY_SERVER_API_VERSION + DELIMITER
+ "elements";

private final RestTemplate restTemplate;
private final RestTemplate restTemplate = new RestTemplate();

private final String directoryServerBaseUri;
private static String directoryServerBaseUri;

@Autowired
public DirectoryService(@Value("${gridsuite.services.directory-server.base-uri:http://directory-server/}") String directoryServerBaseUri,
RestTemplate restTemplate) {
this.directoryServerBaseUri = directoryServerBaseUri;
this.restTemplate = restTemplate;
public DirectoryService(@Value("${gridsuite.services.directory-server.base-uri:http://directory-server/}") String directoryServerBaseUri) {
setDirectoryServerBaseUri(directoryServerBaseUri);
}

public static void setDirectoryServerBaseUri(String serverBaseUri) {
DirectoryService.directoryServerBaseUri = serverBaseUri;
}

public Set<UUID> findUnexistingElements(@NotEmpty Set<UUID> elementsUuids) {
Expand Down
187 changes: 187 additions & 0 deletions src/test/java/org/gridsuite/useradmin/server/UserProfileTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/**
* Copyright (c) 2024, RTE (http://www.rte-france.com)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.gridsuite.useradmin.server;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.matching.StringValuePattern;
import org.gridsuite.useradmin.server.dto.UserProfile;
import org.gridsuite.useradmin.server.repository.UserAdminRepository;
import org.gridsuite.useradmin.server.service.DirectoryService;
import org.gridsuite.useradmin.server.utils.WireMockUtils;
import org.junit.Assert;
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.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.stream.binder.test.OutputDestination;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.github.tomakehurst.wiremock.WireMockServer;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.springframework.http.MediaType.APPLICATION_JSON;
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.result.MockMvcResultMatchers.status;

/**
* @author David Braquart <david.braquart at rte-france.com>
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserProfileTest {
@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper = new ObjectMapper();

@Autowired
private UserAdminRepository userAdminRepository;

@Autowired
private UserAdminRepository userProfileRepository;

@Autowired
private OutputDestination output;

private static final long TIMEOUT = 1000;

protected static WireMockServer wireMockServer;

protected WireMockUtils wireMockUtils;

@Before
public void setUp() {
wireMockServer = new WireMockServer(wireMockConfig().dynamicPort());
wireMockServer.start();
DirectoryService.setDirectoryServerBaseUri(wireMockServer.baseUrl());
wireMockUtils = new WireMockUtils(wireMockServer);
}

@After
public void tearOff() {
userAdminRepository.deleteAll();
userProfileRepository.deleteAll();

try {
wireMockServer.checkForUnmatchedRequests();
Assert.assertEquals(0, wireMockServer.findAll(WireMock.anyRequestedFor(WireMock.anyUrl())).size());
} finally {
wireMockServer.shutdown();
}
}

private static final String USER_UNKNOWN = "UNKNOWN";
private static final String ADMIN_USER = "admin1";
private static final String NOT_ADMIN = "notAdmin";
private static final String PROFILE_1 = "profile_1";

@Test
public void testUserProfile() throws Exception {
ObjectWriter objectWriter = objectMapper.writer().withDefaultPrettyPrinter();

// stub for parameters elements existence check
final String urlPath = "/v1/elements";
UUID stubId = wireMockServer.stubFor(WireMock.get(WireMock.urlMatching(urlPath + "\\?strictMode=false&ids="))
.willReturn(WireMock.ok()
.withBody(objectMapper.writeValueAsString(Set.of()))
.withHeader("Content-Type", "application/json"))).getId();

// no existing profile
List<UserProfile> userProfiles = objectMapper.readValue(
mockMvc.perform(get("/" + UserAdminApi.API_VERSION + "/profiles")
.header("userId", ADMIN_USER)
.contentType(APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString(),
new TypeReference<>() {
});
assertEquals(0, userProfiles.size());
wireMockUtils.verifyGetRequest(stubId, urlPath, handleQueryParams(List.of()), false);

// Create a profile
mockMvc.perform(post("/" + UserAdminApi.API_VERSION + "/profiles/{profileName}", PROFILE_1)
.header("userId", ADMIN_USER)
)
.andExpect(status().isCreated())
.andReturn();

userProfiles = objectMapper.readValue(
mockMvc.perform(get("/" + UserAdminApi.API_VERSION + "/profiles")
.header("userId", ADMIN_USER)
.contentType(APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString(),
new TypeReference<>() {
});
assertEquals(1, userProfiles.size());
assertEquals(PROFILE_1, userProfiles.get(0).name());
assertNull(userProfiles.get(0).loadFlowParameterId());
assertNull(userProfiles.get(0).validity());
wireMockUtils.verifyGetRequest(stubId, urlPath, handleQueryParams(List.of()), false);

// Remove the profile
mockMvc.perform(delete("/" + UserAdminApi.API_VERSION + "/profiles")
.content(objectWriter.writeValueAsString(List.of(PROFILE_1)))
.contentType(MediaType.APPLICATION_JSON)
.header("userId", ADMIN_USER)
)
.andExpect(status().isNoContent())
.andReturn();

userProfiles = objectMapper.readValue(
mockMvc.perform(get("/" + UserAdminApi.API_VERSION + "/profiles")
.header("userId", ADMIN_USER)
.contentType(APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString(),
new TypeReference<>() {
});
assertEquals(0, userProfiles.size());
wireMockUtils.verifyGetRequest(stubId, urlPath, handleQueryParams(List.of()), false);

// not allowed
mockMvc.perform(delete("/" + UserAdminApi.API_VERSION + "/profiles")
.content(objectWriter.writeValueAsString(List.of(PROFILE_1)))
.contentType(MediaType.APPLICATION_JSON)
.header("userId", NOT_ADMIN)
)
.andExpect(status().isForbidden())
.andReturn();

// profile already deleted / not found
mockMvc.perform(delete("/" + UserAdminApi.API_VERSION + "/profiles")
.content(objectWriter.writeValueAsString(List.of(PROFILE_1)))
.contentType(MediaType.APPLICATION_JSON)
.header("userId", ADMIN_USER)
)
.andExpect(status().isNotFound())
.andReturn();
}

private Map<String, StringValuePattern> handleQueryParams(List<UUID> paramIds) {
return Map.of("ids", WireMock.matching(paramIds.stream().map(uuid -> ".+").collect(Collectors.joining(","))));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Copyright (c) 2024, RTE (http://www.rte-france.com)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.gridsuite.useradmin.server.utils;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.admin.model.ServeEventQuery;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;
import com.github.tomakehurst.wiremock.matching.StringValuePattern;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.junit.Assert.assertEquals;

public class WireMockUtils {

private final WireMockServer wireMockServer;

public WireMockUtils(WireMockServer wireMockServer) {
this.wireMockServer = wireMockServer;
}

public void verifyGetRequest(UUID stubId, String urlPath, Map<String, StringValuePattern> queryParams, boolean regexMatching) {
RequestPatternBuilder requestBuilder = regexMatching ? WireMock.getRequestedFor(WireMock.urlPathMatching(urlPath)) : WireMock.getRequestedFor(WireMock.urlPathEqualTo(urlPath));
queryParams.forEach(requestBuilder::withQueryParam);
wireMockServer.verify(1, requestBuilder);
removeRequestForStub(stubId, 1);
}

private void removeRequestForStub(UUID stubId, int nbRequests) {
List<ServeEvent> serveEvents = wireMockServer.getServeEvents(ServeEventQuery.forStubMapping(stubId)).getServeEvents();
assertEquals(nbRequests, serveEvents.size());
for (ServeEvent serveEvent : serveEvents) {
wireMockServer.removeServeEvent(serveEvent.getId());
}
}
}

0 comments on commit 62e2037

Please sign in to comment.