implement trend detection logic
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
- for now aimed to detect weekly trends in car distances, easily extendable to all other attributes of the statsm model - including test
This commit is contained in:
@@ -0,0 +1,165 @@
|
||||
package SuMoC.backend.trenddetection.services;
|
||||
|
||||
import SuMoC.backend.trenddetection.TrendDetection;
|
||||
import SuMoC.backend.trenddetection.WeeklyMobilityStatsRepository;
|
||||
import SuMoC.backend.trenddetection.config.TrendDetectionProperties;
|
||||
import SuMoC.backend.trenddetection.enums.DeltaType;
|
||||
import SuMoC.backend.trenddetection.enums.StatAttribute;
|
||||
import SuMoC.backend.trenddetection.enums.TrendTimespan;
|
||||
import SuMoC.backend.trenddetection.enums.TrendType;
|
||||
import SuMoC.backend.trenddetection.models.WeeklyMobilityStats;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class TrendDetectorServiceTest {
|
||||
|
||||
@Mock
|
||||
private WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
|
||||
|
||||
@Mock
|
||||
private TrendDetectionProperties trendDetectionProperties;
|
||||
|
||||
@InjectMocks
|
||||
private TrendDetectorService trendDetectorService;
|
||||
|
||||
private User user1;
|
||||
private User user2;
|
||||
private User user3;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
user1 = new User("Private1", "Public1", "user1@example.com", "pass1");
|
||||
user1.setId(1L);
|
||||
|
||||
user2 = new User("Private2", "Public2", "user2@example.com", "pass2");
|
||||
user2.setId(2L);
|
||||
|
||||
user3 = new User("Private3", "Public3", "user3@example.com", "pass3");
|
||||
user3.setId(3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void detectWeeklyTrends_WithSignificantChanges_DetectsTrends() {
|
||||
// Arrange
|
||||
int year = 2026;
|
||||
int weekNumber = 2;
|
||||
|
||||
// Set threshold values for this test
|
||||
when(trendDetectionProperties.getPositiveThreshold()).thenReturn(25.0);
|
||||
when(trendDetectionProperties.getNegativeThreshold()).thenReturn(-25.0);
|
||||
|
||||
// User 1: Significant increase (100m -> 400m = +300%)
|
||||
WeeklyMobilityStats user1Previous = createWeeklyStats(user1, year, weekNumber - 1, 100L);
|
||||
WeeklyMobilityStats user1Current = createWeeklyStats(user1, year, weekNumber, 400L);
|
||||
|
||||
// User 2: Significant decrease (1000m -> 200m = -80%)
|
||||
WeeklyMobilityStats user2Previous = createWeeklyStats(user2, year, weekNumber - 1, 1000L);
|
||||
WeeklyMobilityStats user2Current = createWeeklyStats(user2, year, weekNumber, 200L);
|
||||
|
||||
// User 3: No significant change (500m -> 550m = +10%)
|
||||
WeeklyMobilityStats user3Previous = createWeeklyStats(user3, year, weekNumber - 1, 500L);
|
||||
WeeklyMobilityStats user3Current = createWeeklyStats(user3, year, weekNumber, 550L);
|
||||
|
||||
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1))
|
||||
.thenReturn(List.of(user1Previous, user2Previous, user3Previous));
|
||||
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber))
|
||||
.thenReturn(List.of(user1Current, user2Current, user3Current));
|
||||
|
||||
// Act
|
||||
List<TrendDetection> 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.getUserId().equals(user1.getId()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
assertNotNull(user1Trend, "User 1 should have a detected trend");
|
||||
assertEquals(TrendType.INCREASING, user1Trend.getType());
|
||||
assertEquals(StatAttribute.CAR_DISTANCE, user1Trend.getAttribute());
|
||||
assertEquals(TrendTimespan.WEEKLY, user1Trend.getTimespan());
|
||||
assertEquals(DeltaType.PERCENTAGE, user1Trend.getDeltaType());
|
||||
assertEquals(300.0, user1Trend.getChangeValue(), 0.01);
|
||||
|
||||
// Verify decreasing trend for user2
|
||||
TrendDetection user2Trend = detectedTrends.stream()
|
||||
.filter(t -> t.getUserId().equals(user2.getId()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
assertNotNull(user2Trend, "User 2 should have a detected trend");
|
||||
assertEquals(TrendType.DECREASING, user2Trend.getType());
|
||||
assertEquals(StatAttribute.CAR_DISTANCE, user2Trend.getAttribute());
|
||||
assertEquals(TrendTimespan.WEEKLY, user2Trend.getTimespan());
|
||||
assertEquals(DeltaType.PERCENTAGE, user2Trend.getDeltaType());
|
||||
assertEquals(-80.0, user2Trend.getChangeValue(), 0.01);
|
||||
|
||||
// Verify no trend detected for user3
|
||||
boolean user3HasTrend = detectedTrends.stream()
|
||||
.anyMatch(t -> t.getUserId().equals(user3.getId()));
|
||||
assertFalse(user3HasTrend, "User 3 should not have a detected trend (change below threshold)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void detectWeeklyTrends_WithMissingData_HandlesGracefully() {
|
||||
// Arrange
|
||||
int year = 2026;
|
||||
int weekNumber = 2;
|
||||
|
||||
// User 1: Has current week data but no previous week data
|
||||
WeeklyMobilityStats user1Current = createWeeklyStats(user1, year, weekNumber, 500L);
|
||||
|
||||
// User 2: Has previous week data but no current week data
|
||||
WeeklyMobilityStats user2Previous = createWeeklyStats(user2, year, weekNumber - 1, 800L);
|
||||
|
||||
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1))
|
||||
.thenReturn(List.of(user2Previous));
|
||||
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber))
|
||||
.thenReturn(List.of(user1Current));
|
||||
|
||||
// Act & Assert - should not throw any exception
|
||||
assertDoesNotThrow(() -> {
|
||||
List<TrendDetection> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
|
||||
assertEquals(0, detectedTrends.size(), "Should not detect any trends when matching data is missing");
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to create WeeklyMobilityStats with specified car distance
|
||||
*/
|
||||
private WeeklyMobilityStats createWeeklyStats(User user, int year, int weekNumber, Long carDistance) {
|
||||
return WeeklyMobilityStats.builder()
|
||||
.user(user)
|
||||
.year(year)
|
||||
.weekNumber(weekNumber)
|
||||
.totalDistance(carDistance.doubleValue())
|
||||
.tripCount(10)
|
||||
.sumMobilityScore(50.0)
|
||||
.averageMobilityScore(5.0)
|
||||
.sumMetersTraveled(carDistance)
|
||||
.sumMetersWalkingAndCycling(0L)
|
||||
.sumMetersPublicTransport(0L)
|
||||
.sumMetersWalking(0L)
|
||||
.sumMetersBicycle(0L)
|
||||
.sumMetersEscooter(0L)
|
||||
.sumMetersBus(0L)
|
||||
.sumMetersTram(0L)
|
||||
.sumMetersTrain(0L)
|
||||
.sumMetersCar(carDistance)
|
||||
.sumMetersMotorcycle(0L)
|
||||
.sumMetersTaxi(0L)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ public class UserServiceTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
userRepository.deleteAll();
|
||||
sender = userRepository.save(uniqueUser(1));
|
||||
differentUser = userRepository.save(uniqueUser(2));
|
||||
}
|
||||
@@ -67,7 +68,7 @@ public class UserServiceTest {
|
||||
assertEquals(differentUser.getPublicName(), publicSetting.getDisplayName());
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@@ -86,7 +87,6 @@ public class UserServiceTest {
|
||||
assertTrue(userRepository.findById(differentUser.getId()).isPresent());
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -101,14 +101,14 @@ public class UserServiceTest {
|
||||
|
||||
// Check if user can change his own password
|
||||
|
||||
// Too short password
|
||||
assertThrows(RuntimeException.class, () -> userService.setPassword(sender.getId(), "test"));
|
||||
// TODO: check why this assertion fails (most likely because of password encoding internals)
|
||||
// assertTrue(passwordEncoder.matches("password1", userRepository.findById(sender.getId()).get().getPassword()));
|
||||
// Too short password
|
||||
assertThrows(RuntimeException.class, () -> userService.setPassword(sender.getId(), "test"));
|
||||
// TODO: check why this assertion fails (most likely because of password encoding internals)
|
||||
// assertTrue(passwordEncoder.matches("password1", userRepository.findById(sender.getId()).get().getPassword()));
|
||||
|
||||
// Valid password
|
||||
userService.setPassword(sender.getId(), newPassword);
|
||||
assertTrue(passwordEncoder.matches(newPassword, userRepository.findById(sender.getId()).get().getPassword()));
|
||||
// Valid password
|
||||
userService.setPassword(sender.getId(), newPassword);
|
||||
assertTrue(passwordEncoder.matches(newPassword, userRepository.findById(sender.getId()).get().getPassword()));
|
||||
}
|
||||
|
||||
|
||||
@@ -125,17 +125,17 @@ public class UserServiceTest {
|
||||
|
||||
// Check if user can change his own email
|
||||
|
||||
// Other user's email
|
||||
assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), differentUser.getEmail()));
|
||||
assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
|
||||
// Other user's email
|
||||
assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), differentUser.getEmail()));
|
||||
assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
|
||||
|
||||
// Invalid email format
|
||||
assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), invalidEmail));
|
||||
assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
|
||||
// Invalid email format
|
||||
assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), invalidEmail));
|
||||
assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
|
||||
|
||||
// Valid email
|
||||
userService.setEmail(sender.getId(), newEmail);
|
||||
assertEquals(newEmail, userRepository.findById(sender.getId()).get().getEmail());
|
||||
// Valid email
|
||||
userService.setEmail(sender.getId(), newEmail);
|
||||
assertEquals(newEmail, userRepository.findById(sender.getId()).get().getEmail());
|
||||
}
|
||||
|
||||
|
||||
@@ -178,5 +178,4 @@ public class UserServiceTest {
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user