extend branch coverage
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good

This commit is contained in:
Lukas Laaser
2026-03-11 09:06:24 +01:00
parent 6065cf9aa5
commit d647a878a3
22 changed files with 741 additions and 13 deletions
@@ -9,6 +9,7 @@ import SuMoC.backend.user.service.CurrentUserService;
import SuMoC.backend.user.service.FriendshipService;
import SuMoC.backend.user.service.PrivacyService;
import SuMoC.backend.user.stats.*;
import SuMoC.backend.user.stats.models.StatsList;
import jakarta.transaction.Transactional;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@@ -92,10 +92,13 @@ public class AuthenticationService {
User user = new User(registrationDTO.getPublicName(), registrationDTO.getPrivateName(), registrationDTO.getEmail().toLowerCase(), encodedPassword);
// Sicherheitshalber nochmal explizit setzen
/* Shouldnt be necessary
if (user.getRoles() == null || user.getRoles().isEmpty()) {
user.setRoles(new HashSet<>());
user.getRoles().add(RoleName.USER);
}
*/
userRepository.save(user);
// We generate the login dto to get the token right after registration
@@ -72,7 +72,8 @@ public class TokenService {
return jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
}
//TODO: change return type
// Never used so commented out
/*
public void decodeJwt(String jwt){
System.out.println("###############DECODED JWT##################");
System.out.println(jwtDecoder.decode(jwt).getClaims());
@@ -83,5 +84,7 @@ public class TokenService {
return Math.toIntExact(jwtDecoder.decode(jwt).getClaim("userId"));
}
*/
}
@@ -5,6 +5,10 @@ import java.security.KeyPairGenerator;
public class KeyGeneratorUtility {
private KeyGeneratorUtility() {
throw new IllegalStateException("Utility class");
}
public static KeyPair generateRsaKey(){
KeyPair keyPair;
@@ -8,7 +8,7 @@ import SuMoC.backend.user.dtos.MinimalUserDTO;
import SuMoC.backend.user.dtos.StatScope;
import SuMoC.backend.user.enums.VisibilityPrivacy;
import SuMoC.backend.user.service.UserService;
import SuMoC.backend.user.stats.StatsList;
import SuMoC.backend.user.stats.models.StatsList;
import SuMoC.backend.user.stats.StatsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
@@ -6,14 +6,13 @@ import SuMoC.backend.routing.models.RoutingPreferences;
import SuMoC.backend.trip.models.Trip;
import SuMoC.backend.user.enums.RoleName;
import SuMoC.backend.user.enums.VisibilityPrivacy;
import SuMoC.backend.user.stats.StatsList;
import SuMoC.backend.user.stats.models.StatsList;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import lombok.Setter;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@Entity
@Table(name = "users")
@@ -1,5 +1,6 @@
package SuMoC.backend.user.stats;
import SuMoC.backend.user.stats.models.StatsList;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
@@ -1,6 +1,8 @@
package SuMoC.backend.user.stats;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.user.stats.models.Stats;
import SuMoC.backend.user.stats.models.StatsList;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import org.springframework.data.jpa.domain.Specification;
@@ -1,5 +1,6 @@
package SuMoC.backend.user.stats;
import SuMoC.backend.user.stats.models.Stats;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StatsRepository extends JpaRepository<Stats, Long> {
@@ -7,6 +7,7 @@ import SuMoC.backend.user.dtos.StatScope;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import SuMoC.backend.user.service.CurrentUserService;
import SuMoC.backend.user.stats.models.StatsList;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
@@ -74,10 +75,11 @@ public class StatsService {
User user = currentUserService.get();
/* Should not be necessary because it gets always init
if (user.getStats() == null) {
user.setStats(new StatsList(user));
}
*/
StatScope effectiveScope = (scope == null) ? StatScope.ALL : scope;
@@ -1,4 +1,4 @@
package SuMoC.backend.user.stats;
package SuMoC.backend.user.stats.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -1,4 +1,4 @@
package SuMoC.backend.user.stats;
package SuMoC.backend.user.stats.models;
import java.lang.reflect.Field;
@@ -0,0 +1,49 @@
package SuMoC.backend.other;
import SuMoC.backend.images.ImageBase64Util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ImageBase64UtilTest {
@Test
void encode_nullInput_returnsNull() {
assertNull(ImageBase64Util.encode(null));
}
@Test
void encode_emptyArray_returnsNull() {
assertNull(ImageBase64Util.encode(new byte[0]));
}
@Test
void encode_validData_returnsBase64String() {
byte[] data = {1, 2, 3};
String result = ImageBase64Util.encode(data);
assertNotNull(result);
assertFalse(result.isEmpty());
}
@Test
void decode_nullInput_returnsNull() {
assertNull(ImageBase64Util.decode(null));
}
@Test
void decode_emptyString_returnsNull() {
assertNull(ImageBase64Util.decode(""));
}
@Test
void decode_validBase64_returnsBytes() {
byte[] original = {1, 2, 3};
String encoded = ImageBase64Util.encode(original);
assertArrayEquals(original, ImageBase64Util.decode(encoded));
}
@Test
void encodeAndDecode_roundtrip_returnsOriginal() {
byte[] original = {10, 20, 30, 40, 50};
assertArrayEquals(original, ImageBase64Util.decode(ImageBase64Util.encode(original)));
}
}
@@ -0,0 +1,121 @@
package SuMoC.backend.security;
import SuMoC.backend.notification.services.EmailService;
import SuMoC.backend.security.dtos.*;
import SuMoC.backend.security.enums.RegistrationStatus;
import SuMoC.backend.security.repository.PasswordResetTokenRepository;
import SuMoC.backend.security.services.AuthenticationService;
import SuMoC.backend.security.services.TokenService;
import SuMoC.backend.user.mapper.UserMapper;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
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 org.springframework.mail.MailSendException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class AuthenticationServiceUnitTest {
@Mock private UserRepository userRepository;
@Mock private PasswordEncoder passwordEncoder;
@Mock private AuthenticationManager authenticationManager;
@Mock private TokenService tokenService;
@Mock private UserMapper userMapper;
@Mock private PasswordResetTokenRepository passwordResetTokenRepository;
@Mock private EmailService emailService;
@InjectMocks
private AuthenticationService authenticationService;
// registerUser -> catch (IllegalArgumentException)
@Test
public void testRegisterUser_IllegalArgumentException_ReturnsUnknownError() {
UserRegistrationDTO dto = new UserRegistrationDTO(
"publicName", "privateName", "valid@test.de", "validPassword123"
);
when(userRepository.existsByEmail(anyString())).thenReturn(false);
when(userRepository.existsByPublicName(anyString())).thenReturn(false);
when(passwordEncoder.encode(anyString()))
.thenThrow(new IllegalArgumentException("Simulated encoding error"));
RegistrationResponseDTO response = authenticationService.registerUser(dto);
assertEquals(RegistrationStatus.UNKNOWN_ERROR, response.getStatus());
assertNull(response.getUserDTO());
assertNull(response.getJwt());
}
// login -> catch (AuthenticationException) -> leeres LoginResponseDTO
@Test
public void testLogin_AuthenticationException_ReturnsEmptyResponse() {
UserAuthenticationPairDTO dto = new UserAuthenticationPairDTO("test@test.de", "wrongPassword");
when(authenticationManager.authenticate(any()))
.thenThrow(new BadCredentialsException("Bad credentials"));
LoginResponseDTO response = authenticationService.login(dto);
assertNotNull(response);
assertNull(response.getUserDTO());
assertEquals("", response.getJwt());
}
// login -> catch (RuntimeException) -> leeres LoginResponseDTO
// z.B. wenn userRepository.findByEmail() nach erfolgreichem Auth fehlschlägt
@Test
public void testLogin_RuntimeException_ReturnsEmptyResponse() {
UserAuthenticationPairDTO dto = new UserAuthenticationPairDTO("test@test.de", "validPassword123");
when(authenticationManager.authenticate(any())).thenReturn(null);
when(userRepository.findByEmail(anyString()))
.thenThrow(new RuntimeException("DB connection lost"));
LoginResponseDTO response = authenticationService.login(dto);
assertNotNull(response);
assertNull(response.getUserDTO());
assertEquals("", response.getJwt());
}
// generateNewPasswordResetTokenForUser -> throws MailException
@Test
public void testGenerateOtp_MailException_Propagates() {
String email = "test@test.de";
when(userRepository.existsByEmail(email)).thenReturn(true);
when(passwordResetTokenRepository.findByEmail(email)).thenReturn(Optional.empty());
when(passwordEncoder.encode(anyString())).thenReturn("encodedOtp");
doThrow(new MailSendException("Mail server down"))
.when(emailService).sendPasswordResetEmail(anyString(), anyString());
// MailException soll propagieren (kein catch im Service)
assertThrows(MailSendException.class, () ->
authenticationService.generateNewPasswordResetTokenForUser(email)
);
}
// generateNewPasswordResetTokenForUser -> UsernameNotFoundException
@Test
public void testGenerateOtp_UserNotFound_ThrowsUsernameNotFoundException() {
when(userRepository.existsByEmail(anyString())).thenReturn(false);
assertThrows(UsernameNotFoundException.class, () ->
authenticationService.generateNewPasswordResetTokenForUser("ghost@test.de")
);
}
}
@@ -4,6 +4,7 @@ import SuMoC.backend.notification.services.EmailService;
import SuMoC.backend.security.dtos.*;
import SuMoC.backend.security.enums.RegistrationStatus;
import SuMoC.backend.security.exceptions.InvalidTokenException;
import SuMoC.backend.security.models.PasswordResetToken;
import SuMoC.backend.security.repository.PasswordResetTokenRepository;
import SuMoC.backend.security.services.AuthenticationService;
@@ -23,14 +24,17 @@ import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Optional;
import static SuMoC.backend.Factories.UserTestFactory.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -157,6 +161,22 @@ public class AuthentificationServiceTest {
});
}
@Test
public void testRegistration_InvalidPassword() {
User user = validUser();
UserRegistrationDTO dto = getUserRegistrationDTO(user);
UserRegistrationDTO shortPwDto = new UserRegistrationDTO(
dto.getPublicName(), dto.getPrivateName(), dto.getEmail(), "abc"
);
RegistrationResponseDTO response = authenticationService.registerUser(shortPwDto);
assertEquals(RegistrationStatus.PASSWORD_INVALID, response.getStatus());
assertNull(response.getUserDTO());
assertNull(response.getJwt());
}
@Test
public void testRegistrationSuccessful() {
User user = validUser();
@@ -320,4 +340,67 @@ public class AuthentificationServiceTest {
}
@Test
public void testGenerateOtp_DeletesExistingToken() {
User user = validUser();
authenticationService.registerUser(getUserRegistrationDTO(user));
String email = user.getEmail();
authenticationService.generateNewPasswordResetTokenForUser(email);
authenticationService.generateNewPasswordResetTokenForUser(email);
long tokenCount = passwordResetTokenRepository.findAll()
.stream()
.filter(t -> t.getEmail().equals(email))
.count();
assertEquals(1, tokenCount);
verify(emailService, times(2)).sendPasswordResetEmail(eq(email), any());
}
@Test
public void testResetPassword_ExpiredToken() {
User user = validUser();
authenticationService.registerUser(getUserRegistrationDTO(user));
String email = user.getEmail();
authenticationService.generateNewPasswordResetTokenForUser(email);
ArgumentCaptor<String> otpCaptor = ArgumentCaptor.forClass(String.class);
verify(emailService).sendPasswordResetEmail(eq(email), otpCaptor.capture());
// Query necessary to set back time manually
entityManager.createNativeQuery(
"UPDATE one_time_password_tokens SET expiry_date = :expired WHERE email = :email"
)
.setParameter("expired", LocalDateTime.now().minusMinutes(1))
.setParameter("email", email)
.executeUpdate();
entityManager.flush();
entityManager.clear();
assertThrows(InvalidTokenException.class, () ->
authenticationService.resetPassword(new PasswordResetDTO(otpCaptor.getValue(), email, "NewValidPassword"))
);
}
@Test
public void testResetPassword_UserDeleted() {
User user = validUser();
authenticationService.registerUser(getUserRegistrationDTO(user));
String email = user.getEmail();
authenticationService.generateNewPasswordResetTokenForUser(email);
ArgumentCaptor<String> otpCaptor = ArgumentCaptor.forClass(String.class);
verify(emailService).sendPasswordResetEmail(eq(email), otpCaptor.capture());
userRepository.deleteAll();
entityManager.flush();
entityManager.clear();
assertThrows(UsernameNotFoundException.class, () ->
authenticationService.resetPassword(new PasswordResetDTO(otpCaptor.getValue(), email, "NewValidPassword2026"))
);
}
}
@@ -0,0 +1,104 @@
package SuMoC.backend.security;
import SuMoC.backend.security.utils.RSAKeyProperties;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@ActiveProfiles("test")
public class RSAKeyPropertiesTest {
@TempDir
Path tempDir;
private String pubKeyPath() { return tempDir.resolve("public.pem").toString(); }
private String privKeyPath() { return tempDir.resolve("private.pem").toString(); }
@Test
public void constructor_generatesAndPersistsKeys_whenFilesDoNotExist() {
RSAKeyProperties props = new RSAKeyProperties(pubKeyPath(), privKeyPath());
assertNotNull(props.getPublicKey());
assertNotNull(props.getPrivateKey());
assertInstanceOf(RSAPublicKey.class, props.getPublicKey());
assertInstanceOf(RSAPrivateKey.class, props.getPrivateKey());
}
@Test
public void constructor_loadsExistingKeys_whenFilesExist() throws IOException {
RSAKeyProperties first = new RSAKeyProperties(pubKeyPath(), privKeyPath());
RSAKeyProperties second = new RSAKeyProperties(pubKeyPath(), privKeyPath());
assertEquals(
first.getPublicKey().getModulus(),
second.getPublicKey().getModulus()
);
assertEquals(
first.getPrivateKey().getModulus(),
second.getPrivateKey().getModulus()
);
Path onlyPub = tempDir.resolve("onlypub");
String pub2 = onlyPub.resolve("public.pem").toString();
String priv2 = onlyPub.resolve("private.pem").toString();
RSAKeyProperties onlyPubProps = new RSAKeyProperties(pub2, priv2);
Files.delete(Paths.get(priv2));
RSAKeyProperties mixed = new RSAKeyProperties(pub2, priv2);
assertNotNull(mixed.getPublicKey());
assertNotNull(mixed.getPrivateKey());
}
@Test
public void constructor_generatesDifferentKeys_forDifferentDirs() {
Path otherDir = tempDir.resolve("other");
String otherPub = otherDir.resolve("public.pem").toString();
String otherPriv = otherDir.resolve("private.pem").toString();
RSAKeyProperties first = new RSAKeyProperties(pubKeyPath(), privKeyPath());
RSAKeyProperties second = new RSAKeyProperties(otherPub, otherPriv);
assertNotEquals(
first.getPublicKey().getModulus(),
second.getPublicKey().getModulus()
);
}
@Test
public void constructor_throwsIllegalStateException_onInvalidPath() {
assertThrows(IllegalStateException.class,
() -> new RSAKeyProperties("/invalid\0path/pub.pem", "/invalid\0path/priv.pem")
);
}
@Test
public void constructor_throwsIllegalStateException_whenDirectoryNotWritable() throws Exception {
Path readOnlyDir = tempDir.resolve("readonly");
Files.createDirectories(readOnlyDir);
readOnlyDir.toFile().setWritable(false);
String pub = readOnlyDir.resolve("public.pem").toString();
String priv = readOnlyDir.resolve("private.pem").toString();
try {
assertThrows(IllegalStateException.class,
() -> new RSAKeyProperties(pub, priv)
);
} finally {
readOnlyDir.toFile().setWritable(true);
}
}
}
@@ -3,8 +3,8 @@ package SuMoC.backend.user;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import SuMoC.backend.user.stats.Stats;
import SuMoC.backend.user.stats.StatsList;
import SuMoC.backend.user.stats.models.Stats;
import SuMoC.backend.user.stats.models.StatsList;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
@@ -85,7 +85,7 @@ public class FriendshipServiceTest {
friendshipRepository.deleteAllInBatch();
friendshipRepository.flush();
// already pending: only sender reverse missing -> unexpected throw
// already pending: only sender side exists, reverse missing -> unexpected throw
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REQUESTED));
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
@@ -98,7 +98,7 @@ public class FriendshipServiceTest {
friendshipRepository.deleteAllInBatch();
friendshipRepository.flush();
// already pending reverse: only sender reverse missing -> unexpected throw
// already pending reverse: only sender side exists, reverse missing -> unexpected throw
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
@@ -111,7 +111,7 @@ public class FriendshipServiceTest {
friendshipRepository.deleteAllInBatch();
friendshipRepository.flush();
// already friends: only sender reverse missing -> unexpected throw
// already friends: only sender side exists, reverse missing -> unexpected throw
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
@@ -121,6 +121,22 @@ public class FriendshipServiceTest {
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REJECTED));
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
friendshipRepository.flush();
// PENDING check: relation to Friend != REQUESTED, rel to Sender == PENDING
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.PENDING));
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
friendshipRepository.flush();
// ACCEPTED check: relation to Friend != ACCEPTED, rel to Sender == ACCEPTED
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REQUESTED));
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
friendshipRepository.flush();
}
@Test
@@ -174,6 +190,31 @@ public class FriendshipServiceTest {
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
// wrong status: sender is REQUESTED instead of PENDING (swapped)
friendshipRepository.deleteAllInBatch();
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REQUESTED));
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.PENDING));
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
// wrong status: both ACCEPTED
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
// relation to Friend != PENDING, relation to Sender == REQUESTED
friendshipRepository.deleteAllInBatch();
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REQUESTED));
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
friendshipRepository.flush();
// relation to Friend == PENDING, relation to sender != REQUESTED
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
}
@@ -205,6 +246,22 @@ public class FriendshipServiceTest {
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
assertThrows(RuntimeException.class, () -> friendshipService.rejectFriendship(sender, friend.getId()));
// only one side exists (sender has PENDING, friend missing)
friendshipRepository.deleteAllInBatch();
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
assertThrows(RuntimeException.class, () -> friendshipService.rejectFriendship(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
// only one side exists (friend has REQUESTED, sender missing)
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REQUESTED));
assertThrows(RuntimeException.class, () -> friendshipService.rejectFriendship(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
// wrong status: sender is REQUESTED instead of PENDING
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REQUESTED));
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.PENDING));
assertThrows(RuntimeException.class, () -> friendshipService.rejectFriendship(sender, friend.getId()));
}
@@ -236,6 +293,16 @@ public class FriendshipServiceTest {
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REQUESTED));
assertThrows(RuntimeException.class, () -> friendshipService.unfriend(sender, friend.getId()));
// only one side exists (only sender has ACCEPTED)
friendshipRepository.deleteAllInBatch();
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
assertThrows(RuntimeException.class, () -> friendshipService.unfriend(sender, friend.getId()));
friendshipRepository.deleteAllInBatch();
// only one side exists (only friend has ACCEPTED)
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
assertThrows(RuntimeException.class, () -> friendshipService.unfriend(sender, friend.getId()));
}
@@ -446,4 +513,33 @@ public class FriendshipServiceTest {
assertThrows(RuntimeException.class,
() -> friendshipService.getPrivateNameIfFriendshipAccepted(sender, List.of(99999L)));
}
// -------------------------------------------------------------------------
// getByFriendcode
// -------------------------------------------------------------------------
@Test
void requestFriendshipByFriendcode_Success() {
friendshipService.requestFriendshipByFriendcode(sender, friend.getFriendCode());
assertEquals(FriendShipStatus.REQUESTED, friendshipRepository.findByUserAndFriend(sender, friend).getStatus());
assertEquals(FriendShipStatus.PENDING, friendshipRepository.findByUserAndFriend(friend, sender).getStatus());
}
@Test
void requestFriendshipByFriendcode_NotFound_Throws() {
assertThrows(RuntimeException.class,
() -> friendshipService.requestFriendshipByFriendcode(sender, "INVALID_CODE"));
}
@Test
void requestFriendshipByFriendcode_Self_Throws() {
assertThrows(RuntimeException.class,
() -> friendshipService.requestFriendshipByFriendcode(sender, sender.getFriendCode()));
}
}
@@ -5,6 +5,8 @@ import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.gamification.scoretable.LeaderboardService;
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
import SuMoC.backend.gamification.scoretable.models.LeaderboardEntry;
import SuMoC.backend.images.ImageBase64Util;
import SuMoC.backend.user.enums.VisibilityPrivacy;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.FriendshipRepository;
import SuMoC.backend.user.repository.UserRepository;
@@ -197,5 +199,87 @@ public class LeaderboardServiceTest {
assertEquals(privacyService.checkVisibility(sender, user) ? user.getPrivateName() : user.getPublicName(), entry.getUsername());
}
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
public void testGetFriendLeaderboard_senderNotInFriendList() {
// sender is never in friendlist -> noneMatch always true -> sender always appended
Leaderboard lb = leaderboardService.getFriendLeaderboard(Timeframe.TOTAL, "XP", 3);
LeaderboardEntry senderEntry = lb.getEntries().stream()
.filter(e -> e.getUserId().equals(sender.getId()))
.findFirst().orElseThrow();
// sender entry uses privateName, isFriend=false, own profilePicture
assertEquals(sender.getPrivateName(), senderEntry.getUsername());
assertFalse(senderEntry.getIsFriend());
assertEquals(
ImageBase64Util.encode(sender.getProfileImage().getImageData()),
senderEntry.getBase64ProfilePicture()
);
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
public void testGetLeaderboard_senderNotInTopN() {
// reset sender XP to 0 so sender is last -> falls into noneMatch-block
sender.getStats().addToAllStats("XP", -1000);
Leaderboard lb = leaderboardService.getLeaderboard(Timeframe.TOTAL, "XP", 3);
// should be top 3 + sender appended
assertEquals(4, lb.getEntries().size());
LeaderboardEntry senderEntry = lb.getEntries().stream()
.filter(e -> e.getUserId().equals(sender.getId()))
.findFirst().orElseThrow();
assertEquals(sender.getPrivateName(), senderEntry.getUsername());
assertFalse(senderEntry.getIsFriend());
assertEquals(
ImageBase64Util.encode(sender.getProfileImage().getImageData()),
senderEntry.getBase64ProfilePicture()
);
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
public void testGetRank() {
// sender has 1000 XP -> rank 1 (nobody higher)
long rank = leaderboardService.getRank(Timeframe.TOTAL, "XP", 1000);
assertEquals(1, rank);
// rank of 0 XP, everyone is higher -> last place
long lastRank = leaderboardService.getRank(Timeframe.TOTAL, "XP", 0);
assertEquals(11, lastRank); // 10 users all have > 0 XP, so rank = 10 + 1
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
public void testGetFriendLeaderboard_profilePictureEncoding() {
// ps = true: friend is PUBLIC -> encode() called, privateName
User friend = friends.getFirst();
friend.setVisibilityPrivacy(VisibilityPrivacy.PUBLIC);
byte[] img = new byte[]{1, 2, 3};
friend.getProfileImage().setImageData(img);
Leaderboard lb = leaderboardService.getFriendLeaderboard(Timeframe.TOTAL, "XP");
LeaderboardEntry publicEntry = lb.getEntries().stream()
.filter(e -> e.getUserId().equals(friend.getId()))
.findFirst().orElseThrow();
assertEquals(friend.getPrivateName(), publicEntry.getUsername());
assertEquals(ImageBase64Util.encode(img), publicEntry.getBase64ProfilePicture());
// ps = false: friend not public -> null, publicName
User nonPublicFriend = friends.get(1);
LeaderboardEntry nonPublicEntry = lb.getEntries().stream()
.filter(e -> e.getUserId().equals(nonPublicFriend.getId()))
.findFirst().orElseThrow();
assertEquals(nonPublicFriend.getPublicName(), nonPublicEntry.getUsername());
assertNull(nonPublicEntry.getBase64ProfilePicture());
}
}
@@ -0,0 +1,154 @@
package SuMoC.backend.user.service;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import SuMoC.backend.user.stats.StatsListRepository;
import SuMoC.backend.user.stats.StatsListSpecifications;
import SuMoC.backend.user.stats.models.StatsList;
import jakarta.transaction.Transactional;
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.test.context.ActiveProfiles;
import java.util.List;
import static SuMoC.backend.Factories.UserTestFactory.uniqueUser;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class StatsListSpecificationsTest {
@Autowired
private UserRepository userRepository;
@Autowired
private StatsListRepository statsListRepository;
private User user1;
private User user2;
private User user3;
@BeforeEach
void setup() {
user1 = userRepository.save(uniqueUser(1));
user2 = userRepository.save(uniqueUser(2));
user3 = userRepository.save(uniqueUser(3));
user1.getStats().addToStat(Timeframe.TOTAL, "XP", 100);
user2.getStats().addToStat(Timeframe.TOTAL, "XP", 50);
user3.getStats().addToStat(Timeframe.TOTAL, "XP", 200);
user1.getStats().addToStat(Timeframe.WEEKLY, "XP", 30);
user2.getStats().addToStat(Timeframe.WEEKLY, "XP", 80);
user3.getStats().addToStat(Timeframe.WEEKLY, "XP", 10);
user1.getStats().addToStat(Timeframe.MONTHLY, "CO2_SAVED", 500);
user2.getStats().addToStat(Timeframe.MONTHLY, "CO2_SAVED", 100);
user3.getStats().addToStat(Timeframe.MONTHLY, "CO2_SAVED", 300);
userRepository.saveAll(List.of(user1, user2, user3));
}
@Test
void orderByStat_total_xp_descendingOrder() {
List<StatsList> result = statsListRepository.findAll(
StatsListSpecifications.orderByStat(Timeframe.TOTAL, "XP"));
List<StatsList> filtered = result.stream()
.filter(s -> s.getStatValue(Timeframe.TOTAL, "XP") > 0)
.toList();
assertTrue(filtered.size() >= 3);
assertEquals(200, filtered.get(0).getStatValue(Timeframe.TOTAL, "XP"));
assertEquals(100, filtered.get(1).getStatValue(Timeframe.TOTAL, "XP"));
assertEquals(50, filtered.get(2).getStatValue(Timeframe.TOTAL, "XP"));
}
@Test
void orderByStat_weekly_xp_descendingOrder() {
List<StatsList> result = statsListRepository.findAll(
StatsListSpecifications.orderByStat(Timeframe.WEEKLY, "XP"));
List<StatsList> filtered = result.stream()
.filter(s -> s.getStatValue(Timeframe.WEEKLY, "XP") > 0)
.toList();
assertTrue(filtered.size() >= 3);
assertEquals(80, filtered.get(0).getStatValue(Timeframe.WEEKLY, "XP"));
assertEquals(30, filtered.get(1).getStatValue(Timeframe.WEEKLY, "XP"));
assertEquals(10, filtered.get(2).getStatValue(Timeframe.WEEKLY, "XP"));
}
@Test
void orderByStat_monthly_co2_descendingOrder() {
List<StatsList> result = statsListRepository.findAll(
StatsListSpecifications.orderByStat(Timeframe.MONTHLY, "CO2_SAVED"));
List<StatsList> filtered = result.stream()
.filter(s -> s.getStatValue(Timeframe.MONTHLY, "CO2_SAVED") > 0)
.toList();
assertTrue(filtered.size() >= 3);
assertEquals(500, filtered.get(0).getStatValue(Timeframe.MONTHLY, "CO2_SAVED"));
assertEquals(300, filtered.get(1).getStatValue(Timeframe.MONTHLY, "CO2_SAVED"));
assertEquals(100, filtered.get(2).getStatValue(Timeframe.MONTHLY, "CO2_SAVED"));
}
@Test
void higherThan_total_xp_findsCorrectUsers() {
List<StatsList> result = statsListRepository.findAll(
StatsListSpecifications.higherThan(Timeframe.TOTAL, "XP", 75));
assertTrue(result.size() >= 2);
assertTrue(result.stream()
.allMatch(s -> s.getStatValue(Timeframe.TOTAL, "XP") > 75));
}
@Test
void higherThan_weekly_xp_exactBoundary() {
List<StatsList> result = statsListRepository.findAll(
StatsListSpecifications.higherThan(Timeframe.WEEKLY, "XP", 30));
assertTrue(result.stream()
.allMatch(s -> s.getStatValue(Timeframe.WEEKLY, "XP") > 30));
assertTrue(result.stream()
.anyMatch(s -> s.getStatValue(Timeframe.WEEKLY, "XP") == 80));
}
@Test
void higherThan_monthly_co2_noResults() {
List<StatsList> result = statsListRepository.findAll(
StatsListSpecifications.higherThan(Timeframe.MONTHLY, "CO2_SAVED", 600));
assertTrue(result.isEmpty());
}
@Test
void higherThan_total_xp_allOwnResults() {
List<StatsList> result = statsListRepository.findAll(
StatsListSpecifications.higherThan(Timeframe.TOTAL, "XP", 0));
assertTrue(result.size() >= 3);
assertTrue(result.stream()
.allMatch(s -> s.getStatValue(Timeframe.TOTAL, "XP") > 0));
}
@Test
void combined_higherThan_and_orderByStat() {
List<StatsList> result = statsListRepository.findAll(
StatsListSpecifications.higherThan(Timeframe.TOTAL, "XP", 75)
.and(StatsListSpecifications.orderByStat(Timeframe.TOTAL, "XP")));
assertTrue(result.size() >= 2);
assertTrue(result.stream()
.allMatch(s -> s.getStatValue(Timeframe.TOTAL, "XP") > 75));
assertEquals(200, result.get(0).getStatValue(Timeframe.TOTAL, "XP"));
assertEquals(100, result.get(1).getStatValue(Timeframe.TOTAL, "XP"));
}
}
@@ -4,7 +4,7 @@ import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.user.dtos.StatScope;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import SuMoC.backend.user.stats.StatsList;
import SuMoC.backend.user.stats.models.StatsList;
import SuMoC.backend.user.stats.StatsService;
import jakarta.transaction.Transactional;
import org.junit.jupiter.api.BeforeEach;
@@ -392,6 +392,27 @@ public class UserServiceTest {
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
void testGetSelf_profilePicture() {
// imageData is null -> no base64 in DTO
sender.getProfileImage().setImageData(null);
userRepository.save(sender);
assertNull(userService.getSelf().getBase64ProfilePicture());
// imageData is set -> base64 in DTO
byte[] image = new byte[]{1, 2, 3, 4, 5};
sender.getProfileImage().setImageData(image);
userRepository.save(sender);
assertEquals(ImageBase64Util.encode(image), userService.getSelf().getBase64ProfilePicture());
// profileImage is null -> no base64 in DTO
sender.setProfileImage(null);
userRepository.save(sender);
userRepository.flush();
assertNull(userService.getSelf().getBase64ProfilePicture());
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
void testGetProfilePicture_publicWithoutPicture() {