From 67507e01782140e6978f62511e264fc03941bc3f Mon Sep 17 00:00:00 2001 From: Nic12345678 <162564162+Nic12345678@users.noreply.github.com> Date: Fri, 12 Apr 2024 17:43:26 +0200 Subject: [PATCH] Testing Broadcast- Controller and Service --- .../MicroServiceApplication.java | 5 - .../oss/wahllokalsystem/domain/Message.java | 6 +- .../domain/MessageRepository.java | 4 + .../service/BroadcastService.java | 18 +- .../UnicodeConfigurationTest.java | 2 +- .../domain/MessageRepositoryTest.java | 36 ++-- .../wahllokalsystem/domain/MessageTest.java | 6 +- .../rest/BroadcastControllerTest.java | 173 ++++++++++++++++++ .../rest/TheEntityRepositoryTest.java | 56 ------ 9 files changed, 218 insertions(+), 88 deletions(-) create mode 100644 wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/rest/BroadcastControllerTest.java delete mode 100644 wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/rest/TheEntityRepositoryTest.java diff --git a/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/MicroServiceApplication.java b/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/MicroServiceApplication.java index 4a74a0233..1e3ac2e27 100644 --- a/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/MicroServiceApplication.java +++ b/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/MicroServiceApplication.java @@ -10,10 +10,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; - /** * Application class for starting the micro-service. */ @@ -36,7 +32,6 @@ } ) @EnableAutoConfiguration -@EnableMethodSecurity(securedEnabled = true) public class MicroServiceApplication { public static void main(String[] args) { diff --git a/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/domain/Message.java b/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/domain/Message.java index 4b153b55f..7408e4ddb 100644 --- a/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/domain/Message.java +++ b/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/domain/Message.java @@ -8,14 +8,12 @@ import java.time.LocalDateTime; import java.util.UUID; import lombok.AllArgsConstructor; +import lombok.Data; import lombok.NoArgsConstructor; -import lombok.Getter; -import lombok.Setter; import org.hibernate.annotations.GenericGenerator; @Entity -@Getter -@Setter +@Data @NoArgsConstructor @AllArgsConstructor public class Message { diff --git a/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/domain/MessageRepository.java b/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/domain/MessageRepository.java index b59b8fbe4..eab368d66 100644 --- a/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/domain/MessageRepository.java +++ b/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/domain/MessageRepository.java @@ -1,5 +1,6 @@ package de.muenchen.oss.wahllokalsystem.domain; +import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.data.repository.CrudRepository; @@ -12,4 +13,7 @@ public interface MessageRepository extends CrudRepository { Optional findFirstByWahlbezirkIDOrderByEmpfangsZeit(String wahlbezirkID); + List findByWahlbezirkID(String number); + + Message findByNachricht(String s); } diff --git a/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/service/BroadcastService.java b/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/service/BroadcastService.java index 05fc5b9a0..f9acfe878 100644 --- a/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/service/BroadcastService.java +++ b/wls-broadcast-service/src/main/java/de/muenchen/oss/wahllokalsystem/service/BroadcastService.java @@ -39,7 +39,7 @@ public void broadcast(final BroadcastMessageDTO messageToBroadcast){ log.debug("#broadcast"); - // To Do Validierung Über die Validation API + // To Do Validierung Über die Validation API, correct also Test de/muenchen/oss/wahllokalsystem/rest/BroadcastControllerTest.java /*if ( wahlbezirkIDs == null || wahlbezirkIDs.isEmpty() || Strings.isNullOrEmpty(nachricht)) { throw WlsExceptionFactory.build(ExceptionKonstanten.CODE_NACHRICHTENABRUFEN_PARAMETER_UNVOLLSTAENDIG); }*/ @@ -53,16 +53,13 @@ public void broadcast(final BroadcastMessageDTO messageToBroadcast){ return message; }).toList(); - log.debug("Storing {} new messages...", messagesToSave.size()); - messageRepo.saveAll(messagesToSave); } @PreAuthorize("hasAuthority('Broadcast_BUSINESSACTION_GetMessage')") public MessageDTO getOldestMessage(String wahlbezirkID) throws FachlicheWlsException { log.debug("#nachrichtenAbrufen"); - - //ToDo: Wird später + //ToDo: Wird später aus neuem wls-common exception ExceptionKonstanten etwa gebaut /* if (Strings.isNullOrEmpty(wahlbezirkID)) { throw WlsExceptionFactory.build(ExceptionKonstanten.CODE_NACHRICHTENABRUFEN_PARAMETER_UNVOLLSTAENDIG); @@ -79,17 +76,24 @@ public MessageDTO getOldestMessage(String wahlbezirkID) throws FachlicheWlsExcep @PreAuthorize("hasAuthority('Broadcast_BUSINESSACTION_MessageRead')") public void deleteMessage(String nachrichtID) { //TODO UUID als Parameter - log.debug("#nachrichtGelesen"); // if (Strings.isNullOrEmpty(nachrichtID)) { // throw WlsExceptionFactory.build(ExceptionKonstanten.CODE_NACHRICHTENABRUFEN_PARAMETER_UNVOLLSTAENDIG); // } val nachrichtUUID = java.util.UUID.fromString(nachrichtID); + //TODO hat das Altsystem einen Fehler geworfen wenn er nichts gefunden hat? + // Das Altsystem hat so getan alswürde es werfen: + // catch (Exception e) { + // LOG.info("Message with OID:" + nachrichtUUID + "already deleted"); + // } + // In Wirklichkeit wirft in diesem Fall CrudRepository keine Exception + // https://github.com/spring-projects/spring-data-commons/issues/2651 try { messageRepo.deleteById(nachrichtUUID); } catch (Exception e) { - log.info("Message with OID:" + nachrichtUUID + "already deleted"); //TODO hat das Altsystem einen Fehler geworfen + //ToDo aus neuen ExceptionKonstanten etwas finden + log.error("Message with OID:" + nachrichtUUID + " could not be deleted"); } } diff --git a/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/configuration/UnicodeConfigurationTest.java b/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/configuration/UnicodeConfigurationTest.java index fd3e79e9e..142784db3 100644 --- a/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/configuration/UnicodeConfigurationTest.java +++ b/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/configuration/UnicodeConfigurationTest.java @@ -58,7 +58,7 @@ class UnicodeConfigurationTest { @Test void testForNfcNormalization() { // Persist entity with decomposed string. - final MessageDTO messageDTO = new MessageDTO(UUID.fromString("id_1"), "wahlbezirkID_1", TEXT_ATTRIBUTE_DECOMPOSED, LocalDateTime.of(1990, 10, 3, 2, 47)); + final MessageDTO messageDTO = new MessageDTO(UUID.fromString("1-2-3-4-5"), "wahlbezirkID_1", TEXT_ATTRIBUTE_DECOMPOSED, LocalDateTime.of(1990, 10, 3, 2, 47)); final TheEntityDto theEntityDto = new TheEntityDto(); theEntityDto.setMyMessageDTO(messageDTO); diff --git a/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/domain/MessageRepositoryTest.java b/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/domain/MessageRepositoryTest.java index 1f989b806..3f81b1bf4 100644 --- a/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/domain/MessageRepositoryTest.java +++ b/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/domain/MessageRepositoryTest.java @@ -2,7 +2,8 @@ import static de.muenchen.oss.wahllokalsystem.TestConstants.SPRING_NO_SECURITY_PROFILE; import static de.muenchen.oss.wahllokalsystem.TestConstants.SPRING_TEST_PROFILE; -import static org.junit.jupiter.api.Assertions.*; + +import org.assertj.core.api.Assertions; import de.muenchen.oss.wahllokalsystem.MicroServiceApplication; import de.muenchen.oss.wahllokalsystem.rest.BroadcastMessageDTO; import de.muenchen.oss.wahllokalsystem.service.BroadcastService; @@ -10,6 +11,8 @@ import java.util.Comparator; import java.util.List; import java.util.Optional; +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -26,6 +29,7 @@ } ) @ActiveProfiles(profiles = { SPRING_TEST_PROFILE, SPRING_NO_SECURITY_PROFILE }) +@Slf4j class MessageRepositoryTest { @Autowired @@ -38,19 +42,24 @@ class MessageRepositoryTest { @Transactional(propagation = Propagation.REQUIRED, noRollbackFor = Exception.class) void testSave() { + String originalOid = "1-2-3-4-5"; + String originalNachricht = "Test Nachricht"; + // Implement your logic here by replacing and/or extending the code // initialize Message original = new Message(); - original.setNachricht("test nachricht"); + original.setOid(UUID.fromString(originalOid)); + original.setNachricht(originalNachricht); // persist original = repository.save(original); // check Message persisted = repository.findById(original.getOid()).orElse(null); - assertNotNull(persisted); - assertEquals(original, persisted); + + Assertions.assertThat(persisted).isNotNull(); + Assertions.assertThat(persisted).isEqualTo(original); } @@ -62,6 +71,7 @@ void testSave() { void testFirst() { List wahlbezirke = Arrays.asList("1", "2", "3", "4"); + String searchedWahlbezirkID = "3"; BroadcastMessageDTO m1 = new BroadcastMessageDTO(wahlbezirke, "Ich bin Nachricht_1"); broadcast_S.broadcast(m1); @@ -74,23 +84,23 @@ void testFirst() { BroadcastMessageDTO m5 = new BroadcastMessageDTO(wahlbezirke, "Ich bin Nachricht_5"); broadcast_S.broadcast(m5); - Optional optionalFoundMessage = repository.findFirstByWahlbezirkIDOrderByEmpfangsZeit("3"); + //Expected -sent Message List allMessages = (List) repository.findAll(); - allMessages.sort( Comparator .comparing((Message m) -> m.getEmpfangsZeit().toLocalDate()) .reversed() - .thenComparing( - Comparator - .comparing((Message m) -> m.getEmpfangsZeit().toLocalTime() - ) - - ) + .thenComparing((Message m) -> m.getEmpfangsZeit().toLocalTime()) ); - assertEquals(optionalFoundMessage.get(), allMessages.get(0)); + Message sentMessage = allMessages.stream() + .filter(mes -> mes.getWahlbezirkID().equals(searchedWahlbezirkID)) + .findFirst() + .get(); + //Actual - Found + Optional optionalFoundMessage = repository.findFirstByWahlbezirkIDOrderByEmpfangsZeit(searchedWahlbezirkID); + Assertions.assertThat(sentMessage).isEqualTo(optionalFoundMessage.get()); } } \ No newline at end of file diff --git a/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/domain/MessageTest.java b/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/domain/MessageTest.java index 646eedac2..3f24c16f3 100644 --- a/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/domain/MessageTest.java +++ b/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/domain/MessageTest.java @@ -43,7 +43,8 @@ void failurOnWahlbezirkIdIsMissing() { @Test void failurOnWahlbezirkIdIsMoreThan1024Chars() { val message = createMessageWithAllRequiredData(); - message.setWahlbezirkID(StringUtils.left("", 1025)); + String myString = " ".repeat(1025); + message.setWahlbezirkID(myString); val validationResult = validator.validate(message); @@ -63,7 +64,8 @@ void failurOnNachrichtIsNull() { @Test void failurOnNachrichtIsMoreThan1024Chars() { val message = createMessageWithAllRequiredData(); - message.setNachricht(StringUtils.left("", 1025)); + String myString = " ".repeat(1025); + message.setNachricht(myString); val validationResult = validator.validate(message); diff --git a/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/rest/BroadcastControllerTest.java b/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/rest/BroadcastControllerTest.java new file mode 100644 index 000000000..a9262409e --- /dev/null +++ b/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/rest/BroadcastControllerTest.java @@ -0,0 +1,173 @@ +package de.muenchen.oss.wahllokalsystem.rest; + +import static de.muenchen.oss.wahllokalsystem.TestConstants.SPRING_NO_SECURITY_PROFILE; +import static de.muenchen.oss.wahllokalsystem.TestConstants.SPRING_TEST_PROFILE; +import de.muenchen.oss.wahllokalsystem.domain.Message; +import de.muenchen.oss.wahllokalsystem.wls.common.exception.FachlicheWlsException; +import de.muenchen.oss.wahllokalsystem.wls.common.exception.util.ExceptionKonstanten; +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.List; +import org.assertj.core.api.Assertions; +import de.muenchen.oss.wahllokalsystem.MicroServiceApplication; +import de.muenchen.oss.wahllokalsystem.domain.MessageRepository; +import de.muenchen.oss.wahllokalsystem.service.BroadcastService; +import de.muenchen.oss.wahllokalsystem.utils.BroadcastSecurityUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ActiveProfiles; + +@SpringBootTest( + classes = { MicroServiceApplication.class }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { + "spring.datasource.url=jdbc:h2:mem:wahllokalsystem;DB_CLOSE_ON_EXIT=FALSE", + "refarch.gracefulshutdown.pre-wait-seconds=0" + } +) +@ActiveProfiles(profiles = { SPRING_TEST_PROFILE, SPRING_NO_SECURITY_PROFILE }) +class BroadcastControllerTest { + + @Autowired + BroadcastService broadcast_S; + + @Autowired + private MessageRepository messageRepo; + + @BeforeEach + public void setup() { + Assertions.assertThat(broadcast_S).isNotNull(); + SecurityContextHolder.clearContext(); + BroadcastSecurityUtils.grantFullAccess(); + messageRepo.deleteAll(); + } + + + /** + * To Do Test if right Exception will be thrown after implementing + * Validierung Über die Validation API in + * src/main/java/de/muenchen/oss/wahllokalsystem/service/BroadcastService.java + */ + //@Test(expected = WlsException.class) + //public void broadcast_WahlbezirkID_Null_Test() { + // broadcast_S.broadcast(null, null, null); + //} + //@Test(expected = WlsException.class) + //public void getMessage_WahlbezirkID_Null_Test() throws Exception { + // broadcast_S.getMessage(null, null); + //} +// @Test(expected = WlsException.class) +// public void messageRead_NachrichtID_Null_Test() { +// messageReadBusinessActionService.messageRead(null, null); +// } + + @Test + void broadcast() { + List wahlbezirke = Arrays.asList("1", "2", "3", "4"); + String broadcastMessage = "Dies ist eine Broadcast-Nachricht"; + + BroadcastMessageDTO m1 = new BroadcastMessageDTO(wahlbezirke, broadcastMessage); + broadcast_S.broadcast(m1); + + List messages = messageRepo.findByWahlbezirkID("4"); + + Assertions.assertThat(messages.size()).isEqualTo(1); + Assertions.assertThat(broadcastMessage).isEqualTo(messages.get(0).getNachricht()); + } + + @Test + public void getOldestMessage_No_Message_Test() { + + RuntimeException thrownException = null; + try{ + broadcast_S.getOldestMessage("123"); + } catch (Exception e){ + thrownException = (RuntimeException) e; + } + + Assertions.assertThat(thrownException) + .isNotNull() + .isInstanceOf(FachlicheWlsException.class) + .hasMessageStartingWith("No message found") + .extracting("code") + .isEqualTo(ExceptionKonstanten.CODE_ENTITY_NOT_FOUND); + + } + + @Test + public void getOldestMessageTest(){ + String wahlbezirkID = "4711"; + LocalDateTime time = LocalDateTime.of(2018, 5, 29, 12, 0); + String messageToSave = "This is the test Message"; + + Message msg1 = new Message(); + msg1.setWahlbezirkID(wahlbezirkID); + msg1.setNachricht(messageToSave); + msg1.setEmpfangsZeit(time); + messageRepo.save(msg1); + + MessageDTO foundMessage = broadcast_S.getOldestMessage(wahlbezirkID); + Assertions.assertThat(msg1.getNachricht()).isEqualTo(foundMessage.nachricht()); + } + + @Test + public void getOldestMessage_MultipleMessageTest(){ + String wahlbezirkID = "4711"; + LocalDateTime time = LocalDateTime.of(2018, 5, 29, 12, 0); + String messageToSave1 = "This is the test Message1"; + String messageToSave2 = "This is the test Message2"; + + Message msg1 = new Message(); + msg1.setWahlbezirkID(wahlbezirkID); + msg1.setNachricht(messageToSave1); + msg1.setEmpfangsZeit(time); + + Message msg2 = new Message(); + msg2.setWahlbezirkID(wahlbezirkID); + msg2.setNachricht(messageToSave2); + msg2.setEmpfangsZeit(time.minusYears(1L)); + + messageRepo.save(msg1); + messageRepo.save(msg2); + + String foundMessage = broadcast_S.getOldestMessage(wahlbezirkID).nachricht(); + Assertions.assertThat(messageToSave2).isEqualTo(foundMessage); + } + + @Test + public void deleteMessage_messageRead_DoubleDelete_Test() { + String wahlbezirkID_1 = "1", wahlbezirkID_2 = "2"; + LocalDateTime time = LocalDateTime.of(2018, 5, 29, 12, 0); + + String MESSAGE = "Message"; + Message msg1 = new Message(); + msg1.setWahlbezirkID(wahlbezirkID_1); + msg1.setNachricht(MESSAGE + wahlbezirkID_1); + msg1.setEmpfangsZeit(time); + + Message msg2 = new Message(); + msg2.setWahlbezirkID(wahlbezirkID_2); + msg2.setNachricht(MESSAGE + wahlbezirkID_2); + msg2.setEmpfangsZeit(time.minusYears(1L)); + + messageRepo.save(msg1); + messageRepo.save(msg2); + + Message message_1 = messageRepo.findByNachricht(MESSAGE + wahlbezirkID_1); + broadcast_S.deleteMessage(message_1.getOid().toString()); + + List stillExistingMessages = messageRepo.findByWahlbezirkID(wahlbezirkID_2); + + Assertions.assertThat(stillExistingMessages) + .hasSize(1) + .hasAtLeastOneElementOfType(Message.class); + + Assertions.assertThat(MESSAGE + wahlbezirkID_2).isEqualTo(stillExistingMessages.get(0).getNachricht()); + Assertions.assertThat(MESSAGE + wahlbezirkID_2).isEqualTo(stillExistingMessages.get(0).getNachricht()); + + broadcast_S.deleteMessage(message_1.getOid().toString()); + } +} \ No newline at end of file diff --git a/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/rest/TheEntityRepositoryTest.java b/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/rest/TheEntityRepositoryTest.java deleted file mode 100644 index b57390b53..000000000 --- a/wls-broadcast-service/src/test/java/de/muenchen/oss/wahllokalsystem/rest/TheEntityRepositoryTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c): it@M - Dienstleister für Informations- und Telekommunikationstechnik - * der Landeshauptstadt München, 2024 - */ -package de.muenchen.oss.wahllokalsystem.rest; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; - -import de.muenchen.oss.wahllokalsystem.MicroServiceApplication; -import de.muenchen.oss.wahllokalsystem.domain.TheEntity; - -import static de.muenchen.oss.wahllokalsystem.TestConstants.SPRING_TEST_PROFILE; -import static de.muenchen.oss.wahllokalsystem.TestConstants.SPRING_NO_SECURITY_PROFILE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -@SpringBootTest( - classes = { MicroServiceApplication.class }, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "spring.datasource.url=jdbc:h2:mem:wahllokalsystem;DB_CLOSE_ON_EXIT=FALSE", - "refarch.gracefulshutdown.pre-wait-seconds=0" - } -) -@ActiveProfiles(profiles = { SPRING_TEST_PROFILE, SPRING_NO_SECURITY_PROFILE }) -class TheEntityRepositoryTest { - - @Autowired - private TheEntityRepository repository; - - @Test - @Transactional(propagation = Propagation.REQUIRED, noRollbackFor = Exception.class) - void testSave() { - - // Implement your logic here by replacing and/or extending the code - - // initialize - TheEntity original = new TheEntity(); - original.setTextAttribute("test"); - - // persist - original = repository.save(original); - - // check - TheEntity persisted = repository.findById(original.getId()).orElse(null); - assertNotNull(persisted); - assertEquals(original, persisted); - - } - -}