From ada64feeadbbaa4de92623ae33b38ef235409c23 Mon Sep 17 00:00:00 2001
From: Oto Stanko <493068@fi.muni.cz>
Date: Sun, 16 Apr 2023 23:07:43 +0200
Subject: [PATCH] Rest of the tests and checkstyle

---
 .../cz/muni/pa165/race/service/DbGetter.java  | 41 ++++++++++
 .../muni/pa165/race/service/RaceService.java  | 20 ++---
 .../pa165/race/rest/RaceControllerTest.java   | 82 +++++++++++++------
 .../cz/muni/pa165/race/rest/RaceTestUtil.java | 17 +++-
 .../pa165/race/rest/SeasonControllerTest.java | 61 +++++++-------
 .../muni/pa165/race/rest/SeasonTestUtil.java  |  7 +-
 6 files changed, 155 insertions(+), 73 deletions(-)
 create mode 100644 race/src/main/java/cz/muni/pa165/race/service/DbGetter.java

diff --git a/race/src/main/java/cz/muni/pa165/race/service/DbGetter.java b/race/src/main/java/cz/muni/pa165/race/service/DbGetter.java
new file mode 100644
index 00000000..e8f0b5bc
--- /dev/null
+++ b/race/src/main/java/cz/muni/pa165/race/service/DbGetter.java
@@ -0,0 +1,41 @@
+package cz.muni.pa165.race.service;
+
+import cz.muni.pa165.common_library.dtos.CarResponseDto;
+import cz.muni.pa165.common_library.dtos.DriverDto;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestTemplate;
+
+/**
+ * Getter for driver and car from appropriate modules.
+ */
+@Component
+public class DbGetter {
+
+  @Autowired
+  RestTemplate client;
+
+  /**
+   * Calls driver module for a driver given by id.
+   *
+   * @param driverId id of a driver.
+   * @return driverDto.
+   */
+  public DriverDto getDriver(Long driverId) {
+    var response =
+        client.getForEntity("http://localhost:8083/driver/get/id=" + driverId, DriverDto.class);
+    return response.getBody();
+  }
+
+  /**
+   * Calls car module for a car given by id.
+   *
+   * @param carId id of a car.
+   * @return carDto.
+   */
+  public CarResponseDto getCar(Long carId) {
+    var response =
+        client.getForEntity("http://localhost:8082/car/?carId=" + carId, CarResponseDto.class);
+    return response.getBody();
+  }
+}
diff --git a/race/src/main/java/cz/muni/pa165/race/service/RaceService.java b/race/src/main/java/cz/muni/pa165/race/service/RaceService.java
index 48797427..dd175641 100644
--- a/race/src/main/java/cz/muni/pa165/race/service/RaceService.java
+++ b/race/src/main/java/cz/muni/pa165/race/service/RaceService.java
@@ -32,7 +32,7 @@ public class RaceService implements RaceServiceI {
   RaceRepository raceRepository;
 
   @Autowired
-  RestTemplate client;
+  DbGetter dbGetter;
 
   RaceService(RaceRepository raceRepository) {
     this.raceRepository = raceRepository;
@@ -66,12 +66,12 @@ public class RaceService implements RaceServiceI {
     var race = raceRepository.findById(raceId)
         .orElseThrow(() -> new DatabaseException("Race not found"));
 
-    var driver = getDriver(driverId);
+    var driver = dbGetter.getDriver(driverId);
     if (race.getDriver2() != null && Objects.equals(race.getDriver2().getDriverId(), driverId)) {
       throw new BadRequestException("Driver already assigned to the race as driver two");
     }
 
-    var car = getCar(carId);
+    var car = dbGetter.getCar(carId);
     if (race.getDriver2() != null && Objects.equals(race.getDriver2().getCarId(), carId)) {
       throw new BadRequestException("Car is already assigned to the race for driver two");
     }
@@ -87,11 +87,11 @@ public class RaceService implements RaceServiceI {
     var race = raceRepository.findById(raceId)
         .orElseThrow(() -> new DatabaseException("Race not found"));
 
-    var driver = getDriver(driverId);
+    var driver = dbGetter.getDriver(driverId);
     if (race.getDriver1() != null && Objects.equals(race.getDriver1().getDriverId(), driverId)) {
       throw new BadRequestException("Driver already assigned to the race as driver one");
     }
-    var car = getCar(carId);
+    var car = dbGetter.getCar(carId);
     if (race.getDriver1() != null && Objects.equals(race.getDriver1().getCarId(), carId)) {
       throw new BadRequestException("Car is already assigned to the race for driver two");
     }
@@ -253,15 +253,5 @@ public class RaceService implements RaceServiceI {
     return raceDto;
   }
 
-  private DriverDto getDriver(Long driverId) {
-    var response =
-        client.getForEntity("http://localhost:8083/driver/get/id=" + driverId, DriverDto.class);
-    return response.getBody();
-  }
 
-  private CarResponseDto getCar(Long carId) {
-    var response =
-        client.getForEntity("http://localhost:8082/car/?carId=" + carId, CarResponseDto.class);
-    return response.getBody();
-  }
 }
diff --git a/race/src/test/java/cz/muni/pa165/race/rest/RaceControllerTest.java b/race/src/test/java/cz/muni/pa165/race/rest/RaceControllerTest.java
index 590aab0f..39665d91 100644
--- a/race/src/test/java/cz/muni/pa165/race/rest/RaceControllerTest.java
+++ b/race/src/test/java/cz/muni/pa165/race/rest/RaceControllerTest.java
@@ -1,19 +1,5 @@
 package cz.muni.pa165.race.rest;
 
-import cz.muni.pa165.race.data.model.Race;
-import cz.muni.pa165.race.data.repository.RaceRepository;
-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.context.SpringBootTest;
-import org.springframework.boot.test.mock.mockito.MockBean;
-import org.springframework.http.MediaType;
-import org.springframework.test.web.servlet.MockMvc;
-
-import java.util.List;
-import java.util.Optional;
-
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.BDDMockito.given;
@@ -22,9 +8,24 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
 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.result.MockMvcResultHandlers.print;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
 
+import cz.muni.pa165.common_library.dtos.CarResponseDto;
+import cz.muni.pa165.common_library.dtos.DriverDto;
+import cz.muni.pa165.race.data.model.Race;
+import cz.muni.pa165.race.data.repository.RaceRepository;
+import cz.muni.pa165.race.service.DbGetter;
+import java.util.List;
+import java.util.Optional;
+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.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
 
 @SpringBootTest
 @AutoConfigureMockMvc
@@ -40,8 +41,22 @@ class RaceControllerTest {
               }
             }
         """;
-  private String expectedMessagePost = "{\"id\":1,\"raceInfo\":{\"location\":\"MONACO\",\"name\":\"Monaco Grand Prix 2023\",\"prizePool\":30000000},\"driverOne\":{\"driverId\":1,\"carId\":1,\"position\":null},\"driverTwo\":{\"driverId\":2,\"carId\":2,\"position\":null}}";
-
+  private String expectedMessagePost = "{\"id\":1,\"raceInfo\":{\"location\":\"MONACO\","
+      + "\"name\":\"Monaco Grand Prix 2023\",\"prizePool\":30000000},\"driverOne\""
+      + ":{\"driverId\":1,\"carId\":1,\"position\":null},\"driverTwo\":{\"driverId\""
+      + ":2,\"carId\":2,\"position\":null}}";
+  private String expectedMessageAssignTwo = "{\"id\":1,\"raceInfo\":{\"location\":"
+      + "\"MONACO\",\"name\":\"Monaco Grand Prix 2023\",\"prizePool\":30000000},"
+      + "\"driverOne\":{\"driverId\":1,\"carId\":1,\"position\":null},\"driverTwo\""
+      + ":{\"driverId\":1,\"carId\":1,\"position\":null}}";
+  private String expectedMessageGet = "{\"id\":1,\"raceInfo\":{\"location\":\"MONACO\""
+      + ",\"name\":\"Monaco Grand Prix 2023\",\"prizePool\":30000000},\"driverOne\""
+      + ":{\"driverId\":1,\"carId\":1,\"position\":null},\"driverTwo\":{\"driverId\""
+      + ":2,\"carId\":2,\"position\":null}}";
+  private String expectedMessageGetAll = "[{\"id\":1,\"raceInfo\":{\"location\""
+      + ":\"MONACO\",\"name\":\"Monaco Grand Prix 2023\",\"prizePool\":30000000},\""
+      + "driverOne\":{\"driverId\":1,\"carId\":1,\"position\":null},\"driverTwo\":{\""
+      + "driverId\":2,\"carId\":2,\"position\":null}}]";
 
   @Autowired
   private MockMvc mockMvc;
@@ -49,6 +64,9 @@ class RaceControllerTest {
   @MockBean
   private RaceRepository raceRepository;
 
+  @MockBean
+  private DbGetter dbGetter;
+
   @BeforeEach
   void setup() {
     Race raceDao = RaceTestUtil.getDaoRace();
@@ -57,6 +75,10 @@ class RaceControllerTest {
     given(raceRepository.findById(anyLong())).willReturn(
         Optional.of(raceDao));
     given(raceRepository.findAll()).willReturn(List.of(raceDao));
+    CarResponseDto carDao = RaceTestUtil.getCarDao();
+    given(dbGetter.getCar(anyLong())).willReturn(carDao);
+    DriverDto driverDto = RaceTestUtil.getDriverDao();
+    given(dbGetter.getDriver(anyLong())).willReturn(driverDto);
   }
 
 
@@ -65,7 +87,6 @@ class RaceControllerTest {
     var request = post("/race/")
         .content(bodyContent)
         .contentType(MediaType.APPLICATION_JSON_VALUE);
-
     this.mockMvc.perform(request)
         .andDo(print())
         .andExpect(status().isOk())
@@ -75,7 +96,6 @@ class RaceControllerTest {
   @Test
   void deleteRace() throws Exception {
     String expectedMessage = "Race with id: 1was succesfully deleted";
-
     var requestDelete = delete("/race/")
         .param("raceId", "1")
         .contentType(MediaType.APPLICATION_JSON_VALUE);
@@ -87,26 +107,22 @@ class RaceControllerTest {
 
   @Test
   void getExistingRace() throws Exception {
-    String expectedMessage = "{\"id\":1,\"raceInfo\":{\"location\":\"MONACO\",\"name\":\"Monaco Grand Prix 2023\",\"prizePool\":30000000},\"driverOne\":{\"driverId\":1,\"carId\":1,\"position\":null},\"driverTwo\":{\"driverId\":2,\"carId\":2,\"position\":null}}";
-
     var requestGet = get("/race/id")
         .param("raceId", "1")
         .contentType(MediaType.APPLICATION_JSON_VALUE);
     this.mockMvc.perform(requestGet)
         .andDo(print())
         .andExpect(status().isOk())
-        .andExpect(content().string(expectedMessage));
+        .andExpect(content().string(expectedMessageGet));
   }
 
   @Test
   void getAllRaces() throws Exception {
     var requestGet = get("/race/");
-    String expectedMessage = "[{\"id\":1,\"raceInfo\":{\"location\":\"MONACO\",\"name\":\"Monaco Grand Prix 2023\",\"prizePool\":30000000},\"driverOne\":{\"driverId\":1,\"carId\":1,\"position\":null},\"driverTwo\":{\"driverId\":2,\"carId\":2,\"position\":null}}]";
-
     this.mockMvc.perform(requestGet)
         .andDo(print())
         .andExpect(status().isOk())
-        .andExpect(content().string(expectedMessage));
+        .andExpect(content().string(expectedMessageGetAll));
   }
 
   @Test
@@ -114,13 +130,25 @@ class RaceControllerTest {
     var requestAssign = patch("/race/assignDriverOne")
         .param("driverOneId", "1")
         .param("raceId", "1")
-        .param("carId", "2")
+        .param("carId", "1")
         .contentType(MediaType.APPLICATION_JSON_VALUE);
-
     this.mockMvc.perform(requestAssign)
         .andDo(print())
         .andExpect(status().isOk())
         .andExpect(content().string(expectedMessagePost));
   }
 
+  @Test
+  void assignDriverTwo() throws Exception {
+    var requestAssign = patch("/race/assignDriverTwo")
+        .param("driverTwoId", "2")
+        .param("raceId", "2")
+        .param("carId", "2")
+        .contentType(MediaType.APPLICATION_JSON_VALUE);
+    this.mockMvc.perform(requestAssign)
+        .andDo(print())
+        .andExpect(status().isOk())
+        .andExpect(content().string(expectedMessageAssignTwo));
+  }
+
 }
diff --git a/race/src/test/java/cz/muni/pa165/race/rest/RaceTestUtil.java b/race/src/test/java/cz/muni/pa165/race/rest/RaceTestUtil.java
index 7606cb9b..164179e3 100644
--- a/race/src/test/java/cz/muni/pa165/race/rest/RaceTestUtil.java
+++ b/race/src/test/java/cz/muni/pa165/race/rest/RaceTestUtil.java
@@ -1,13 +1,19 @@
 package cz.muni.pa165.race.rest;
 
+import cz.muni.pa165.common_library.dtos.CarResponseDto;
+import cz.muni.pa165.common_library.dtos.DriverDto;
 import cz.muni.pa165.common_library.dtos.Location;
-import cz.muni.pa165.common_library.dtos.RaceDto;
 import cz.muni.pa165.race.data.model.Race;
 
 /**
- * @author Oto Stanko
+ * Util functions for race tests.
  */
 public class RaceTestUtil {
+  /**
+   * Returns a created race.
+   *
+   * @return a race.
+   */
   public static Race getDaoRace() {
     return Race.builder()
         .id(1L)
@@ -31,4 +37,11 @@ public class RaceTestUtil {
         .build();
   }
 
+  public static CarResponseDto getCarDao() {
+    return new CarResponseDto(1L, null, null, 1L);
+  }
+
+  public static DriverDto getDriverDao() {
+    return new DriverDto(1L, "Name", "Surname");
+  }
 }
diff --git a/race/src/test/java/cz/muni/pa165/race/rest/SeasonControllerTest.java b/race/src/test/java/cz/muni/pa165/race/rest/SeasonControllerTest.java
index 61647089..bc1ce050 100644
--- a/race/src/test/java/cz/muni/pa165/race/rest/SeasonControllerTest.java
+++ b/race/src/test/java/cz/muni/pa165/race/rest/SeasonControllerTest.java
@@ -1,19 +1,5 @@
 package cz.muni.pa165.race.rest;
 
-import cz.muni.pa165.race.data.model.Season;
-import cz.muni.pa165.race.data.repository.SeasonRepository;
-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.context.SpringBootTest;
-import org.springframework.boot.test.mock.mockito.MockBean;
-import org.springframework.http.MediaType;
-import org.springframework.test.web.servlet.MockMvc;
-
-import java.util.List;
-import java.util.Optional;
-
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.BDDMockito.given;
@@ -25,6 +11,24 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
+import cz.muni.pa165.race.data.model.Race;
+import cz.muni.pa165.race.data.model.Season;
+import cz.muni.pa165.race.data.repository.RaceRepository;
+import cz.muni.pa165.race.data.repository.SeasonRepository;
+import java.util.List;
+import java.util.Optional;
+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.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
+
+/**
+ * Tests for season controller.
+ */
 @SpringBootTest
 @AutoConfigureMockMvc
 public class SeasonControllerTest {
@@ -36,7 +40,11 @@ public class SeasonControllerTest {
         }
       """;
   private String expectedMessagePost = "{\"id\":1,\"year\":2023,\"races\":[]}";
-
+  private String expectedMessageDelete = "Season with id: 1was succesfully deleted";
+  private String expectedMessageGet = "{\"id\":1,\"year\":2023,\"races\":[]}";
+  private String expectedMessageGetAll = "[{\"id\":1,\"year\":2023,\"races\":[]}]";
+  private String expectedMessageAddRace = "{\"id\":1,\"year\":2023,\"races\":[{\""
+      + "id\":1,\"name\":\"Monaco Grand Prix 2023\"}]}";
 
   @Autowired
   private MockMvc mockMvc;
@@ -44,14 +52,20 @@ public class SeasonControllerTest {
   @MockBean
   private SeasonRepository seasonRepository;
 
+  @MockBean
+  private RaceRepository raceRepository;
+
   @BeforeEach
   void setup() {
     Season seasonDao = SeasonTestUtil.getDaoSeason();
+    Race raceDao = RaceTestUtil.getDaoRace();
     given(seasonRepository.save(any(Season.class))).willReturn(
         seasonDao);
     given(seasonRepository.findById(anyLong())).willReturn(
         Optional.of(seasonDao));
     given(seasonRepository.findAll()).willReturn(List.of(seasonDao));
+    given(raceRepository.findById(anyLong())).willReturn(
+        Optional.of(raceDao));
   }
 
 
@@ -60,7 +74,6 @@ public class SeasonControllerTest {
     var request = post("/season/")
         .content(bodyContent)
         .contentType(MediaType.APPLICATION_JSON_VALUE);
-
     this.mockMvc.perform(request)
         .andDo(print())
         .andExpect(status().isOk())
@@ -69,39 +82,33 @@ public class SeasonControllerTest {
 
   @Test
   void deleteRace() throws Exception {
-    String expectedMessage = "Season with id: 1was succesfully deleted";
-
     var requestDelete = delete("/season/")
         .param("seasonId", "1")
         .contentType(MediaType.APPLICATION_JSON_VALUE);
     this.mockMvc.perform(requestDelete)
         .andDo(print())
         .andExpect(status().isOk())
-        .andExpect(content().string(expectedMessage));
+        .andExpect(content().string(expectedMessageDelete));
   }
 
   @Test
   void getExistingRace() throws Exception {
-    String expectedMessage = "{\"id\":1,\"year\":2023,\"races\":[]}";
-
     var requestGet = get("/season/id")
         .param("seasonId", "1")
         .contentType(MediaType.APPLICATION_JSON_VALUE);
     this.mockMvc.perform(requestGet)
         .andDo(print())
         .andExpect(status().isOk())
-        .andExpect(content().string(expectedMessage));
+        .andExpect(content().string(expectedMessageGet));
   }
 
   @Test
   void getAllRaces() throws Exception {
     var requestGet = get("/season/");
-    String expectedMessage = "[{\"id\":1,\"year\":2023,\"races\":[]}]";
-
     this.mockMvc.perform(requestGet)
         .andDo(print())
         .andExpect(status().isOk())
-        .andExpect(content().string(expectedMessage));
+        .andExpect(content().string(expectedMessageGetAll));
   }
 
   @Test
@@ -109,11 +116,9 @@ public class SeasonControllerTest {
     var requestPatch = patch("/season/addRace")
         .param("seasonId", "1")
         .param("raceId", "1");
-    String expectedMessage = "[{\"id\":1,\"year\":2023,\"races\":[]}]";
-
     this.mockMvc.perform(requestPatch)
         .andDo(print())
         .andExpect(status().isOk())
-        .andExpect(content().string(expectedMessage));
+        .andExpect(content().string(expectedMessageAddRace));
   }
 }
diff --git a/race/src/test/java/cz/muni/pa165/race/rest/SeasonTestUtil.java b/race/src/test/java/cz/muni/pa165/race/rest/SeasonTestUtil.java
index 4655a413..7c739315 100644
--- a/race/src/test/java/cz/muni/pa165/race/rest/SeasonTestUtil.java
+++ b/race/src/test/java/cz/muni/pa165/race/rest/SeasonTestUtil.java
@@ -4,9 +4,14 @@ import cz.muni.pa165.race.data.model.Season;
 import java.util.ArrayList;
 
 /**
- * @author Oto Stanko
+ * Utils for season tests.
  */
 public class SeasonTestUtil {
+  /**
+   * Returns a created Season.
+   *
+   * @return a season.
+   */
   public static Season getDaoSeason() {
     return Season.builder()
         .id(1L)
-- 
GitLab