Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • xgulcik/pa165-formula-one-team
1 result
Show changes
Commits on Source (45)
Showing
with 908 additions and 123 deletions
......@@ -48,7 +48,11 @@ Common classes used across the application.
Management of cars.
Runs on port 8082.
Extended functionality for car module: For a given car and its component, both given by their respective IDs,
a list of sparse components can be fetched from carComponent module. A sparse component is any component
with the same name as the given component of the car that is not used by the car.
WARNING: when putting components or drivers, services component and driver need to run.
### component
......@@ -70,7 +74,15 @@ Runs on port 8083.
`mvn -pl race spring-boot:run`
Management of races.
Management of races. Extended functionality for this module
is endpoint findMostSuitableDriverForLocation. This endpoint finds drivers with max
points from all races at given location.
WARNING: when posting race with driver or car assigned,
you have to run also car and driver services in order to check that these objects exist.
You can create race without driverOne and driverTwo.
Corresponding services need to run when also assigning drivers or cars in other endpoints.
Runs on port 8081.
......
......@@ -52,6 +52,13 @@
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>17</maven.compiler.source>
......
package cz.muni.pa165.car;
import cz.muni.pa165.car.data.model.Car;
import cz.muni.pa165.common_library.exception.RestExceptionHandler;
import jakarta.transaction.Transactional;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
/**
* Main app.
*/
@SpringBootApplication
@EnableJpaRepositories(basePackages = {"cz.muni.pa165.car.data.repository"})
@EnableTransactionManagement
@EntityScan(basePackageClasses = {Car.class})
//@Import({RestExceptionHandler.class, ClientConfig.class})
@Transactional
@EntityScan(basePackages = {"cz.muni.pa165.car.data.model"})
@Import(RestExceptionHandler.class)
public class App {
......
package cz.muni.pa165.car.data.repository;
import cz.muni.pa165.car.data.model.Car;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* Car Repository for Driver Manager.
*/
@Repository
public interface CarRepository extends JpaRepository<Car, Long> {}
public interface CarRepository extends JpaRepository<Car, Long> {
@Query("SELECT c FROM Car c WHERE c.id = :id")
Optional<Car> findById(@Param("id") Long id);
@Query("SELECT c FROM Car c")
List<Car> findAll();
}
......@@ -7,6 +7,7 @@ import cz.muni.pa165.common_library.dtos.CarResponseDto;
import io.swagger.v3.oas.annotations.Operation;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
......@@ -26,6 +27,9 @@ public class CarComponentPairController {
CarComponentPairService carComponentService;
@Autowired
DbGetter dbGetter;
public CarComponentPairController(CarComponentPairService carComponentService) {
this.carComponentService = carComponentService;
}
......@@ -56,7 +60,7 @@ public class CarComponentPairController {
@PutMapping(path = "/removecomponent",
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CarResponseDto> removeComponent(@RequestParam Long componentId,
@RequestParam Long carId) {
@RequestParam Long carId) {
return ResponseEntity.ok(carComponentService.removeComponent(componentId, carId));
}
......@@ -69,8 +73,8 @@ public class CarComponentPairController {
@Operation(summary = "Get all components of a car")
@GetMapping(path = "/getcomponents",
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<CarComponentResponseDto>>
getAllComponentsOfCar(@RequestParam Long carId) {
public ResponseEntity<List<CarComponentResponseDto>> getAllComponentsOfCar(
@RequestParam Long carId) {
return ResponseEntity.ok(carComponentService.getAllComponentsOfCar(carId));
}
......@@ -84,10 +88,10 @@ public class CarComponentPairController {
*/
@Operation(summary = "Get all components from component repo")
@GetMapping(path = "/getsparecomponents",
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<CarComponentResponseDto>>
getAllCarComponents(@RequestParam Long carId, @RequestParam Long componentId) {
List<CarComponentResponseDto> allComponents = DbGetter.getAllComponentsFromDb();
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<CarComponentResponseDto>> getAllCarComponents(@RequestParam Long carId,
@RequestParam Long componentId) {
List<CarComponentResponseDto> allComponents = dbGetter.getAllComponentsFromDb();
var carComponentsResponse = getAllComponentsOfCar(carId);
var carComponents = carComponentsResponse.getBody();
CarComponentResponseDto requestedComponent = null;
......
......@@ -14,7 +14,7 @@ import org.springframework.web.client.RestTemplate;
@Component
public class DbGetter {
private static RestTemplate client = new RestTemplate();
private RestTemplate client = new RestTemplate();
private static final String GET_DRIVER_URL = "http://localhost:8083/driver/get/id=";
private static final String GET_COMPONENT_URL = "http://localhost:8084/component/id?componentId=";
......@@ -26,7 +26,7 @@ public class DbGetter {
* @param id driver id
* @return Driver object
*/
public static DriverInsightDto getDriverFromDb(Long id) {
public DriverInsightDto getDriverFromDb(Long id) {
String url = GET_DRIVER_URL + id;
ResponseEntity<DriverInsightDto> response = client.getForEntity(url, DriverInsightDto.class);
return response.getBody();
......@@ -38,7 +38,7 @@ public class DbGetter {
* @param id component id
* @return Component object
*/
public static CarComponentResponseDto getComponentFromDb(Long id) {
public CarComponentResponseDto getComponentFromDb(Long id) {
String url = GET_COMPONENT_URL + id;
ResponseEntity<CarComponentResponseDto> response =
client.getForEntity(url, CarComponentResponseDto.class);
......@@ -50,7 +50,7 @@ public class DbGetter {
*
* @return List of all car components in database.
*/
public static List<CarComponentResponseDto> getAllComponentsFromDb() {
public List<CarComponentResponseDto> getAllComponentsFromDb() {
String url = GET_ALL_COMPONENTS;
var response =
client.getForEntity(url, CarComponentResponseDto[].class);
......
package cz.muni.pa165.car.service;
import static cz.muni.pa165.car.restemplate.DbGetter.getComponentFromDb;
import cz.muni.pa165.car.data.model.Car;
import cz.muni.pa165.car.data.repository.CarRepository;
import cz.muni.pa165.car.mapper.CarMapper;
import cz.muni.pa165.car.restemplate.DbGetter;
import cz.muni.pa165.common_library.dtos.CarComponentResponseDto;
import cz.muni.pa165.common_library.dtos.CarResponseDto;
import cz.muni.pa165.common_library.exception.DatabaseException;
......@@ -12,7 +11,9 @@ import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service for manipulation with car's components.
......@@ -22,6 +23,9 @@ public class CarComponentPairServiceImpl implements CarComponentPairService {
CarRepository carRepository;
@Autowired
DbGetter dbGetter;
/**
* Constructor for Car - Car Component Service.
*
......@@ -32,6 +36,7 @@ public class CarComponentPairServiceImpl implements CarComponentPairService {
}
@Override
@Transactional
public CarResponseDto addComponent(Long componentId, Long carId) {
var car = carRepository.findById(carId).orElseThrow(
() -> new DatabaseException("Car not found"));
......@@ -40,7 +45,7 @@ public class CarComponentPairServiceImpl implements CarComponentPairService {
throw new DatabaseException("Component with id " + componentId + " already in use");
}
var components = car.getComponents();
CarComponentResponseDto carComponent = getComponentFromDb(componentId);
CarComponentResponseDto carComponent = dbGetter.getComponentFromDb(componentId);
components.add(carComponent.getId());
car.setComponents(components);
carRepository.save(car);
......@@ -63,12 +68,13 @@ public class CarComponentPairServiceImpl implements CarComponentPairService {
}
@Override
@Transactional(readOnly = true)
public List<CarComponentResponseDto> getAllComponentsOfCar(Long carId) {
var car = carRepository.findById(carId).orElseThrow(
() -> new DatabaseException("Car not found"));
var componentDtos = new ArrayList<CarComponentResponseDto>();
for (Long id : car.getComponents()) {
CarComponentResponseDto carComponent = getComponentFromDb(id);
CarComponentResponseDto carComponent = dbGetter.getComponentFromDb(id);
componentDtos.add(
new CarComponentResponseDto(
carComponent.getId(),
......
package cz.muni.pa165.car.service;
import static cz.muni.pa165.car.restemplate.DbGetter.getDriverFromDb;
import cz.muni.pa165.car.data.repository.CarRepository;
import cz.muni.pa165.car.mapper.CarMapper;
import cz.muni.pa165.car.restemplate.DbGetter;
import cz.muni.pa165.common_library.dtos.CarResponseDto;
import cz.muni.pa165.common_library.dtos.DriverDto;
import cz.muni.pa165.common_library.dtos.DriverInsightDto;
......@@ -12,7 +12,9 @@ import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service for Driver Manager.
......@@ -22,6 +24,9 @@ public class CarDriverPairServiceImpl implements CarDriverPairService {
CarRepository carRepository;
@Autowired
DbGetter dbGetter;
/**
* Constructor for Car - Driver Service.
*
......@@ -32,12 +37,13 @@ public class CarDriverPairServiceImpl implements CarDriverPairService {
}
@Override
@Transactional
public CarResponseDto assignDriverToCar(Long driverId, Long carId) {
var car = carRepository.findById(carId).orElseThrow(
() -> new DatabaseException("Car not found"));
var drivers = car.getDrivers();
var savedDriver = getDriverFromDb(driverId);
var savedDriver = dbGetter.getDriverFromDb(driverId);
drivers.add(savedDriver.id());
car.setDrivers(drivers);
......@@ -46,6 +52,7 @@ public class CarDriverPairServiceImpl implements CarDriverPairService {
}
@Override
@Transactional
public CarResponseDto unassignDriverFromCar(Long driverId, Long carId) {
var car = carRepository.findById(carId).orElseThrow(
() -> new DatabaseException("Car not found"));
......@@ -66,7 +73,7 @@ public class CarDriverPairServiceImpl implements CarDriverPairService {
() -> new DatabaseException("Car not found"));
var driverDtos = new ArrayList<DriverDto>();
for (Long id : car.getDrivers()) {
DriverInsightDto driver = getDriverFromDb(id);
DriverInsightDto driver = dbGetter.getDriverFromDb(id);
driverDtos.add(
new DriverDto(driver.id(),
driver.name(),
......@@ -77,11 +84,12 @@ public class CarDriverPairServiceImpl implements CarDriverPairService {
}
@Override
@Transactional
public CarResponseDto setMainDriver(Long carId, Long driverId) {
var car = carRepository.findById(carId).orElseThrow(
() -> new DatabaseException("Car not found"));
var savedDriver = getDriverFromDb(driverId);
var savedDriver = dbGetter.getDriverFromDb(driverId);
car.setMainDriverId(savedDriver.id());
var drivers = car.getDrivers();
......@@ -92,6 +100,7 @@ public class CarDriverPairServiceImpl implements CarDriverPairService {
}
@Override
@Transactional
public CarResponseDto removeMainDriver(Long carId) {
var car = carRepository.findById(carId).orElseThrow(
() -> new DatabaseException("Car not found"));
......
......@@ -11,8 +11,9 @@ import cz.muni.pa165.common_library.dtos.CarRequestDto;
import cz.muni.pa165.common_library.dtos.CarResponseDto;
import cz.muni.pa165.common_library.exception.DatabaseException;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
......@@ -23,6 +24,9 @@ public class CarServiceImpl implements CarService {
CarRepository carRepository;
@Autowired
DbGetter dbGetter;
/**
* Constructor for Car Service.
*
......@@ -33,6 +37,7 @@ public class CarServiceImpl implements CarService {
}
@Override
@Transactional
public CarResponseDto postCar(CarRequestDto carRequestDto) {
var componentIds = carRequestDto.getComponentIds();
......@@ -40,12 +45,13 @@ public class CarServiceImpl implements CarService {
if (isComponentInUse(componentId)) {
throw new DatabaseException("Component with id " + componentId + " already in use");
}
DbGetter.getComponentFromDb(componentId);
dbGetter.getComponentFromDb(componentId);
}
return carConverterToDto(carRepository.save(carDtoConverter(carRequestDto)));
}
@Override
@Transactional(readOnly = true)
public CarResponseDto getCarById(Long carId) {
return carConverterToDto(carRepository.findById(carId).orElseThrow(
() -> new DatabaseException(
......@@ -55,6 +61,7 @@ public class CarServiceImpl implements CarService {
}
@Override
@Transactional(readOnly = true)
public List<CarResponseDto> getAllCars() {
return carRepository
.findAll()
......@@ -64,6 +71,7 @@ public class CarServiceImpl implements CarService {
}
@Override
@Transactional
public String deleteById(Long carId) {
carRepository.deleteById(carId);
return "Car with id = " + carId + " deleted!";
......
package cz.muni.pa165.car.data.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import cz.muni.pa165.car.data.model.Car;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
@DataJpaTest
class CarRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private CarRepository carRepository;
@Test
public void saveTest() {
Car car = Car.builder()
.id(1L)
.components(Set.of(2L, 3L, 4L))
.drivers(Set.of(5L, 6L, 7L))
.mainDriverId(6L)
.build();
Car savedCar = carRepository.save(car);
Assertions.assertEquals(savedCar, car);
Assertions.assertEquals(entityManager.find(Car.class, 1L).getId(), 1);
}
@Test
public void addComponentAndSaveTest() {
Car car = Car.builder()
.id(1L)
.components(Set.of(2L, 3L, 4L))
.drivers(Set.of(6L))
.mainDriverId(6L)
.build();
Car savedCar = carRepository.save(car);
savedCar.getComponents().add(111L);
Car carWithAddedComponent = carRepository.save(savedCar);
assertTrue(carWithAddedComponent.getComponents().contains(111L));
}
@Test
public void removeComponentAndSaveTest() {
Car car = Car.builder()
.id(1L)
.components(Set.of(2L, 3L, 4L))
.drivers(Set.of(6L))
.mainDriverId(6L)
.build();
Car savedCar = carRepository.save(car);
savedCar.getComponents().remove(111L);
Car carWithAddedComponent = carRepository.save(savedCar);
assertFalse(carWithAddedComponent.getComponents().contains(111L));
}
@Test
public void getAllComponentsTest() {
Car car = Car.builder()
.id(1L)
.components(Set.of(2L, 3L, 4L))
.drivers(Set.of(6L))
.mainDriverId(6L)
.build();
Car savedCar = carRepository.save(car);
assertEquals(savedCar.getComponents(), Set.of(2L, 3L, 4L));
}
@Test
public void addDriverAndSaveTest() {
Car car = Car.builder()
.id(1L)
.components(Set.of())
.drivers(Set.of(5L, 6L, 7L))
.mainDriverId(6L)
.build();
Car savedCar = carRepository.save(car);
savedCar.getDrivers().add(111L);
Car carWithAddedDriver = carRepository.save(savedCar);
assertTrue(carWithAddedDriver.getDrivers().contains(111L));
}
@Test
public void removeDriverAndSaveTest() {
Car car = Car.builder()
.id(1L)
.components(Set.of())
.drivers(Set.of(5L, 6L, 7L))
.mainDriverId(6L)
.build();
Car savedCar = carRepository.save(car);
savedCar.getDrivers().remove(6L);
Car carWithRemovedDriver = carRepository.save(savedCar);
assertFalse(carWithRemovedDriver.getDrivers().contains(6L));
}
@Test
public void setDriverAsMainAndSaveTest() {
Car car = Car.builder()
.id(1L)
.components(Set.of())
.drivers(Set.of(5L, 6L, 7L))
.mainDriverId(6L)
.build();
Car savedCar = carRepository.save(car);
assertEquals(6L, (long) savedCar.getMainDriverId());
savedCar.setMainDriverId(7L);
Car carWithReplacedMainDriver = carRepository.save(savedCar);
assertEquals(7L, (long) savedCar.getMainDriverId());
}
@Test
public void removeDriverAsMainAndSaveTest() {
Car car = Car.builder()
.id(1L)
.components(Set.of())
.drivers(Set.of(5L, 6L, 7L))
.mainDriverId(6L)
.build();
Car savedCar = carRepository.save(car);
assertEquals(6L, (long) savedCar.getMainDriverId());
savedCar.setMainDriverId(null);
Car carWithRemovedMainDriver = carRepository.save(savedCar);
assertNull(carWithRemovedMainDriver.getMainDriverId());
}
}
package cz.muni.pa165.car.rest;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.fasterxml.jackson.databind.ObjectMapper;
import cz.muni.pa165.car.restemplate.DbGetter;
import cz.muni.pa165.car.service.CarComponentPairService;
import cz.muni.pa165.common_library.dtos.CarComponentResponseDto;
import cz.muni.pa165.common_library.dtos.CarResponseDto;
import java.math.BigDecimal;
import java.util.List;
import org.junit.jupiter.api.Assertions;
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.WebMvcTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(CarComponentPairController.class)
class CarComponentPairControllerTest {
private static CarResponseDto carResponseDto;
private static CarResponseDto carResponseDto2;
private static CarComponentResponseDto carComponentResponseDto;
private static CarComponentResponseDto carComponentResponseDto2;
@Autowired
private MockMvc mockMvc;
@MockBean
private CarComponentPairService carComponentPairServiceMock;
@Autowired
private ObjectMapper objectMapper;
@TestConfiguration
static class TestConfig {
@Bean
DbGetter dbGetter() {
return new DbGetter();
}
}
@BeforeEach
void initializeTestObjects() {
carResponseDto = CarResponseDto.builder()
.id(1L)
.componentIdsNames(List.of(1L, 2L))
.driverIdsNames(List.of(1L))
.mainDriverId(1L)
.build();
carResponseDto2 = CarResponseDto.builder()
.id(1L)
.componentIdsNames(List.of())
.driverIdsNames(List.of(1L))
.mainDriverId(1L)
.build();
carComponentResponseDto = CarComponentResponseDto.builder()
.id(1L)
.name("")
.weight(BigDecimal.TEN)
.manufacturer("")
.price(BigDecimal.TEN)
.build();
carComponentResponseDto2 = CarComponentResponseDto.builder()
.id(2L)
.name("")
.manufacturer("")
.price(BigDecimal.TEN)
.weight(BigDecimal.TEN)
.build();
}
@Test
void addComponent() throws Exception {
given(carComponentPairServiceMock.addComponent(1L, 1L)).willReturn(carResponseDto);
String response = mockMvc.perform(put("/carcomponent/addcomponent")
.param("componentId", String.valueOf(1L))
.param("carId", String.valueOf(1L))
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
CarResponseDto carResponseDto = objectMapper.readValue(response, CarResponseDto.class);
Assertions.assertEquals(1L, carResponseDto.getId());
Assertions.assertEquals(List.of(1L, 2L), carResponseDto.getComponentIdsNames());
}
@Test
void removeComponent() throws Exception {
given(carComponentPairServiceMock.removeComponent(1L, 1L)).willReturn(carResponseDto2);
String response = mockMvc.perform(put("/carcomponent/removecomponent")
.param("componentId", String.valueOf(1L))
.param("carId", String.valueOf(1L))
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
CarResponseDto carResponseDto = objectMapper.readValue(response, CarResponseDto.class);
Assertions.assertEquals(1L, carResponseDto.getId());
Assertions.assertEquals(List.of(), carResponseDto.getComponentIdsNames());
}
@Test
void getAllComponentsOfCar() throws Exception {
given(carComponentPairServiceMock.getAllComponentsOfCar(1L)).willReturn(
List.of(carComponentResponseDto, carComponentResponseDto2));
String response = mockMvc.perform(get("/carcomponent/getcomponents")
.param("carId", String.valueOf(1L))
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
List<CarComponentResponseDto> carComponentListResponse =
List.of(objectMapper.readValue(response, CarComponentResponseDto[].class));
Assertions.assertEquals(List.of(carComponentResponseDto, carComponentResponseDto2),
carComponentListResponse);
}
}
\ No newline at end of file
package cz.muni.pa165.car.rest;
import static org.mockito.BDDMockito.given;
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.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.fasterxml.jackson.databind.ObjectMapper;
import cz.muni.pa165.car.service.CarService;
import cz.muni.pa165.common_library.dtos.CarRequestDto;
import cz.muni.pa165.common_library.dtos.CarResponseDto;
import java.util.List;
import org.junit.jupiter.api.Assertions;
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.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(CarController.class)
class CarControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CarService carServiceMock;
@Autowired
private ObjectMapper objectMapper;
private static CarRequestDto carRequestDto;
private static CarResponseDto carResponseDto;
private static CarResponseDto carResponseDto2;
private static CarResponseDto carResponseDto3;
@BeforeEach
void initializeTestObjects() {
carRequestDto = CarRequestDto.builder()
.componentIds(List.of())
.driverIds(List.of())
.mainDriverId(null)
.build();
carResponseDto = CarResponseDto.builder()
.id(1L)
.componentIdsNames(List.of())
.driverIdsNames(List.of())
.mainDriverId(null)
.build();
carResponseDto2 = CarResponseDto.builder()
.id(1L)
.componentIdsNames(List.of())
.driverIdsNames(List.of())
.mainDriverId(null)
.build();
carResponseDto3 = CarResponseDto.builder()
.id(2L)
.componentIdsNames(List.of())
.driverIdsNames(List.of())
.mainDriverId(null)
.build();
}
@Test
void nonExistingPathPostTest() throws Exception {
given(carServiceMock.postCar(carRequestDto)).willReturn(carResponseDto);
mockMvc.perform(put("/car/invalidPath/"))
.andExpect(status().isNotFound());
}
@Test
void createCarTest() throws Exception {
given(carServiceMock.postCar(carRequestDto)).willReturn(carResponseDto);
String response = mockMvc.perform(post("/car/")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(carRequestDto)))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
CarResponseDto carResponseDtoResponse = objectMapper.readValue(response, CarResponseDto.class);
Assertions.assertEquals(carResponseDtoResponse, carResponseDto);
}
@Test
void deleteExistingCarTest() throws Exception {
given(carServiceMock.deleteById(1L)).willReturn("Car with id = " + 1L + " deleted!");
String response = mockMvc.perform(delete("/car/")
.param("carId", String.valueOf(1L))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
Assertions.assertEquals("Car with id = " + 1L + " deleted!", response);
}
@Test
void getCarTest() throws Exception {
given(carServiceMock.getCarById(1L)).willReturn(carResponseDto2);
String response = mockMvc.perform(get("/car/")
.param("carId", String.valueOf(1L))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
CarResponseDto carResponseDtoResponse = objectMapper.readValue(response, CarResponseDto.class);
Assertions.assertEquals(carResponseDtoResponse, carResponseDto2);
}
@Test
void getAllCarsTest() throws Exception {
given(carServiceMock.getAllCars()).willReturn(List.of(carResponseDto2, carResponseDto3));
String response = mockMvc.perform(get("/car/all"))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
List<CarResponseDto> responseList =
List.of(objectMapper.readValue(response, CarResponseDto[].class));
Assertions.assertEquals(responseList, List.of(carResponseDto2, carResponseDto3));
}
}
\ No newline at end of file
package cz.muni.pa165.car.rest;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.fasterxml.jackson.databind.ObjectMapper;
import cz.muni.pa165.car.service.CarDriverPairService;
import cz.muni.pa165.common_library.dtos.CarResponseDto;
import cz.muni.pa165.common_library.dtos.DriverDto;
import java.util.List;
import org.junit.jupiter.api.Assertions;
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.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(CarDriverPairController.class)
class CarDriverPairControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CarDriverPairService carDriverPairServiceMock;
@Autowired
private ObjectMapper objectMapper;
private static DriverDto driverDto;
private static DriverDto driverDto2;
private static CarResponseDto carResponseDto;
private static CarResponseDto carResponseDto2;
private static CarResponseDto carResponseDto3;
private static CarResponseDto carResponseDto4;
@BeforeEach
void beforeEach() {
driverDto = DriverDto.builder()
.id(1L)
.name("Fernando")
.surname("Alonso")
.build();
driverDto2 = DriverDto.builder()
.id(2L)
.name("Max")
.surname("Verstappen")
.build();
carResponseDto = CarResponseDto.builder()
.id(1L)
.componentIdsNames(List.of())
.driverIdsNames(List.of(1L))
.mainDriverId(null)
.build();
carResponseDto2 = CarResponseDto.builder()
.id(2L)
.componentIdsNames(List.of())
.driverIdsNames(List.of())
.mainDriverId(null)
.build();
carResponseDto3 = CarResponseDto.builder()
.id(3L)
.componentIdsNames(List.of())
.driverIdsNames(List.of(1L, 2L))
.mainDriverId(1L)
.build();
carResponseDto4 = CarResponseDto.builder()
.id(1L)
.componentIdsNames(List.of())
.driverIdsNames(List.of())
.mainDriverId(null)
.build();
}
@Test
void nonExistingPathPostTest() throws Exception {
given(carDriverPairServiceMock.assignDriverToCar(1L, 1L)).willReturn(carResponseDto);
mockMvc.perform(put("/cardriver/invalidpath"))
.andExpect(status().isNotFound());
}
@Test
void assignDriverToCar() throws Exception {
given(carDriverPairServiceMock.assignDriverToCar(1L, 1L)).willReturn(carResponseDto);
String response = mockMvc.perform(put("/cardriver/assign")
.param("driverId", String.valueOf(1L))
.param("carId", String.valueOf(1L))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
CarResponseDto carResponseDto = objectMapper.readValue(response, CarResponseDto.class);
Assertions.assertEquals(1L, carResponseDto.getId());
Assertions.assertEquals(List.of(1L), carResponseDto.getDriverIdsNames());
Assertions.assertNull(carResponseDto.getMainDriverId());
}
@Test
void unassignDriverFromCar() throws Exception {
given(carDriverPairServiceMock.unassignDriverFromCar(1L, 1L)).willReturn(carResponseDto4);
String response = mockMvc.perform(put("/cardriver/unassign")
.param("driverId", String.valueOf(1L))
.param("carId", String.valueOf(1L))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
CarResponseDto carResponseDto = objectMapper.readValue(response, CarResponseDto.class);
Assertions.assertEquals(1L, carResponseDto.getId());
Assertions.assertEquals(List.of(), carResponseDto.getDriverIdsNames());
Assertions.assertNull(carResponseDto.getMainDriverId());
}
@Test
void getAllDriversOfCar() throws Exception {
given(carDriverPairServiceMock.getAllDriversOfCar(3L)).willReturn(
List.of(driverDto, driverDto2));
String response = mockMvc.perform(put("/cardriver/alldrivers")
.param("carId", String.valueOf(3L))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
List<DriverDto> driverDtoListResponse =
List.of(objectMapper.readValue(response, DriverDto[].class));
Assertions.assertEquals(List.of(driverDto, driverDto2), driverDtoListResponse);
}
@Test
void setMainDriver() throws Exception {
given(carDriverPairServiceMock.setMainDriver(3L, 1L)).willReturn(carResponseDto3);
String response = mockMvc.perform(put("/cardriver/setmain")
.param("driverId", String.valueOf(1L))
.param("carId", String.valueOf(3L))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
CarResponseDto carResponseDto = objectMapper.readValue(response, CarResponseDto.class);
Assertions.assertEquals(1L, carResponseDto.getMainDriverId());
}
@Test
void removeMainDriver() throws Exception {
given(carDriverPairServiceMock.removeMainDriver(1L)).willReturn(carResponseDto);
String response = mockMvc.perform(put("/cardriver/removemain")
.param("driverId", String.valueOf(1L))
.param("carId", String.valueOf(1L))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
CarResponseDto carResponseDto = objectMapper.readValue(response, CarResponseDto.class);
Assertions.assertNull(carResponseDto.getMainDriverId());
}
}
\ No newline at end of file
package cz.muni.pa165.car.rest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@AutoConfigureMockMvc
class DriverManagerControllerItTest {
// @Autowired
// private MockMvc mockMvc;
//
// @Autowired
// private ObjectMapper objectMapper;
//
// @Autowired
// DriverManagerService driverManagerService;
//
// @Test
// void test() throws Exception {
// long id = 1L;
//
// Car car = driverManagerService.assignDriverToCar(id, id);
//
// String response = mockMvc.perform(put("/driver/assign").queryParam("driverId",
// String.valueOf(id)).queryParam("carId", String.valueOf(id)))
// .andExpect(status().isOk())
// .andReturn().getResponse().getContentAsString();
// Car carResponse = objectMapper.readValue(response, Car.class);
// Assertions.assertAll(
// () -> Assertions.assertEquals(car.getId(), carResponse.getId()),
// () -> Assertions.assertEquals(car.getDrivers(), carResponse.getDrivers())
// );
// }
}
package cz.muni.pa165.car.rest;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
@WebMvcTest()
class DriverManagerControllerUnitTest {
// @Autowired
// private MockMvc mockMvc;
//
// @MockBean
// private DriverManagerFacade mockDriverManagerFacade;
//
// @Autowired
// private ObjectMapper objectMapper;
//
// @Test
// void assignDriverValid() throws Exception {
// long id = 2L;
// var drivers = new HashSet<Driver>();
// Car car = new Car();
// car.setId(id);
// car.setDrivers(drivers);
//
// given(mockDriverManagerFacade.assignDriverToCar(anyLong(), anyLong())).willReturn(
// car);
// mockMvc.perform(put("/driver/assign").queryParam("driverId",
// String.valueOf(id)).queryParam("carId", String.valueOf(id)))
// .andExpect(status().isOk())
// .andExpect(jsonPath("$.id").value(id));
// }
//
// @Test
// void notExistingPath() throws Exception {
// mockMvc.perform(put("/invalidPath"))
// .andExpect(status().isNotFound());
// }
//
// @Test
// void assignInvalid() throws Exception {
// long id = -1L;
// var drivers = new HashSet<Driver>();
// Car car = new Car();
// car.setId(id);
// car.setDrivers(drivers);
//
// given(mockDriverManagerFacade.assignDriverToCar(anyLong(), anyLong())).willReturn(
// car);
// mockMvc.perform(put("/driver/assign").queryParam("driverId",
// "invalidNumber").queryParam("carId", "invalidNumber"))
// .andExpect(status().isBadRequest());
// }
}
package cz.muni.pa165.component.rest;
package cz.muni.pa165.car.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import cz.muni.pa165.component.service.ComponentService;
import cz.muni.pa165.car.data.repository.CarRepository;
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.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class ComponentInitControllerItTest {
class CarComponentPairServiceTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Autowired
ComponentService componentInitService;
@MockBean
private CarRepository carRepository;
@BeforeEach
void setUp() {
}
@Test
void addComponent() {
}
@Test
void removeComponent() {
}
@Test
void getAllComponentsOfCar() {
}
}
package cz.muni.pa165.car.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import cz.muni.pa165.car.data.repository.CarRepository;
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.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class CarDriverPairServiceTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private CarRepository carRepository;
@BeforeEach
void setUp() {
}
@Test
void assignDriverToCar() {
}
@Test
void unassignDriverFromCar() {
}
@Test
void getAllDriversOfCar() {
}
@Test
void setMainDriver() {
}
@Test
void removeMainDriver() {
}
}
package cz.muni.pa165.car.service;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.BDDMockito.given;
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.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.fasterxml.jackson.databind.ObjectMapper;
import cz.muni.pa165.car.data.model.Car;
import cz.muni.pa165.car.data.repository.CarRepository;
import cz.muni.pa165.car.restemplate.DbGetter;
import cz.muni.pa165.common_library.dtos.CarComponentResponseDto;
import cz.muni.pa165.common_library.dtos.CarRequestDto;
import cz.muni.pa165.common_library.dtos.CarResponseDto;
import cz.muni.pa165.common_library.dtos.DriverInsightDto;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
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()
class CarServiceTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private CarRepository carRepository;
@MockBean
private DbGetter dbGetter;
private static Car car1;
private static Car car;
private static CarResponseDto carResponseDto1;
private static CarRequestDto carRequestDto;
@BeforeEach
void initialize() {
car = Car.builder()
.id(null)
.components(Set.of(1L, 2L))
.drivers(Set.of(1L, 2L))
.mainDriverId(1L)
.build();
car1 = Car.builder()
.id(1L)
.components(Set.of(1L, 2L))
.drivers(Set.of(1L, 2L))
.mainDriverId(1L)
.build();
carResponseDto1 = CarResponseDto.builder()
.id(1L)
.componentIdsNames(List.of(1L, 2L))
.driverIdsNames(List.of(1L, 2L))
.mainDriverId(1L)
.build();
carRequestDto = CarRequestDto.builder()
.componentIds(List.of(1L, 2L))
.driverIds(List.of(1L, 2L))
.mainDriverId(1L)
.build();
}
@Test
void carAddTest() throws Exception {
given(carRepository.save(car)).willReturn(car1);
given(carRepository.findById(1L)).willReturn(
Optional.of(car1));
DriverInsightDto driverInsightDto =
new DriverInsightDto(1L, "name", "surname", "nationality", Map.of());
CarComponentResponseDto carComponentDto = CarComponentResponseDto.builder().build();
given(dbGetter.getDriverFromDb(anyLong())).willReturn(driverInsightDto);
given(dbGetter.getComponentFromDb(anyLong())).willReturn(carComponentDto);
String response = mockMvc.perform(post("/car/")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(carRequestDto)))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
var carResponse = objectMapper.readValue(response, CarResponseDto.class);
Assertions.assertAll(
() -> Assertions.assertEquals(carResponse.getId(), car1.getId()),
() -> Assertions.assertEquals(carResponse.getComponentIdsNames(),
car1.getComponents().stream().toList()),
() -> Assertions.assertEquals(carResponse.getDriverIdsNames(),
car1.getDrivers().stream().toList()),
() -> Assertions.assertEquals(carResponse.getMainDriverId(), car1.getMainDriverId())
);
}
@Test
void carGetAllTest() throws Exception {
given(carRepository.findAll()).willReturn(List.of(car1));
String response = mockMvc.perform(get("/car/all"))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
var carResponse = List.of(objectMapper.readValue(response, CarResponseDto[].class));
Assertions.assertAll(
() -> Assertions.assertEquals(carResponse.get(0).getId(), car1.getId()),
() -> Assertions.assertEquals(carResponse.get(0).getComponentIdsNames(),
car1.getComponents().stream().toList()),
() -> Assertions.assertEquals(carResponse.get(0).getDriverIdsNames(),
car1.getDrivers().stream().toList()),
() -> Assertions.assertEquals(carResponse.get(0).getMainDriverId(), car1.getMainDriverId())
);
}
@Test
void carGetByIdTest() throws Exception {
given(carRepository.findById(1L)).willReturn(Optional.of(car1));
String response = mockMvc.perform(get("/car/")
.param("carId", String.valueOf(1L))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
var carResponse = objectMapper.readValue(response, CarResponseDto.class);
Assertions.assertAll(
() -> Assertions.assertEquals(carResponse.getId(), car1.getId()),
() -> Assertions.assertEquals(carResponse.getComponentIdsNames(),
car1.getComponents().stream().toList()),
() -> Assertions.assertEquals(carResponse.getDriverIdsNames(),
car1.getDrivers().stream().toList()),
() -> Assertions.assertEquals(carResponse.getMainDriverId(), car1.getMainDriverId())
);
}
@Test
void carDeleteByIdTest() throws Exception {
given(carRepository.findById(1L)).willReturn(Optional.of(car1));
String response = mockMvc.perform(delete("/car/")
.param("carId", String.valueOf(1L))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
Assertions.assertEquals(response, "Car with id = " + 1L + " deleted!");
}
}
......@@ -23,10 +23,10 @@ public class RaceDto {
@Schema(description = "race information")
private RaceDto.RaceInfo raceInfo;
@Schema(description = "driver one", example = "{1, 1, Charles Leclerc}")
@Schema(description = "driver one")
private RaceDriverCarDto driverOne;
@Schema(description = "driver two", example = "{2, 2, Carlos Sainz}")
@Schema(description = "driver two")
private RaceDriverCarDto driverTwo;
/**
......@@ -39,7 +39,7 @@ public class RaceDto {
public static class RaceInfo {
@NotNull
@Schema(description = "race location", example = "Monaco")
@Schema(description = "race location", example = "MONACO")
private Location location;
@NotNull
......
......@@ -30,7 +30,6 @@ public class SeasonDto {
private int year;
@NotNull
@Schema(description = "season races", example = "[{1, STC Saudi Arabian GP Jeddah},"
+ " {2, Rolex Australian GP Melbourne}]")
@Schema(description = "season races")
List<RaceNameDto> races;
}