Skip to content
Snippets Groups Projects
Commit c5b53844 authored by Lukas Karsch's avatar Lukas Karsch
Browse files

#3 continued tests for garden with user. user added to repository query, service etc

parent a3f8f1f8
No related branches found
No related tags found
1 merge request!12#3 merge fully implemented garden branch into main
### Get all plants
GET http://localhost:8080/api/v1/plants
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsdWthcy5rYXJzY2hAZ214LmRlIiwiaWF0IjoxNjk5ODczMDA4LCJleHAiOjE2OTk5NTk0MDh9.iU9gkWinFla3__ksuwLmKosevRXrrYlDdSQCPhNHxbM
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsdWthcy5rYXJzY2hAZ214LmRlIiwiaWF0IjoxNzAwNDkyNTkyLCJleHAiOjE3MDA1Nzg5OTJ9.slDWTIZinUjuV9MRQMdgrM8mih8MP0lVbMsCLWr72c4
### Get garden entries
GET http://localhost:8080/api/v1/garden/
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsdWthcy5rYXJzY2hAZ214LmRlIiwiaWF0IjoxNzAwNDkyNTkyLCJleHAiOjE3MDA1Nzg5OTJ9.slDWTIZinUjuV9MRQMdgrM8mih8MP0lVbMsCLWr72c4
### Create account
POST http://localhost:8080/api/v1/auth/register
......@@ -19,5 +23,5 @@ content-type: application/json
{
"email": "lukas.karsch@gmx.de",
"password": "12345678"
"password": "myPassword123"
}
......@@ -9,6 +9,7 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import java.util.List;
......@@ -24,6 +25,7 @@ public class GrowBrosApplication {
}
@Bean
@Profile("!test")
public CommandLineRunner plants(PlantsService plantsService) {
return (args) -> {
List<String> json = List.of("""
......
package hdm.mi.growbros.controllers;
import hdm.mi.growbros.models.plant.Plant;
import hdm.mi.growbros.models.user.User;
import hdm.mi.growbros.service.GardenService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.List;
......@@ -11,18 +15,25 @@ import java.util.List;
@RequestMapping("/api/v1/garden")
@RequiredArgsConstructor
public class GardenController {
private static final Logger log = LoggerFactory.getLogger(GardenService.class);
private final GardenService gardenService;
@GetMapping("/")
public List<Plant> getPlantsInGarden(@RequestParam(value = "sort", required = false) String sort) {
//TODO: get the user by adding (Authentication authentication) as params
public List<Plant> getPlantsInGarden(
@RequestParam(value = "sort", required = false) String sort,
@AuthenticationPrincipal User user
) {
//TODO: pagination necessary?
return gardenService.getUserPlants(0L, sort);
return gardenService.getUserPlants(user, sort);
}
@PostMapping("/add/{plantId}")
public void addPlantToGarden(@PathVariable Long plantId) {
gardenService.addPlantToGarden(plantId, 0L);
public void addPlantToGarden(
@PathVariable Long plantId,
@AuthenticationPrincipal User user
) {
gardenService.addPlantToGarden(plantId, user);
}
@DeleteMapping("/remove/{entryId}")
......
package hdm.mi.growbros.models;
import hdm.mi.growbros.models.plant.Plant;
import hdm.mi.growbros.models.user.User;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
......@@ -26,8 +27,8 @@ public class GardenEntry {
@ManyToOne
private Plant plant;
// @ManyToOne(optional = false)
// private User user;
@ManyToOne(optional = false)
private User user;
@CreatedDate
private Date createdAt;
......
package hdm.mi.growbros.repositories;
import hdm.mi.growbros.models.GardenEntry;
import hdm.mi.growbros.models.user.User;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
......@@ -10,8 +12,11 @@ import java.util.List;
@Repository
public interface GardenRepository extends JpaRepository<GardenEntry, Long> {
List<GardenEntry> findByUser(User user, Sort sort);
@Query("""
SELECT ge FROM GardenEntry ge
WHERE ge.user = :user
ORDER BY
CASE
WHEN :week <= ge.plant.harvestWeekStart
......@@ -21,10 +26,11 @@ public interface GardenRepository extends JpaRepository<GardenEntry, Long> {
ge.plant.name
ASC
""")
List<GardenEntry> findAllByNearestHarvestWeek(@Param("week") int currentWeek);
List<GardenEntry> findAllByNearestHarvestWeek(@Param("user") User user, @Param("week") int currentWeek);
@Query("""
SELECT ge FROM GardenEntry ge
WHERE ge.user = :user
ORDER BY
CASE
WHEN :week <= ge.plant.plantWeekStart
......@@ -34,5 +40,5 @@ public interface GardenRepository extends JpaRepository<GardenEntry, Long> {
ge.plant.name
ASC
""")
List<GardenEntry> findAllByNearestPlantingWeek(@Param("week") int currentWeek);
List<GardenEntry> findAllByNearestPlantingWeek(@Param("user") User user, @Param("week") int currentWeek);
}
......@@ -3,6 +3,7 @@ package hdm.mi.growbros.service;
import hdm.mi.growbros.exceptions.PlantNotFoundException;
import hdm.mi.growbros.models.GardenEntry;
import hdm.mi.growbros.models.plant.Plant;
import hdm.mi.growbros.models.user.User;
import hdm.mi.growbros.repositories.GardenRepository;
import hdm.mi.growbros.repositories.PlantRepository;
import hdm.mi.growbros.util.DateTimeUtils;
......@@ -19,17 +20,17 @@ public class GardenService {
private final GardenRepository gardenRepository;
private final PlantRepository plantRepository;
public List<Plant> getUserPlants(Long userId, String sort) {
if (sort == null) return getAllPlantsOrderedByName();
public List<Plant> getUserPlants(User user, String sort) {
if (sort == null) return getAllPlantsOrderedByName(user);
return switch (sort) {
case "createdAt" -> getAllPlantsOrderedByCreatedDate();
case "plantDate" -> getAllPlantsOrderedByNextPossiblePlantDate();
case "harvestDate" -> getAllPlantsOrderedByNextPossibleHarvest();
default -> getAllPlantsOrderedByName();
case "createdAt" -> getAllPlantsOrderedByCreatedDate(user);
case "plantDate" -> getAllPlantsOrderedByNextPossiblePlantDate(user);
case "harvestDate" -> getAllPlantsOrderedByNextPossibleHarvest(user);
default -> getAllPlantsOrderedByName(user);
};
}
public void addPlantToGarden(Long plantId, Long userId) {
public void addPlantToGarden(Long plantId, User user) {
//get user
Plant plant = plantRepository.findById(plantId).orElseThrow(() -> new PlantNotFoundException(plantId));
GardenEntry gardenEntry = new GardenEntry();
......@@ -49,27 +50,27 @@ public class GardenService {
return deleted;
}
private List<Plant> getAllPlantsOrderedByName() {
private List<Plant> getAllPlantsOrderedByName(User user) {
return mapGardenEntriesToPlants(
gardenRepository.findAll(Sort.by("plant.name"))
gardenRepository.findByUser(user, Sort.by("plant.name"))
);
}
private List<Plant> getAllPlantsOrderedByCreatedDate() {
private List<Plant> getAllPlantsOrderedByCreatedDate(User user) {
return mapGardenEntriesToPlants(
gardenRepository.findAll(Sort.by("createdDate"))
gardenRepository.findByUser(user, Sort.by("createdDate"))
);
}
private List<Plant> getAllPlantsOrderedByNextPossiblePlantDate() {
private List<Plant> getAllPlantsOrderedByNextPossiblePlantDate(User user) {
return mapGardenEntriesToPlants(
gardenRepository.findAllByNearestPlantingWeek(DateTimeUtils.getCurrentWeekForToday())
gardenRepository.findAllByNearestPlantingWeek(user, DateTimeUtils.getCurrentWeekForToday())
);
}
private List<Plant> getAllPlantsOrderedByNextPossibleHarvest() {
private List<Plant> getAllPlantsOrderedByNextPossibleHarvest(User user) {
return mapGardenEntriesToPlants(
gardenRepository.findAllByNearestHarvestWeek(DateTimeUtils.getCurrentWeekForToday())
gardenRepository.findAllByNearestHarvestWeek(user, DateTimeUtils.getCurrentWeekForToday())
);
}
......
package hdm.mi.growbros.config;
import hdm.mi.growbros.models.user.User;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import java.util.Arrays;
@TestConfiguration
public class SpringSecurityTestConfig {
@Bean
@Primary
public UserDetailsService userDetailsService() {
User basicUser = User.builder()
.email("user@gmail.com")
.firstname("User")
.password("validPassword123!")
.build();
return new InMemoryUserDetailsManager(Arrays.asList(
basicUser
));
}
}
\ No newline at end of file
......@@ -2,10 +2,14 @@ package hdm.mi.growbros.repositories;
import hdm.mi.growbros.models.GardenEntry;
import hdm.mi.growbros.models.plant.Plant;
import org.junit.jupiter.api.BeforeAll;
import hdm.mi.growbros.models.user.Role;
import hdm.mi.growbros.models.user.User;
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.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
......@@ -13,15 +17,28 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
//TODO: Test for when the current week is in between plant/harvest start and end date
@SpringBootTest
//@SpringBootTest
@DataJpaTest
@ActiveProfiles("test")
class GardenRepositoryTest {
@Autowired
private GardenRepository underTest;
@Autowired
private TestEntityManager entityManager;
private static GardenEntry ge1, ge2, ge3;
private static User user;
@BeforeEach
public void setupEach(@Autowired GardenRepository underTest, @Autowired PlantRepository plantRepository) {
user = User.builder()
.email("user@gmail.com")
.role(Role.USER)
.password("safePassword123!")
.build();
entityManager.persist(user);
@BeforeAll
public static void setupAll(@Autowired GardenRepository underTest, @Autowired PlantRepository plantRepository) {
Plant p1 = Plant.builder()
.name("Early plant")
.plantWeekStart(1)
......@@ -29,6 +46,7 @@ class GardenRepositoryTest {
.harvestWeekStart(10)
.harvestWeekEnd(15)
.build();
entityManager.persist(p1);
Plant p2 = Plant.builder()
.name("Medium late plant")
.plantWeekStart(4)
......@@ -36,6 +54,7 @@ class GardenRepositoryTest {
.harvestWeekStart(18)
.harvestWeekEnd(20)
.build();
entityManager.persist(p2);
Plant p3 = Plant.builder()
.name("Late plant")
.plantWeekStart(10)
......@@ -43,9 +62,10 @@ class GardenRepositoryTest {
.harvestWeekStart(25)
.harvestWeekEnd(30)
.build();
ge1 = new GardenEntry(0L, p1, null);
ge2 = new GardenEntry(0L, p2, null);
ge3 = new GardenEntry(0L, p3, null);
entityManager.persist(p3);
ge1 = new GardenEntry(0L, p1, user, null);
ge2 = new GardenEntry(0L, p2, user, null);
ge3 = new GardenEntry(0L, p3, user, null);
plantRepository.saveAll(List.of(p1, p2, p3));
underTest.saveAll(List.of(ge1, ge2, ge3));
}
......@@ -53,7 +73,7 @@ class GardenRepositoryTest {
@Test
void testNearestHarvestWeek() {
//when
var result = underTest.findAllByNearestHarvestWeek(1);
var result = underTest.findAllByNearestHarvestWeek(user, 1);
//then
assertEquals(List.of(ge1, ge2, ge3), result);
......@@ -62,7 +82,7 @@ class GardenRepositoryTest {
@Test
void findNearestPlantingWeek() {
//when
var result = underTest.findAllByNearestPlantingWeek(1);
var result = underTest.findAllByNearestPlantingWeek(user, 1);
//then
assertEquals(List.of(ge1, ge2, ge3), result);
......
......@@ -5,3 +5,4 @@ spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.profiles.active=test
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment