Skip to content

Commit

Permalink
test: fix test with auth
Browse files Browse the repository at this point in the history
  • Loading branch information
laurentC35 committed Jan 25, 2024
1 parent 06a533f commit c15a73b
Show file tree
Hide file tree
Showing 7 changed files with 128 additions and 20 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package fr.insee.publicenemy.api.utils;

import fr.insee.publicenemy.api.configuration.auth.AuthConstants;
import fr.insee.publicenemy.api.configuration.auth.AuthorityRoleEnum;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AuthenticatedUserTestHelper {

public JwtAuthenticationToken getUser() {
return getAuthenticatedUser(
AuthorityRoleEnum.ADMIN, AuthorityRoleEnum.DESIGNER);
}
public JwtAuthenticationToken getAuthenticatedUser(AuthorityRoleEnum... roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (AuthorityRoleEnum role : roles) {
authorities.add(new SimpleGrantedAuthority(AuthConstants.ROLE_PREFIX + role.name()));
}

Map<String, Object> headers = Map.of("typ", "JWT");
Map<String, Object> claims = Map.of("preferred_username", "dupont-identifier", "name", "Jean Dupont");

Jwt jwt = new Jwt("token-value", Instant.MIN, Instant.MAX, headers, claims);
return new JwtAuthenticationToken(jwt, authorities, "dupont-identifier");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,40 @@

import fr.insee.publicenemy.api.application.domain.model.Context;
import fr.insee.publicenemy.api.application.ports.I18nMessagePort;
import fr.insee.publicenemy.api.utils.AuthenticatedUserTestHelper;
import org.junit.jupiter.api.BeforeEach;
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.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;

import java.util.Arrays;
import java.util.List;

import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(ContextController.class)
@ContextConfiguration(classes = ContextController.class)
@SpringBootTest
@ActiveProfiles("test")
@ContextConfiguration
@AutoConfigureMockMvc
class ContextControllerTest {
@MockBean
private I18nMessagePort i18nService;

private final AuthenticatedUserTestHelper authenticatedUserTestHelper = new AuthenticatedUserTestHelper();

@Autowired
private MockMvc mockMvc;

Expand All @@ -37,7 +47,8 @@ public void init() {
@Test
void onGetContextsReturnsAllContexts() throws Exception {
List<String> contextNames = Arrays.stream(Context.values()).map(Enum::name).toList();
mockMvc.perform(get("/api/contexts"))
mockMvc.perform(get("/api/contexts")
.with(authentication(authenticatedUserTestHelper.getUser())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.size()", is(2)))
.andExpect(jsonPath("$[0].name", is(contextNames.get(0))))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,40 @@
package fr.insee.publicenemy.api.controllers;

import fr.insee.publicenemy.api.application.domain.model.Mode;
import fr.insee.publicenemy.api.utils.AuthenticatedUserTestHelper;
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.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.is;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(ModeController.class)
@ContextConfiguration(classes = ModeController.class)
@SpringBootTest
@ActiveProfiles("test")
@ContextConfiguration
@AutoConfigureMockMvc
class ModeControllerTest {

@Autowired
private MockMvc mockMvc;

private final AuthenticatedUserTestHelper authenticatedUserTestHelper = new AuthenticatedUserTestHelper();

@Test
void onGetModesReturnsAllModes() throws Exception {
Mode[] modes = Mode.values();
mockMvc.perform(get("/api/modes"))
mockMvc.perform(get("/api/modes")
.with(authentication(authenticatedUserTestHelper.getUser())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.size()", is(modes.length)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
import fr.insee.publicenemy.api.application.usecase.DDIUseCase;
import fr.insee.publicenemy.api.application.usecase.QuestionnaireUseCase;
import fr.insee.publicenemy.api.application.usecase.SurveyUnitCsvUseCase;
import fr.insee.publicenemy.api.configuration.auth.AuthorityRoleEnum;
import fr.insee.publicenemy.api.controllers.dto.ContextRest;
import fr.insee.publicenemy.api.controllers.dto.ModeRest;
import fr.insee.publicenemy.api.controllers.dto.QuestionnaireAddRest;
import fr.insee.publicenemy.api.controllers.dto.QuestionnaireRest;
import fr.insee.publicenemy.api.controllers.exceptions.ApiExceptionComponent;
import fr.insee.publicenemy.api.utils.AuthenticatedUserTestHelper;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand All @@ -24,12 +26,15 @@
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockPart;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
Expand All @@ -43,12 +48,14 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(QuestionnaireController.class)
@ContextConfiguration(classes = QuestionnaireController.class)
@Slf4j
@SpringBootTest
@ActiveProfiles("test")
@ContextConfiguration
@AutoConfigureMockMvc
class QuestionnaireControllerTest {
@MockBean
private QuestionnaireUseCase questionnaireUseCase;
Expand All @@ -70,6 +77,8 @@ class QuestionnaireControllerTest {

@Autowired
private MockMvc mockMvc;

private final AuthenticatedUserTestHelper authenticatedUserTestHelper = new AuthenticatedUserTestHelper();
private List<Questionnaire> questionnaires;

private Questionnaire questionnaire;
Expand Down Expand Up @@ -105,7 +114,8 @@ void onGetQuestionnairesShouldFetchAllQuestionnaires() throws Exception {

when(questionnaireUseCase.getQuestionnaires()).thenReturn(questionnaires);

mockMvc.perform(get("/api/questionnaires"))
mockMvc.perform(get("/api/questionnaires")
.with(authentication(authenticatedUserTestHelper.getUser())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.size()", is(questionnaires.size())));
}
Expand All @@ -115,7 +125,8 @@ void onGetQuestionnaireShouldFetchQuestionnaireAttributes() throws Exception {
Long id = questionnaire.getId();
when(questionnaireUseCase.getQuestionnaire(id)).thenReturn(questionnaire);

mockMvc.perform(get("/api/questionnaires/{id}", id))
mockMvc.perform(get("/api/questionnaires/{id}", id)
.with(authentication(authenticatedUserTestHelper.getUser())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(questionnaireRest.id().intValue())))
.andExpect(jsonPath("$.poguesId", is(questionnaireRest.poguesId())))
Expand All @@ -132,7 +143,8 @@ void onGetSurveyUnitsDataReturnCSV() throws Exception {
byte[] data = "\"att1\",\"att2\"".getBytes();
when(questionnaireUseCase.getSurveyUnitData(id)).thenReturn(data);

MvcResult result = mockMvc.perform(get("/api/questionnaires/{id}/data", id))
MvcResult result = mockMvc.perform(get("/api/questionnaires/{id}/data", id)
.with(authentication(authenticatedUserTestHelper.getUser())))
.andExpect(status().isOk())
.andReturn();

Expand All @@ -152,6 +164,7 @@ void onAddQuestionnaireShouldFetchQuestionnaireAttributes() throws Exception {

questionnaireMockPart.getHeaders().setContentType(MediaType.APPLICATION_JSON);
mockMvc.perform(multipart("/api/questionnaires/add").file(surveyUnitMockPart).part(questionnaireMockPart)
.with(authentication(authenticatedUserTestHelper.getUser()))
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(questionnaireRest.id().intValue())))
Expand All @@ -168,7 +181,8 @@ void onGetQuestionnaireFromPoguesShouldFetchQuestionnaireAttributes() throws Exc
String poguesId = questionnaire.getPoguesId();
when(ddiUseCase.getQuestionnaire(poguesId)).thenReturn(questionnaire);

mockMvc.perform(get("/api/questionnaires/pogues/{poguesId}", poguesId))
mockMvc.perform(get("/api/questionnaires/pogues/{poguesId}", poguesId)
.with(authentication(authenticatedUserTestHelper.getUser())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.poguesId", is(questionnaireRest.poguesId())))
.andExpect(jsonPath("$.label", is(questionnaireRest.label())))
Expand All @@ -192,6 +206,7 @@ void onSaveQuestionnaireShouldFetchQuestionnaireAttributes(String surveyUnitData
questionnaire.getContext(), questionnaire.getSurveyUnitData())).thenReturn(questionnaire);

mockMvc.perform(multipart("/api/questionnaires/{id}", id).part(contextMockPart).file(surveyUnitMockPart)
.with(authentication(authenticatedUserTestHelper.getUser()))
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(questionnaireRest.id().intValue())))
Expand All @@ -214,6 +229,7 @@ void onSaveQuestionnaireWhenEmptyDataShouldFetchDataFromQuestionnaire() throws E
Long id = questionnaire.getId();

mockMvc.perform(multipart("/api/questionnaires/{id}", id).part(contextMockPart)
.with(authentication(authenticatedUserTestHelper.getUser()))
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk());
verify(questionnaireUseCase, times(1)).getSurveyUnitData(id);
Expand All @@ -223,7 +239,8 @@ void onSaveQuestionnaireWhenEmptyDataShouldFetchDataFromQuestionnaire() throws E
void onDeleteQuestionnaireShouldReturnEmptyJsonObject() throws Exception {
Long id = questionnaire.getId();

mockMvc.perform(delete("/api/questionnaires/{id}/delete", id))
mockMvc.perform(delete("/api/questionnaires/{id}/delete", id)
.with(authentication(authenticatedUserTestHelper.getUser())))
.andExpect(status().isOk())
.andExpect(content().json("{}"));
}
Expand All @@ -243,6 +260,7 @@ void onAddQuestionnaireWhenGlobalErrorsOnCsvSchemaReturnGenericErrorMessages() t
SurveyUnitsGlobalValidationException surveyUnitsValidationException = new SurveyUnitsGlobalValidationException("main error message", new ArrayList<>());
when(surveyUnitCsvUseCase.validateSurveyUnits(surveyUnitData, "l8wwljbo")).thenThrow(surveyUnitsValidationException);
mockMvc.perform(multipart("/api/questionnaires/add").file(surveyUnitMockPart).part(questionnaireMockPart)
.with(authentication(authenticatedUserTestHelper.getUser()))
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isBadRequest());

Expand All @@ -266,7 +284,10 @@ void onAddQuestionnaireWhenSpecificErrorsOnCsvSchemaReturnGenericErrorMessages()
SurveyUnitsSpecificValidationException surveyUnitsSpecificValidationException = new SurveyUnitsSpecificValidationException("main error message", new ArrayList<>());
when(surveyUnitCsvUseCase.validateSurveyUnits(surveyUnitData, "l8wwljbo")).thenThrow(surveyUnitsSpecificValidationException);

mockMvc.perform(multipart("/api/questionnaires/add").file(surveyUnitMockPart).part(questionnaireMockPart)
mockMvc.perform(multipart("/api/questionnaires/add")
.file(surveyUnitMockPart)
.part(questionnaireMockPart)
.with(authentication(authenticatedUserTestHelper.getUser()))
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isBadRequest());

Expand Down
Loading

0 comments on commit c15a73b

Please sign in to comment.