Merge branch 'route_alternatives'
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
# Conflicts: # src/main/java/SuMoC/backend/user/models/User.java
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
package SuMoC.backend.Factories;
|
||||
|
||||
import SuMoC.backend.h3.H3Service;
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
@Component
|
||||
public class RegularTripDetectionDTOFactory {
|
||||
|
||||
private final H3Service h3Service;
|
||||
|
||||
private final Random random = new Random();
|
||||
|
||||
private final String h3_essen_schuetzenbahn = "8a1fa535568ffff";
|
||||
private final String h3_essen_hbf = "8a1fa535020ffff";
|
||||
private final String h3_essen_west = "8a1fa5356a5ffff";
|
||||
|
||||
public RegularTripDetectionDTOFactory(H3Service h3Service) {
|
||||
this.h3Service = h3Service;
|
||||
}
|
||||
|
||||
public List<RegularTripDetectionDTO> regularFromAtoBwithOverlappingAndPreferredTimeWindows() {
|
||||
List<RegularTripDetectionDTO> dtos = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < 5; i++) {
|
||||
var startDateTime = LocalDateTime.now().minusMinutes(20 * i).minusWeeks(i);
|
||||
var endDateTime = startDateTime.plusMinutes(15);
|
||||
|
||||
dtos.add(RegularTripDetectionDTO.builder()
|
||||
.tripId(i)
|
||||
.userId(1L)
|
||||
.startH3Cell(h3_essen_schuetzenbahn)
|
||||
.endH3Cell(h3_essen_hbf)
|
||||
.startTime(startDateTime.toInstant(ZoneOffset.UTC))
|
||||
.endTime(endDateTime.toInstant(ZoneOffset.UTC))
|
||||
.mainModality(Modality.CAR)
|
||||
.startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_schuetzenbahn))
|
||||
.endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_hbf))
|
||||
.build());
|
||||
|
||||
if (i == 0) {
|
||||
// Create double entry for i = 0 to test if detector correctly focusses on the most supported time window
|
||||
dtos.add(RegularTripDetectionDTO.builder()
|
||||
.tripId(400 + i)
|
||||
.userId(1L)
|
||||
.startH3Cell(h3_essen_schuetzenbahn)
|
||||
.endH3Cell(h3_essen_hbf)
|
||||
.startTime(startDateTime.plusWeeks(1).toInstant(ZoneOffset.UTC)) // overlapping time window
|
||||
.endTime(endDateTime.plusWeeks(1).toInstant(ZoneOffset.UTC))
|
||||
.mainModality(Modality.CAR)
|
||||
.startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_schuetzenbahn))
|
||||
.endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_hbf))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
return dtos;
|
||||
}
|
||||
|
||||
public List<RegularTripDetectionDTO> regularFromAtoB(int size) {
|
||||
List<RegularTripDetectionDTO> dtos = new ArrayList<>();
|
||||
for (int i = 0; i < size; i++) {
|
||||
var startDateTime = LocalDateTime.now().minusMinutes(30).minusWeeks(i);
|
||||
var endDateTime = startDateTime.plusMinutes(15);
|
||||
|
||||
dtos.add(RegularTripDetectionDTO.builder()
|
||||
.tripId(i)
|
||||
.userId(1L)
|
||||
.startH3Cell(h3_essen_schuetzenbahn)
|
||||
.endH3Cell(h3_essen_hbf)
|
||||
.startTime(startDateTime.toInstant(ZoneOffset.UTC))
|
||||
.endTime(endDateTime.toInstant(ZoneOffset.UTC))
|
||||
.mainModality(Modality.CAR)
|
||||
.startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_schuetzenbahn))
|
||||
.endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_hbf))
|
||||
.build());
|
||||
}
|
||||
|
||||
return dtos;
|
||||
}
|
||||
|
||||
public List<RegularTripDetectionDTO> regularFromAtoBwithNeighbourCells(int size) {
|
||||
List<RegularTripDetectionDTO> dtos = new ArrayList<>();
|
||||
for (int i = 0; i < size; i++) {
|
||||
var startDateTime = LocalDateTime.now().minusMinutes(30).minusWeeks(i);
|
||||
var endDateTime = startDateTime.plusMinutes(15);
|
||||
|
||||
String startCell = h3Service.getRoutePatternNeighbors(h3_essen_schuetzenbahn).get(random.nextInt(6)); // h3 always has 6 neighbors
|
||||
if (i == 0) {
|
||||
startCell = h3_essen_schuetzenbahn; // one time use the original cell - simulates some noise
|
||||
}
|
||||
|
||||
String endCell = h3Service.getRoutePatternNeighbors(h3_essen_hbf).get(random.nextInt(6));
|
||||
if (i == 0) {
|
||||
endCell = h3_essen_hbf; // one time use the original cell - simulates some noise
|
||||
}
|
||||
|
||||
dtos.add(RegularTripDetectionDTO.builder()
|
||||
.tripId(200 + i)
|
||||
.userId(1L)
|
||||
.startH3Cell(startCell)
|
||||
.endH3Cell(endCell)
|
||||
.startTime(startDateTime.toInstant(ZoneOffset.UTC))
|
||||
.endTime(endDateTime.toInstant(ZoneOffset.UTC))
|
||||
.mainModality(Modality.CAR)
|
||||
.startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(startCell))
|
||||
.endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(endCell))
|
||||
.build());
|
||||
}
|
||||
|
||||
return dtos;
|
||||
}
|
||||
|
||||
public List<RegularTripDetectionDTO> nonRegularFromAtoC() {
|
||||
List<RegularTripDetectionDTO> dtos = new ArrayList<>();
|
||||
for (int i = 0; i < 5; i++) {
|
||||
var startDateTime = LocalDateTime.now().minusMinutes(30).minusDays(i);
|
||||
var endDateTime = startDateTime.plusMinutes(15);
|
||||
|
||||
dtos.add(RegularTripDetectionDTO.builder()
|
||||
.tripId(100 + i)
|
||||
.userId(1L)
|
||||
.startH3Cell(h3_essen_schuetzenbahn)
|
||||
.endH3Cell(h3_essen_west)
|
||||
.startTime(startDateTime.toInstant(ZoneOffset.UTC))
|
||||
.endTime(endDateTime.toInstant(ZoneOffset.UTC))
|
||||
.mainModality(Modality.CAR)
|
||||
.startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_schuetzenbahn))
|
||||
.endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_west))
|
||||
.build());
|
||||
}
|
||||
|
||||
return dtos;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package SuMoC.backend.Factories;
|
||||
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.trip.models.Trip;
|
||||
import SuMoC.backend.trip.models.TripSegment;
|
||||
import SuMoC.backend.user.models.User;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class TripTestFactory {
|
||||
|
||||
/**
|
||||
* Returns structurally valid trip, position data is arbitrary.
|
||||
*/
|
||||
public static Trip getValidTrip(Instant start, Instant end, User user) {
|
||||
Trip trip = new Trip();
|
||||
trip.setUser(user);
|
||||
trip.setStartTime(start);
|
||||
trip.setEndTime(end);
|
||||
trip.setStartPlace("Start Place");
|
||||
trip.setStartLatitude(40.7128);
|
||||
trip.setStartLongitude(-74.0060);
|
||||
trip.setStartH3Cell("8928308280fffff");
|
||||
trip.setEndPlace("End Place");
|
||||
trip.setEndLatitude(34.0522);
|
||||
trip.setEndLongitude(-118.2437);
|
||||
trip.setEndH3Cell("8928308280bffff");
|
||||
trip.setCo2Emissions(10.5);
|
||||
trip.setMobilityScore(50);
|
||||
trip.setCost(50f);
|
||||
trip.setTripSegments(new HashSet<TripSegment>());
|
||||
trip.setMainModality(Modality.CAR);
|
||||
trip.setInvalidated(false);
|
||||
return trip;
|
||||
}
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.notification.enums.NotificationStatus;
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import SuMoC.backend.trend.dto.TrendDetectionDTO;
|
||||
import SuMoC.backend.trend.enums.DeltaType;
|
||||
import SuMoC.backend.trend.enums.StatAttribute;
|
||||
import SuMoC.backend.trend.enums.TrendTimespan;
|
||||
import SuMoC.backend.trend.enums.TrendType;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class NotificationSchedulerServiceTest {
|
||||
|
||||
@Mock
|
||||
private NotificationRepository notificationRepository;
|
||||
|
||||
@Mock
|
||||
private EntityManager entityManager;
|
||||
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
private NotificationSchedulerService notificationSchedulerService;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<List<Notification>> notificationListCaptor;
|
||||
|
||||
private User mockUser;
|
||||
private LocalTime testTime;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
objectMapper = new ObjectMapper();
|
||||
notificationSchedulerService = new NotificationSchedulerService(objectMapper, notificationRepository, entityManager);
|
||||
mockUser = new User("privateName", "publicName", "test@example.com", "password");
|
||||
mockUser.setId(1L);
|
||||
testTime = LocalTime.of(9, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void scheduleAll_WithTrendDetectionDTO_SerializesAndPersistsSuccessfully() {
|
||||
// Arrange
|
||||
TrendDetectionDTO trendDetectionDTO = new TrendDetectionDTO(
|
||||
1L,
|
||||
TrendTimespan.WEEKLY,
|
||||
TrendType.INCREASING,
|
||||
StatAttribute.CAR_DISTANCE,
|
||||
DeltaType.ABSOLUTE,
|
||||
25.5
|
||||
);
|
||||
|
||||
List<? extends SuMoC.backend.notification.interfaces.Notifieable> dataBodies = List.of(trendDetectionDTO);
|
||||
|
||||
// Mock EntityManager to return a proxy
|
||||
when(entityManager.getReference(eq(User.class), eq(1L))).thenReturn(mockUser);
|
||||
|
||||
// Act
|
||||
notificationSchedulerService.scheduleAll(
|
||||
(List<SuMoC.backend.notification.interfaces.Notifieable>) dataBodies,
|
||||
NotificationType.TREND,
|
||||
testTime
|
||||
);
|
||||
|
||||
// Assert
|
||||
verify(notificationRepository, times(1)).saveAll(notificationListCaptor.capture());
|
||||
List<Notification> savedNotifications = notificationListCaptor.getValue();
|
||||
|
||||
assertEquals(1, savedNotifications.size());
|
||||
Notification notification = savedNotifications.getFirst();
|
||||
|
||||
// Verify notification properties
|
||||
assertEquals(mockUser, notification.getUser());
|
||||
assertEquals(NotificationType.TREND, notification.getType());
|
||||
assertEquals(NotificationStatus.PENDING, notification.getStatus());
|
||||
assertEquals(testTime, notification.getEarliestTimeOfDayToSend());
|
||||
assertEquals(0, notification.getFailedSendAttempts());
|
||||
assertNotNull(notification.getCreatedAt());
|
||||
|
||||
// Verify that the data was serialized correctly
|
||||
assertNotNull(notification.getData());
|
||||
assertTrue(notification.getData().contains("userId"));
|
||||
assertTrue(notification.getData().contains("WEEKLY"));
|
||||
assertTrue(notification.getData().contains("INCREASING"));
|
||||
assertTrue(notification.getData().contains("CAR_DISTANCE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void scheduleAll_WithTrendDetectionDTO_DataCanBeDeserialized() throws Exception {
|
||||
// Arrange
|
||||
TrendDetectionDTO originalDTO = new TrendDetectionDTO(
|
||||
1L,
|
||||
TrendTimespan.WEEKLY,
|
||||
TrendType.DECREASING,
|
||||
StatAttribute.CAR_DISTANCE,
|
||||
DeltaType.PERCENTAGE,
|
||||
15.75
|
||||
);
|
||||
|
||||
List<? extends SuMoC.backend.notification.interfaces.Notifieable> dataBodies = List.of(originalDTO);
|
||||
when(entityManager.getReference(eq(User.class), eq(1L))).thenReturn(mockUser);
|
||||
|
||||
// Act
|
||||
notificationSchedulerService.scheduleAll(
|
||||
(List<SuMoC.backend.notification.interfaces.Notifieable>) dataBodies,
|
||||
NotificationType.TREND,
|
||||
testTime
|
||||
);
|
||||
|
||||
// Capture the saved notification
|
||||
verify(notificationRepository).saveAll(notificationListCaptor.capture());
|
||||
Notification savedNotification = notificationListCaptor.getValue().getFirst();
|
||||
|
||||
// Assert - deserialize and verify the data
|
||||
TrendDetectionDTO deserializedDTO = objectMapper.readValue(
|
||||
savedNotification.getData(),
|
||||
TrendDetectionDTO.class
|
||||
);
|
||||
|
||||
assertEquals(originalDTO.getUserId(), deserializedDTO.getUserId());
|
||||
assertEquals(originalDTO.getTimespan(), deserializedDTO.getTimespan());
|
||||
assertEquals(originalDTO.getType(), deserializedDTO.getType());
|
||||
assertEquals(originalDTO.getAttribute(), deserializedDTO.getAttribute());
|
||||
assertEquals(originalDTO.getDeltaType(), deserializedDTO.getDeltaType());
|
||||
assertEquals(originalDTO.getChangeValue(), deserializedDTO.getChangeValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void scheduleAll_WithMultipleTrendDetectionDTOs_SerializesAll() {
|
||||
// Arrange
|
||||
TrendDetectionDTO dto1 = new TrendDetectionDTO(
|
||||
1L,
|
||||
TrendTimespan.WEEKLY,
|
||||
TrendType.INCREASING,
|
||||
StatAttribute.CAR_DISTANCE,
|
||||
DeltaType.ABSOLUTE,
|
||||
10.0
|
||||
);
|
||||
|
||||
TrendDetectionDTO dto2 = new TrendDetectionDTO(
|
||||
2L,
|
||||
TrendTimespan.WEEKLY,
|
||||
TrendType.DECREASING,
|
||||
StatAttribute.CAR_DISTANCE,
|
||||
DeltaType.PERCENTAGE,
|
||||
5.0
|
||||
);
|
||||
|
||||
List<? extends SuMoC.backend.notification.interfaces.Notifieable> dataBodies = List.of(dto1, dto2);
|
||||
|
||||
// Mock EntityManager to return proxies
|
||||
User mockUser2 = new User("privateName2", "publicName2", "test2@example.com", "password");
|
||||
mockUser2.setId(2L);
|
||||
|
||||
when(entityManager.getReference(eq(User.class), eq(1L))).thenReturn(mockUser);
|
||||
when(entityManager.getReference(eq(User.class), eq(2L))).thenReturn(mockUser2);
|
||||
|
||||
// Act
|
||||
notificationSchedulerService.scheduleAll(
|
||||
(List<SuMoC.backend.notification.interfaces.Notifieable>) dataBodies,
|
||||
NotificationType.TREND,
|
||||
testTime
|
||||
);
|
||||
|
||||
// Assert
|
||||
verify(notificationRepository, times(1)).saveAll(notificationListCaptor.capture());
|
||||
List<Notification> savedNotifications = notificationListCaptor.getValue();
|
||||
|
||||
assertEquals(2, savedNotifications.size());
|
||||
assertEquals(mockUser, savedNotifications.get(0).getUser());
|
||||
assertEquals(mockUser2, savedNotifications.get(1).getUser());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void scheduleAll_WithTrendDetectionDTO_SerializationException_ThrowsRuntimeException() {
|
||||
// Arrange
|
||||
TrendDetectionDTO dto = new TrendDetectionDTO(
|
||||
1L,
|
||||
TrendTimespan.WEEKLY,
|
||||
TrendType.INCREASING,
|
||||
StatAttribute.CAR_DISTANCE,
|
||||
DeltaType.ABSOLUTE,
|
||||
25.5
|
||||
);
|
||||
|
||||
List<? extends SuMoC.backend.notification.interfaces.Notifieable> dataBodies = List.of(dto);
|
||||
|
||||
when(entityManager.getReference(eq(User.class), eq(1L))).thenReturn(mockUser);
|
||||
|
||||
// Act & Assert
|
||||
// The service should handle serialization correctly and not throw exceptions
|
||||
// for valid DTOs
|
||||
assertDoesNotThrow(() ->
|
||||
notificationSchedulerService.scheduleAll(
|
||||
(List<SuMoC.backend.notification.interfaces.Notifieable>) dataBodies,
|
||||
NotificationType.TREND,
|
||||
testTime
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void scheduleAll_VerifyNotificationStatusIsInitiallyPending() {
|
||||
// Arrange
|
||||
TrendDetectionDTO trendDetectionDTO = TrendDetectionDTO.mockTrendDetectionDTO();
|
||||
trendDetectionDTO.setUserId(1L);
|
||||
|
||||
List<? extends SuMoC.backend.notification.interfaces.Notifieable> dataBodies = List.of(trendDetectionDTO);
|
||||
when(entityManager.getReference(eq(User.class), eq(1L))).thenReturn(mockUser);
|
||||
|
||||
// Act
|
||||
notificationSchedulerService.scheduleAll(
|
||||
(List<SuMoC.backend.notification.interfaces.Notifieable>) dataBodies,
|
||||
NotificationType.TREND,
|
||||
testTime
|
||||
);
|
||||
|
||||
// Assert
|
||||
verify(notificationRepository).saveAll(notificationListCaptor.capture());
|
||||
Notification notification = notificationListCaptor.getValue().getFirst();
|
||||
|
||||
assertEquals(NotificationStatus.PENDING, notification.getStatus());
|
||||
assertEquals(0, notification.getFailedSendAttempts());
|
||||
}
|
||||
}
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package SuMoC.backend.regulartrip.detectionapproaches;
|
||||
|
||||
import SuMoC.backend.Factories.RegularTripDetectionDTOFactory;
|
||||
import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SpringBootTest(properties = {
|
||||
"geocoding.provider=carta",
|
||||
"geocoding.carta.base-url=https://mobydex.locoslab.com/carta"
|
||||
})
|
||||
public class IterativeClustererTest {
|
||||
|
||||
@Mock(lenient = true)
|
||||
private RegularTripDetectionProperties properties;
|
||||
|
||||
@InjectMocks
|
||||
private IterativeClusterer iterativeClusterer;
|
||||
|
||||
@Autowired
|
||||
private RegularTripDetectionDTOFactory regularTripDetectionDTOFactory;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(properties.getDetectionTimeWindowDays()).thenReturn(30);
|
||||
when(properties.getTimeWindowSeconds()).thenReturn(90 * 60);
|
||||
when(properties.getMinTripsForRegularity()).thenReturn(2);
|
||||
when(properties.getIterativeShuffleAmounts()).thenReturn(5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Easiest case: We only have regular trips from cell a to cell b.
|
||||
* But also non regular from a to c, b to d, which should not be included in the result.
|
||||
*/
|
||||
@Test
|
||||
public void detectFromSameCellToSameCell_Success() {
|
||||
// Arrange
|
||||
var dtos = regularTripDetectionDTOFactory.regularFromAtoB(5);
|
||||
dtos.addAll(regularTripDetectionDTOFactory.nonRegularFromAtoC());
|
||||
|
||||
// Act
|
||||
var result = iterativeClusterer.detectRegularTrips(dtos);
|
||||
|
||||
// Assert
|
||||
assert (result.size() == 1);
|
||||
assert (result.get(0).getSupportingTrips().size() == 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Regaulr Trips from cell a to cell b, but we have two overlapping time windows.
|
||||
* E.g. when window is 90 minutes, we have trips at 08:00 and 08:30 and 09:00 and 09:30.
|
||||
* The desired behavior is to still only detect one regular trip where the time window is the one that covers as many trips as possible.
|
||||
*/
|
||||
@Test
|
||||
public void detectFromSameCellToSameCellOverlapping_Success() {
|
||||
// Arrange
|
||||
var dtos = regularTripDetectionDTOFactory.regularFromAtoBwithOverlappingAndPreferredTimeWindows();
|
||||
dtos.addAll(regularTripDetectionDTOFactory.nonRegularFromAtoC());
|
||||
|
||||
// Act
|
||||
var result = iterativeClusterer.detectRegularTrips(dtos);
|
||||
|
||||
// Assert
|
||||
assert (result.size() == 1);
|
||||
assert (result.get(0).getSupportingTrips().size() == 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* We have single non-regular trips from a to b, a+1 to b+1, a-1 to b-1, but together they form a regular trip from neighboring cells.
|
||||
*/
|
||||
@Test
|
||||
public void detectFromNeighboringCells_Success() {
|
||||
// Arrange
|
||||
var dtos = regularTripDetectionDTOFactory.regularFromAtoBwithNeighbourCells(5);
|
||||
dtos.addAll(regularTripDetectionDTOFactory.nonRegularFromAtoC());
|
||||
|
||||
// Act
|
||||
var result = iterativeClusterer.detectRegularTrips(dtos);
|
||||
|
||||
// Assert
|
||||
assert (result.size() == 1);
|
||||
assert (result.get(0).getSupportingTrips().size() == 5);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package SuMoC.backend.trend.services;
|
||||
|
||||
import SuMoC.backend.trend.TrendDetection;
|
||||
import SuMoC.backend.trend.WeeklyMobilityStatsRepository;
|
||||
import SuMoC.backend.trend.config.TrendDetectionProperties;
|
||||
import SuMoC.backend.trend.config.TrendProperties;
|
||||
import SuMoC.backend.trend.dto.TrendDetectionDTO;
|
||||
import SuMoC.backend.trend.enums.DeltaType;
|
||||
import SuMoC.backend.trend.enums.StatAttribute;
|
||||
import SuMoC.backend.trend.enums.TrendTimespan;
|
||||
@@ -28,7 +28,7 @@ public class TrendDetectorServiceTest {
|
||||
private WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
|
||||
|
||||
@Mock
|
||||
private TrendDetectionProperties trendDetectionProperties;
|
||||
private TrendProperties trendProperties;
|
||||
|
||||
@InjectMocks
|
||||
private TrendDetectorService trendDetectorService;
|
||||
@@ -56,8 +56,8 @@ public class TrendDetectorServiceTest {
|
||||
int weekNumber = 2;
|
||||
|
||||
// Set threshold values for this test
|
||||
when(trendDetectionProperties.getPositiveThreshold()).thenReturn(25.0);
|
||||
when(trendDetectionProperties.getNegativeThreshold()).thenReturn(-25.0);
|
||||
when(trendProperties.getPositiveThreshold()).thenReturn(25.0);
|
||||
when(trendProperties.getNegativeThreshold()).thenReturn(-25.0);
|
||||
|
||||
// User 1: Significant increase (100m -> 400m = +300%)
|
||||
WeeklyMobilityStats user1Previous = createWeeklyStats(user1, year, weekNumber - 1, 100L);
|
||||
@@ -77,14 +77,14 @@ public class TrendDetectorServiceTest {
|
||||
.thenReturn(List.of(user1Current, user2Current, user3Current));
|
||||
|
||||
// Act
|
||||
List<TrendDetection> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
|
||||
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
|
||||
|
||||
// Assert
|
||||
assertEquals(2, detectedTrends.size(), "Should detect 2 trends (1 increase, 1 decrease)");
|
||||
|
||||
// Verify increasing trend for user1
|
||||
TrendDetection user1Trend = detectedTrends.stream()
|
||||
.filter(t -> t.getUser().getId().equals(user1.getId()))
|
||||
TrendDetectionDTO user1Trend = detectedTrends.stream()
|
||||
.filter(t -> t.getUserId().equals(user1.getId()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
assertNotNull(user1Trend, "User 1 should have a detected trend");
|
||||
@@ -95,8 +95,8 @@ public class TrendDetectorServiceTest {
|
||||
assertEquals(300.0, user1Trend.getChangeValue(), 0.01);
|
||||
|
||||
// Verify decreasing trend for user2
|
||||
TrendDetection user2Trend = detectedTrends.stream()
|
||||
.filter(t -> t.getUser().getId().equals(user2.getId()))
|
||||
TrendDetectionDTO user2Trend = detectedTrends.stream()
|
||||
.filter(t -> t.getUserId().equals(user2.getId()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
assertNotNull(user2Trend, "User 2 should have a detected trend");
|
||||
@@ -108,7 +108,7 @@ public class TrendDetectorServiceTest {
|
||||
|
||||
// Verify no trend detected for user3
|
||||
boolean user3HasTrend = detectedTrends.stream()
|
||||
.anyMatch(t -> t.getUser().getId().equals(user3.getId()));
|
||||
.anyMatch(t -> t.getUserId().equals(user3.getId()));
|
||||
assertFalse(user3HasTrend, "User 3 should not have a detected trend (change below threshold)");
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ public class TrendDetectorServiceTest {
|
||||
|
||||
// Act & Assert - should not throw any exception
|
||||
assertDoesNotThrow(() -> {
|
||||
List<TrendDetection> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
|
||||
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
|
||||
assertEquals(0, detectedTrends.size(), "Should not detect any trends when matching data is missing");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package SuMoC.backend.trip;
|
||||
|
||||
import SuMoC.backend.Factories.TripTestFactory;
|
||||
import SuMoC.backend.Factories.UserTestFactory;
|
||||
import SuMoC.backend.common.converter.DayOfWeekConverter;
|
||||
import SuMoC.backend.trip.models.Trip;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
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.test.context.TestPropertySource;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@DataJpaTest
|
||||
@TestPropertySource(properties = {
|
||||
"spring.jpa.hibernate.ddl-auto=create-drop",
|
||||
"spring.datasource.url=jdbc:h2:mem:testdb"
|
||||
})
|
||||
public class TripRepositoryTest {
|
||||
|
||||
@Autowired
|
||||
private TripRepository tripRepository;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Test
|
||||
void testDayOfWeekConverterAppliedInQuery() {
|
||||
// Create a user
|
||||
User user = UserTestFactory.validUser();
|
||||
userRepository.save(user);
|
||||
|
||||
// Create trips on different days of the week
|
||||
// 2025-01-13 is a Monday
|
||||
Trip mondayTrip = TripTestFactory.getValidTrip(Instant.parse("2025-01-13T10:00:00Z"), Instant.parse("2025-01-13T11:00:00Z"), user);
|
||||
tripRepository.save(mondayTrip);
|
||||
|
||||
// 2025-01-19 is a Sunday
|
||||
Trip sundayTrip = TripTestFactory.getValidTrip(Instant.parse("2025-01-19T10:00:00Z"), Instant.parse("2025-01-19T11:00:00Z"), user);
|
||||
tripRepository.save(sundayTrip);
|
||||
|
||||
// Query for trips on Monday
|
||||
List<Trip> mondayTrips = tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(
|
||||
Instant.parse("2025-01-01T00:00:00Z"),
|
||||
Modality.CAR,
|
||||
DayOfWeek.MONDAY
|
||||
);
|
||||
|
||||
// Verify only Monday trip is returned
|
||||
assertEquals(1, mondayTrips.size());
|
||||
assertEquals(mondayTrip.getId(), mondayTrips.get(0).getId());
|
||||
|
||||
// Query for trips on Sunday
|
||||
List<Trip> sundayTrips = tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(
|
||||
Instant.parse("2025-01-01T00:00:00Z"),
|
||||
Modality.CAR,
|
||||
DayOfWeek.SUNDAY
|
||||
);
|
||||
|
||||
// Verify only Tuesday trip is returned
|
||||
assertEquals(1, sundayTrips.size());
|
||||
assertEquals(sundayTrip.getId(), sundayTrips.get(0).getId());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user