Skip to content

Commit

Permalink
add more int tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mafasva committed Dec 9, 2024
1 parent 4934e28 commit 5c234d0
Show file tree
Hide file tree
Showing 7 changed files with 120 additions and 32 deletions.
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
<mockserver-client.version>5.15.0</mockserver-client.version>
<ossindexAnalyzerEnabled>false</ossindexAnalyzerEnabled>
<spring.cloud-version>2023.0.3</spring.cloud-version>
<jsoup.version>1.18.3</jsoup.version>
</properties>

<repositories>
Expand Down Expand Up @@ -195,6 +196,11 @@
<artifactId>hapi-fhir-jaxrsserver-base</artifactId>
<version>${hapi.version}</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,6 @@ public class Message implements Serializable {

private MessageType type;

private boolean toDelete;
private boolean markAsDeleted;

}
5 changes: 3 additions & 2 deletions src/main/java/org/highmed/numportal/mapper/MessageMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import org.highmed.numportal.domain.dto.MessageDto;
import org.highmed.numportal.domain.model.Message;

import javax.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@AllArgsConstructor
public class MessageMapper {
Expand All @@ -19,7 +20,7 @@ private void initialize() {
modelMapper.getConfiguration().setAmbiguityIgnored(true);
}

public MessageDto convertToDTO(Message message) {
public MessageDto convertToDto(Message message) {
return modelMapper.map(message, MessageDto.class);

}
Expand Down
18 changes: 12 additions & 6 deletions src/main/java/org/highmed/numportal/service/MessageService.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
Expand All @@ -26,24 +28,28 @@
@AllArgsConstructor
public class MessageService {

private static final Safelist safeList = Safelist.simpleText().addTags("br");

private MessageMapper messageMapper;
private UserDetailsService userDetailsService;

private MessageRepository messageRepository;

public MessageDto createUserMessage(MessageDto messageDto, String userId) {
Message message = messageMapper.convertToEntity(messageDto);
userDetailsService.checkIsUserApproved(userId);
Message message = messageMapper.convertToEntity(messageDto);
message.setText(Jsoup.clean(message.getText(), safeList));
validateDates(message.getStartDate(), message.getEndDate(), LocalDateTime.now().minusMinutes(5));

Message savedMessage = messageRepository.save(message);

return messageMapper.convertToDTO(savedMessage);
return messageMapper.convertToDto(savedMessage);
}

public Page<MessageDto> getMessages(String userId, Pageable pageable) {
userDetailsService.checkIsUserApproved(userId);
Page<Message> messagePage = messageRepository.findAll(pageable);
return messagePage.map(message -> messageMapper.convertToDTO(message));
return messagePage.map(message -> messageMapper.convertToDto(message));
}

public MessageDto updateUserMessage(Long id, MessageDto messageDto, String userId) {
Expand All @@ -63,14 +69,14 @@ public MessageDto updateUserMessage(Long id, MessageDto messageDto, String userI
validateDates(messageDto.getStartDate(), messageDto.getEndDate(), now);

messageToUpdate.setTitle(messageDto.getTitle());
messageToUpdate.setText(messageDto.getText());
messageToUpdate.setText(Jsoup.clean(messageDto.getText(), safeList));
messageToUpdate.setStartDate(messageDto.getStartDate());
messageToUpdate.setEndDate(messageDto.getEndDate());
messageToUpdate.setType(messageDto.getType());

}
Message savedMessage = messageRepository.save(messageToUpdate);
return messageMapper.convertToDTO(savedMessage);
return messageMapper.convertToDto(savedMessage);
}

public void deleteActiveUserMessage(Long id, String userId) {
Expand All @@ -81,7 +87,7 @@ public void deleteActiveUserMessage(Long id, String userId) {
String.format(MESSAGE_NOT_FOUND, id)));
// active messages should be marked as deleted
if (messageToDelete.getStartDate().isBefore(now) && messageToDelete.getEndDate().isAfter(now)) {
messageToDelete.setToDelete(true);
messageToDelete.setMarkAsDeleted(true);
messageRepository.save(messageToDelete);
} else {
throw new BadRequestException(MessageService.class, CANNOT_DELETE_MESSAGE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ CREATE TABLE message(
start_date timestamp NOT NULL,
end_date timestamp NOT NULL,
type varchar(125) NOT NULL ,
to_delete boolean
mark_as_deleted boolean
);
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import org.highmed.numportal.domain.repository.MessageRepository;
import org.highmed.numportal.integrationtesting.security.WithMockNumUser;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.SneakyThrows;
Expand All @@ -17,25 +16,32 @@
import org.springframework.cloud.openfeign.support.PageJacksonModule;
import org.springframework.cloud.openfeign.support.SortJacksonModule;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import java.time.LocalDateTime;
import java.util.List;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
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.patch;
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.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class MessageControllerIT extends IntegrationTest{
public class MessageControllerIT extends IntegrationTest {

private static final String MESSAGE_PATH = "/message";

private ObjectMapper mapper = new ObjectMapper()
private final ObjectMapper mapper = new ObjectMapper()
.registerModule(new PageJacksonModule())
.registerModule(new SortJacksonModule())
.registerModule(new JavaTimeModule());
private Long updateMessageId;

@Autowired
public MockMvc mockMvc;
Expand All @@ -44,8 +50,8 @@ public class MessageControllerIT extends IntegrationTest{
private MessageRepository messageRepository;

@Before
public void setUpMessage(){
// messageRepository.deleteAll();
public void setUpMessage() {
messageRepository.deleteAll();
LocalDateTime now = java.time.LocalDateTime.now().minusMinutes(5);
Message inactiveMessage =
Message.builder()
Expand All @@ -57,28 +63,74 @@ public void setUpMessage(){
messageRepository.save(inactiveMessage);
Message activeMessage =
Message.builder()
.title("Active message")
.type(MessageType.INFO)
.startDate(now.minusHours(10))
.endDate(now.plusMinutes(5))
.build();
.title("Active message")
.type(MessageType.INFO)
.startDate(now.minusHours(10))
.endDate(now.plusMinutes(5))
.build();
messageRepository.save(activeMessage);
Message plannedMessage =
Message.builder()
.title("Planned message")
.type(MessageType.INFO)
.startDate(now.plusHours(1))
.endDate(now.plusHours(10))
.build();
messageRepository.save(plannedMessage);
.title("Planned message")
.type(MessageType.INFO)
.startDate(now.plusHours(1))
.endDate(now.plusHours(10))
.build();
Message save = messageRepository.save(plannedMessage);
updateMessageId = save.getId();
}

@SuppressWarnings("rawtypes")
@Test
@SneakyThrows
@WithMockNumUser(roles = {"CONTENT_ADMIN"})
public void getUserMessages (){
public void createUserMessage() {
LocalDateTime start = java.time.LocalDateTime.now().plusMinutes(5);
Message plannedMessage =
Message.builder()
.title("Planned message")
.text("This is a <strong>strong</strong> message, with <script>evil code injection</script>.")
.type(MessageType.INFO)
.startDate(start)
.endDate(start.plusMonths(10))
.build();

mockMvc.perform(post(MESSAGE_PATH).with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(plannedMessage)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value(plannedMessage.getTitle()))
.andExpect(jsonPath("$.text", not(containsString("<script>"))))
.andReturn();
}

@Test
@SneakyThrows
@WithMockNumUser(roles = {"CONTENT_ADMIN"})
public void updateUserMessage() {
LocalDateTime start = java.time.LocalDateTime.now().plusHours(1);
Message updateMessage =
Message.builder()
.title("Update planned message")
.text("This is a <strong>strong</strong> message, with <script>evil code injection</script>.")
.type(MessageType.INFO)
.startDate(start)
.endDate(start.plusMonths(10))
.build();

mockMvc.perform(put(MESSAGE_PATH + "/{id}", updateMessageId).with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(updateMessage)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value(updateMessage.getTitle()))
.andExpect(jsonPath("$.text", not(containsString("<script>"))))
.andReturn();
}

@Test
@SneakyThrows
@WithMockNumUser(roles = {"CONTENT_ADMIN"})
@SuppressWarnings("rawtypes")
public void getUserMessages() {
MvcResult result =
mockMvc.perform(get(MESSAGE_PATH).with(csrf())).andExpect(status().isOk()).andReturn();
String contentAsString = result.getResponse().getContentAsString();
Expand All @@ -91,4 +143,27 @@ public void getUserMessages (){
Assert.assertEquals(MessageType.ERROR, firstMessage.getType());
}

@Test
@SneakyThrows
@WithMockNumUser(roles = {"MANAGER"})
public void noAccessApiWithWrongRole() {
LocalDateTime start = java.time.LocalDateTime.now().plusMinutes(5);
Message someMessage =
Message.builder()
.title("Planned message")
.type(MessageType.INFO)
.startDate(start)
.endDate(start.plusMonths(10))
.build();
mockMvc.perform(post(MESSAGE_PATH).with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(someMessage))).andExpect(status().isForbidden());
mockMvc.perform(get(MESSAGE_PATH).with(csrf())).andExpect(status().isForbidden());
mockMvc.perform(put(MESSAGE_PATH + "/{id}", 3).with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(someMessage))).andExpect(status().isForbidden());
mockMvc.perform(patch(MESSAGE_PATH + "/{id}", 3).with(csrf())).andExpect(status().isForbidden());
mockMvc.perform(delete(MESSAGE_PATH + "/{id}", 3).with(csrf())).andExpect(status().isForbidden());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,13 @@ public void setup() {
public void createUserMessageTest() {
when(messageMapper.convertToEntity(messageDto)).thenReturn(message);
when(messageRepository.save(message)).thenReturn(message);
when(messageMapper.convertToDTO(message)).thenReturn(messageDto);
when(messageMapper.convertToDto(message)).thenReturn(messageDto);
MessageDto returnMessage = messageService.createUserMessage(messageDto, USER_ID);

Assert.assertEquals(messageDto, returnMessage);

Mockito.verify(messageMapper, Mockito.times(1)).convertToEntity(messageDto);
Mockito.verify(messageMapper, Mockito.times(1)).convertToDTO(message);
Mockito.verify(messageMapper, Mockito.times(1)).convertToDto(message);
Mockito.verify(messageRepository, Mockito.times(1)).save(message);
Mockito.verify(userDetailsService, Mockito.times(1)).checkIsUserApproved(USER_ID);
}
Expand Down

0 comments on commit 5c234d0

Please sign in to comment.