Skip to content

Commit

Permalink
[backend] Add API tests
Browse files Browse the repository at this point in the history
  • Loading branch information
RomuDeuxfois committed Jan 22, 2024
1 parent 9c58ee0 commit 4503394
Show file tree
Hide file tree
Showing 11 changed files with 582 additions and 22 deletions.
6 changes: 6 additions & 0 deletions openex-api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@
<artifactId>opensaml-saml-impl</artifactId>
<version>${opensaml.version}</version>
</dependency>
<!-- TEST -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand All @@ -199,6 +200,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public class EndpointApi {
public Endpoint createEndpoint(@Valid @RequestBody final EndpointInput input) {
Endpoint endpoint = new Endpoint();
endpoint.setUpdateAttributes(input);
endpoint.setOs(Endpoint.OS_TYPE.valueOf(input.getOs()));
return this.endpointService.createEndpoint(endpoint);
}

Expand All @@ -43,6 +44,7 @@ public Endpoint updateEndpoint(
@Valid @RequestBody final EndpointInput input) {
Endpoint endpoint = this.endpointService.endpoint(endpointId);
endpoint.setUpdateAttributes(input);
endpoint.setOs(Endpoint.OS_TYPE.valueOf(input.getOs()));
return this.endpointService.updateEndpoint(endpoint);
}

Expand Down
49 changes: 28 additions & 21 deletions openex-api/src/main/java/io/openex/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import io.openex.database.specification.GroupSpecification;
import io.openex.rest.user.form.user.CreateUserInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
Expand All @@ -18,6 +19,7 @@
import org.springframework.util.StringUtils;

import jakarta.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
Expand Down Expand Up @@ -70,28 +72,9 @@ public boolean isUserPasswordValid(User user, String password) {
}

public void createUserSession(User user) {
List<SimpleGrantedAuthority> roles = new ArrayList<>();
roles.add(new SimpleGrantedAuthority(ROLE_USER));
if (user.isAdmin()) {
roles.add(new SimpleGrantedAuthority(ROLE_ADMIN));
}
Authentication authentication = buildAuthenticationToken(user);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(new PreAuthenticatedAuthenticationToken(new OpenexPrincipal() {
@Override
public String getId() {
return user.getId();
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}

@Override
public boolean isAdmin() {
return user.isAdmin();
}
}, "", roles));
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
}

Expand Down Expand Up @@ -134,4 +117,28 @@ public User user(@NotBlank final String userId) {
}

// endregion

public static PreAuthenticatedAuthenticationToken buildAuthenticationToken(@NotNull final User user) {
List<SimpleGrantedAuthority> roles = new ArrayList<>();
roles.add(new SimpleGrantedAuthority(ROLE_USER));
if (user.isAdmin()) {
roles.add(new SimpleGrantedAuthority(ROLE_ADMIN));
}
return new PreAuthenticatedAuthenticationToken(new OpenexPrincipal() {
@Override
public String getId() {
return user.getId();
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}

@Override
public boolean isAdmin() {
return user.isAdmin();
}
}, "", roles);
}
}
160 changes: 160 additions & 0 deletions openex-api/src/test/java/io/openex/rest/AssetGroupApiTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package io.openex.rest;

import com.fasterxml.jackson.core.type.TypeReference;
import io.openex.database.model.AssetGroup;
import io.openex.database.repository.AssetGroupRepository;
import io.openex.database.repository.EndpointRepository;
import io.openex.rest.asset_group.form.AssetGroupInput;
import io.openex.rest.utils.WithMockObserverUser;
import io.openex.rest.utils.WithMockPlannerUser;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
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.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;

import java.util.List;

import static io.openex.rest.asset_group.AssetGroupApi.ASSET_GROUP_URI;
import static io.openex.rest.utils.JsonUtils.asJsonString;
import static io.openex.rest.utils.JsonUtils.asStringJson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
@TestMethodOrder(OrderAnnotation.class)
@TestInstance(PER_CLASS)
public class AssetGroupApiTest {

@Autowired
private MockMvc mvc;

@Autowired
private AssetGroupRepository assetGroupRepository;
@Autowired
private EndpointRepository endpointRepository;

@AfterAll
public void teardown() {
this.assetGroupRepository.deleteAll();
this.endpointRepository.deleteAll();
}

@DisplayName("Create asset group succeed")
@Test
@Order(1)
@WithMockUser(roles = {"ADMIN"})
void createAssetGroupTest() throws Exception {
// -- PREPARE --
AssetGroupInput assetGroupInput = new AssetGroupInput();
String name = "Zone";
assetGroupInput.setName(name);

// -- EXECUTE --
String response = this.mvc
.perform(post(ASSET_GROUP_URI)
.content(asJsonString(assetGroupInput))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is2xxSuccessful())
.andReturn()
.getResponse()
.getContentAsString();
AssetGroup assetGroupResponse = asStringJson(response, AssetGroup.class);

// -- ASSERT --
assertEquals(name, assetGroupResponse.getName());
}

@DisplayName("Retrieve asset group succeed")
@Test
@Order(2)
@WithMockObserverUser
void retrieveAssetGroupTest() throws Exception {
// -- EXECUTE --
String response = this.mvc
.perform(get(ASSET_GROUP_URI).accept(MediaType.APPLICATION_JSON))
.andExpect(status().is2xxSuccessful())
.andReturn()
.getResponse()
.getContentAsString();
List<AssetGroup> assetGroupsResponse = asStringJson(response, new TypeReference<>() {
});

// -- ASSERT --
assertEquals(1, assetGroupsResponse.size());
}

@DisplayName("Update asset group succeed")
@Test
@Order(3)
@WithMockUser(roles = {"ADMIN"})
void updateGroupAssetTest() throws Exception {
// -- PREPARE --
AssetGroup assetGroupReponse = getFirstAssetGroup();
AssetGroupInput assetGroupInput = new AssetGroupInput();
String name = "Change zone name";
assetGroupInput.setName(name);

// -- EXECUTE --
String response = this.mvc
.perform(put(ASSET_GROUP_URI + "/" + assetGroupReponse.getId())
.content(asJsonString(assetGroupInput))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is2xxSuccessful())
.andReturn()
.getResponse()
.getContentAsString();
assetGroupReponse = asStringJson(response, AssetGroup.class);

// -- ASSERT --
assertEquals(name, assetGroupReponse.getName());
}

@DisplayName("Delete asset group failed")
@Test
@Order(4)
@WithMockPlannerUser
void deleteAssetGroupFailedTest() throws Exception {
// -- PREPARE --
AssetGroup assetGroupReponse = getFirstAssetGroup();

// -- EXECUTE & ASSERT --
this.mvc.perform(delete(ASSET_GROUP_URI + "/" + assetGroupReponse.getId())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is4xxClientError());
}

@DisplayName("Delete asset group succeed")
@Test
@Order(5)
@WithMockUser(roles = {"ADMIN"})
void deleteAssetGroupSucceedTest() throws Exception {
// -- PREPARE --
AssetGroup assetGroupReponse = getFirstAssetGroup();

// -- EXECUTE --
this.mvc.perform(delete(ASSET_GROUP_URI + "/" + assetGroupReponse.getId())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is2xxSuccessful());

// -- ASSERT --
assertEquals(0, this.assetGroupRepository.count());
}

// -- PRIVATE --

private AssetGroup getFirstAssetGroup() {
return this.assetGroupRepository.findAll().iterator().next();
}

}
Loading

0 comments on commit 4503394

Please sign in to comment.