chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
e396568cc3
commit
5ee51d1913
2918 files changed
+302373
-3
No files matched your search
+57
@@ -0,0 +1,57 @@
|
||||
package com.solvway.mobile.api.cache;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class MessageLabelCacheTest {
|
||||
|
||||
private static class MutableClock extends Clock {
|
||||
private Instant now = Instant.parse("2026-04-24T00:00:00Z");
|
||||
@Override public ZoneId getZone() { return ZoneId.of("UTC"); }
|
||||
@Override public Clock withZone(ZoneId zone) { return this; }
|
||||
@Override public Instant instant() { return now; }
|
||||
void advance(Duration d) { now = now.plus(d); }
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returnsEmpty_whenNothingCached() {
|
||||
MessageLabelCache cache = new MessageLabelCache(Clock.systemUTC());
|
||||
assertThat(cache.get("CODE", "en_US")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returnsValue_whenWithinTtl() {
|
||||
MutableClock clock = new MutableClock();
|
||||
MessageLabelCache cache = new MessageLabelCache(clock);
|
||||
cache.put("CODE", "en_US", "Hello");
|
||||
clock.advance(Duration.ofMinutes(9));
|
||||
|
||||
assertThat(cache.get("CODE", "en_US")).contains("Hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returnsEmpty_afterTtlExpiry() {
|
||||
MutableClock clock = new MutableClock();
|
||||
MessageLabelCache cache = new MessageLabelCache(clock);
|
||||
cache.put("CODE", "en_US", "Hello");
|
||||
clock.advance(Duration.ofMinutes(11));
|
||||
|
||||
assertThat(cache.get("CODE", "en_US")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_respectsLocaleBoundary() {
|
||||
MessageLabelCache cache = new MessageLabelCache(Clock.systemUTC());
|
||||
cache.put("CODE", "en_US", "Hello");
|
||||
cache.put("CODE", "zh_CN", "Nihao");
|
||||
|
||||
assertThat(cache.get("CODE", "en_US")).contains("Hello");
|
||||
assertThat(cache.get("CODE", "zh_CN")).contains("Nihao");
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.solvway.mobile.api.config;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum.CmsPlatform;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class AuthAppKeyConfigTest {
|
||||
|
||||
@Test
|
||||
void resolvesConfiguredPlatformPerKey() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("customerKey:CP", "appKey:APP"));
|
||||
|
||||
assertThat(config.contains("customerKey")).isTrue();
|
||||
assertThat(config.resolvePlatform("customerKey")).isEqualTo(CmsPlatform.CP);
|
||||
assertThat(config.resolvePlatform("appKey")).isEqualTo(CmsPlatform.APP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bareKeyWithoutPlatformDefaultsToApp() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("legacyKey"));
|
||||
|
||||
assertThat(config.contains("legacyKey")).isTrue();
|
||||
assertThat(config.resolvePlatform("legacyKey")).isEqualTo(CmsPlatform.APP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unrecognisedPlatformSuffixTreatsWholeTokenAsKeyAndDefaultsToApp() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("k:NOPE"));
|
||||
|
||||
// "NOPE" is not a CmsPlatform, so the whole token is the key (not "k").
|
||||
assertThat(config.contains("k:NOPE")).isTrue();
|
||||
assertThat(config.contains("k")).isFalse();
|
||||
assertThat(config.resolvePlatform("k:NOPE")).isEqualTo(CmsPlatform.APP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyContainingColonResolvesTrailingPlatformSuffix() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("ab:cd:CP"));
|
||||
|
||||
assertThat(config.contains("ab:cd")).isTrue();
|
||||
assertThat(config.resolvePlatform("ab:cd")).isEqualTo(CmsPlatform.CP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void suffixedTokenIsNotItselfAKey() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("cpKey:CP"));
|
||||
|
||||
assertThat(config.contains("cpKey:CP")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownKeyIsNotContainedAndResolvesToAppDefault() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("k:CP"));
|
||||
|
||||
assertThat(config.contains("missing")).isFalse();
|
||||
assertThat(config.contains(null)).isFalse();
|
||||
assertThat(config.resolvePlatform("missing")).isEqualTo(CmsPlatform.APP);
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.solvway.mobile.api.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class StartupSecurityConfigValidatorTest {
|
||||
|
||||
private static final String VALID_SECRET = "0123456789abcdef0123456789abcdef";
|
||||
private static final String VALID_OUTBOUND_KEY = "outbound-key";
|
||||
|
||||
private static AuthAppKeyConfig keysOf(List<String> keys) {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(keys);
|
||||
return config;
|
||||
}
|
||||
|
||||
private static StartupSecurityConfigValidator validator(String secret, String outboundKey, List<String> inboundKeys) {
|
||||
return new StartupSecurityConfigValidator(secret, outboundKey, keysOf(inboundKeys));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsFullyConfiguredEnvironment() {
|
||||
assertThatCode(validator(VALID_SECRET, VALID_OUTBOUND_KEY, List.of("client-key"))::validate)
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingJwtSecret() {
|
||||
assertThatThrownBy(validator("", VALID_OUTBOUND_KEY, List.of("client-key"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("JWT_SECRET");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSpringQuotedEmptyDefaultForJwtSecret() {
|
||||
assertThatThrownBy(validator("''", VALID_OUTBOUND_KEY, List.of("client-key"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("JWT_SECRET");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsShortJwtSecret() {
|
||||
assertThatThrownBy(validator("tooshort", VALID_OUTBOUND_KEY, List.of("client-key"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("at least 32");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsEmptyInboundApiKeyList() {
|
||||
assertThatThrownBy(validator(VALID_SECRET, VALID_OUTBOUND_KEY, List.of())::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("AUTH_API_KEYS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInboundApiKeyListWhoseTokensHaveNoKey() {
|
||||
// ":CP" is non-blank but parses to an empty key, so it would authorise nothing.
|
||||
assertThatThrownBy(validator(VALID_SECRET, VALID_OUTBOUND_KEY, List.of(":CP"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("AUTH_API_KEYS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInboundApiKeyListOfBlanks() {
|
||||
assertThatThrownBy(validator(VALID_SECRET, VALID_OUTBOUND_KEY, List.of("", " "))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("AUTH_API_KEYS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingOutboundApiKey() {
|
||||
assertThatThrownBy(validator(VALID_SECRET, "", List.of("client-key"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("APIKEY");
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorMessageNeverLeaksTheSecretValue() {
|
||||
String secret = "supersecretvalue";
|
||||
assertThatThrownBy(validator(secret, VALID_OUTBOUND_KEY, List.of("client-key"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.satisfies(ex -> assertThat(ex.getMessage()).doesNotContain(secret));
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
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.http.ResponseEntity;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AuthControllerPhoneVerificationTest {
|
||||
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
|
||||
@InjectMocks private AuthController controller;
|
||||
|
||||
private ResponseEntity<Map<String, String>> loginAs(GeneralEnum.FlagYesNo phone, GeneralEnum.FlagYesNo email) {
|
||||
User u = new User();
|
||||
u.setMemberCode("M1");
|
||||
u.setName("Alice");
|
||||
u.setPhoneNoPrefix("60");
|
||||
u.setPhoneNo("123456789");
|
||||
u.setLogin(GeneralEnum.LoginStatus.Y);
|
||||
u.setPhoneVerified(phone);
|
||||
u.setEmailVerified(email);
|
||||
when(authenticationService.getToken(any())).thenReturn("tok");
|
||||
when(authenticationService.loadUserByToken("tok")).thenReturn(u);
|
||||
AuthRequest req = new AuthRequest();
|
||||
req.setUsername("alice@example.com");
|
||||
return controller.login(req);
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginReportsPhoneVerificationRequiredWhenNeitherVerified() {
|
||||
Map<String, String> body = loginAs(GeneralEnum.FlagYesNo.N, GeneralEnum.FlagYesNo.N).getBody();
|
||||
assertThat(body).containsEntry("phoneVerificationRequired", "true");
|
||||
assertThat(body).containsEntry("token", "tok").containsEntry("memberCode", "M1")
|
||||
.containsEntry("name", "Alice").containsEntry("phoneNoPrefix", "60")
|
||||
.containsEntry("phoneNo", "123456789").containsEntry("resetPasswordRequired", "false");
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginReportsNotRequiredWhenPhoneVerified() {
|
||||
Map<String, String> body = loginAs(GeneralEnum.FlagYesNo.Y, GeneralEnum.FlagYesNo.N).getBody();
|
||||
assertThat(body).containsEntry("phoneVerificationRequired", "false");
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginReportsNotRequiredWhenEmailVerified() {
|
||||
Map<String, String> body = loginAs(GeneralEnum.FlagYesNo.N, GeneralEnum.FlagYesNo.Y).getBody();
|
||||
assertThat(body).containsEntry("phoneVerificationRequired", "false");
|
||||
}
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.model.CheckInBooth;
|
||||
import com.solvway.core.model.StockistCmsProfile;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.core.utils.QrScanUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventControllerAttendanceTest {
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private QrScanUtil qrScanUtil;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private EventController controller;
|
||||
|
||||
private static final long MEMBER_UUID = 12345L;
|
||||
|
||||
private CheckInBooth checkIn(long stockistUuid, long eventUuid, LocalDateTime dt) {
|
||||
CheckInBooth c = new CheckInBooth();
|
||||
c.setStockistUuid(stockistUuid);
|
||||
c.setEventUuid(eventUuid);
|
||||
c.setCheckInDateTime(dt);
|
||||
c.setCheckInDate(dt == null ? null : dt.toLocalDate());
|
||||
return c;
|
||||
}
|
||||
|
||||
private StockistCmsProfile profile(String name) {
|
||||
StockistCmsProfile p = new StockistCmsProfile();
|
||||
p.setStockistName(name);
|
||||
return p;
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_unresolvedMember_returns401() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("");
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
verify(eventService, never()).findCheckInBoothByMemberUuid(anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_sortsDescAndEnrichesBoothName() {
|
||||
LocalDateTime older = LocalDateTime.of(2026, 7, 1, 10, 0);
|
||||
LocalDateTime newer = LocalDateTime.of(2026, 7, 3, 15, 30);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(checkIn(101L, 900L, older), checkIn(202L, 901L, newer)));
|
||||
when(stockistCmsService.findByStockistUuid("101")).thenReturn(Optional.of(profile("Booth Alpha")));
|
||||
when(stockistCmsService.findByStockistUuid("202")).thenReturn(Optional.of(profile("Booth Beta")));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
// most recent first
|
||||
assertThat(body.get(0)).containsEntry("stockistName", "Booth Beta");
|
||||
assertThat(body.get(0)).containsEntry("stockistUuid", 202L);
|
||||
assertThat(body.get(1)).containsEntry("stockistName", "Booth Alpha");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_repeatedBooth_lookedUpOnce() {
|
||||
LocalDateTime t1 = LocalDateTime.of(2026, 7, 1, 10, 0);
|
||||
LocalDateTime t2 = LocalDateTime.of(2026, 7, 2, 10, 0);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(checkIn(101L, 900L, t1), checkIn(101L, 901L, t2)));
|
||||
when(stockistCmsService.findByStockistUuid("101")).thenReturn(Optional.of(profile("Booth Alpha")));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getBody()).hasSize(2);
|
||||
verify(stockistCmsService, times(1)).findByStockistUuid("101");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_unresolvedBoothName_recordStillReturnedWithoutName() {
|
||||
LocalDateTime t1 = LocalDateTime.of(2026, 7, 1, 10, 0);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(checkIn(101L, 900L, t1)));
|
||||
when(stockistCmsService.findByStockistUuid("101")).thenReturn(Optional.empty());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getBody()).hasSize(1);
|
||||
assertThat(res.getBody().get(0)).doesNotContainKey("stockistName");
|
||||
assertThat(res.getBody().get(0)).containsEntry("stockistUuid", 101L);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_empty_returnsEmptyList() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID)).thenReturn(List.of());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_nullCheckInDateTime_sortsLast() {
|
||||
LocalDateTime newer = LocalDateTime.of(2026, 7, 3, 15, 30);
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(checkIn(101L, 900L, null), checkIn(202L, 901L, newer)));
|
||||
when(stockistCmsService.findByStockistUuid("101")).thenReturn(Optional.of(profile("Booth Null")));
|
||||
when(stockistCmsService.findByStockistUuid("202")).thenReturn(Optional.of(profile("Booth Beta")));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
// Non-null timestamp first, null timestamp sorts last.
|
||||
assertThat(body.get(0)).containsEntry("stockistUuid", 202L);
|
||||
assertThat(body.get(1)).containsEntry("stockistUuid", 101L);
|
||||
assertThat(body.get(1)).doesNotContainKey("checkInDateTime");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_repeatedBoothWithNullName_lookedUpOnce() {
|
||||
LocalDateTime t1 = LocalDateTime.of(2026, 7, 1, 10, 0);
|
||||
LocalDateTime t2 = LocalDateTime.of(2026, 7, 2, 10, 0);
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(checkIn(101L, 900L, t1), checkIn(101L, 901L, t2)));
|
||||
when(stockistCmsService.findByStockistUuid("101")).thenReturn(Optional.empty());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getBody()).hasSize(2);
|
||||
assertThat(res.getBody().get(0)).doesNotContainKey("stockistName");
|
||||
assertThat(res.getBody().get(1)).doesNotContainKey("stockistName");
|
||||
// A null-resolving name is cached too: the repeated booth is looked up only once.
|
||||
verify(stockistCmsService, times(1)).findByStockistUuid("101");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_nonNumericMemberUuid_returns401() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("not-a-number");
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
verify(eventService, never()).findCheckInBoothByMemberUuid(anyLong());
|
||||
}
|
||||
}
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.PaymentEnum;
|
||||
import com.solvway.core.model.CheckInBooth;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.StockistCmsProfile;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.core.utils.QrScanUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventControllerCheckInTest {
|
||||
|
||||
// Real QrScanUtil — pure/stateless; exercises actual prefix routing
|
||||
@Spy private QrScanUtil qrScanUtil = new QrScanUtil();
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
|
||||
@InjectMocks
|
||||
private EventController controller;
|
||||
|
||||
// CI prefix from PaymentEnum.QrScanCodeAction.CI → "xFS86OG395iCIPch_"
|
||||
private static final String CI_PREFIX = PaymentEnum.QrScanCodeAction.CI.getPrefix();
|
||||
private static final String PT_PREFIX = PaymentEnum.QrScanCodeAction.PT.getPrefix();
|
||||
|
||||
private static final String ENCRYPTED_STOCKIST = "encryptedStockistPayload";
|
||||
private static final String STOCKIST_UUID_STR = "999001";
|
||||
private static final long STOCKIST_UUID = 999001L;
|
||||
private static final String MEMBER_UUID_STR = "12345";
|
||||
private static final long MEMBER_UUID = 12345L;
|
||||
private static final long EVENT_UUID = 77001L;
|
||||
private static final String MEMBER_CODE = "MC001";
|
||||
|
||||
private Event buildEvent() {
|
||||
Event e = new Event();
|
||||
e.setName("Tastefully 2026");
|
||||
e.setUuid(EVENT_UUID);
|
||||
return e;
|
||||
}
|
||||
|
||||
// ── 1. Happy path ────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_happyPath_returnsCheckedIn() {
|
||||
Event event = buildEvent();
|
||||
CheckInBooth saved = new CheckInBooth();
|
||||
|
||||
StockistCmsProfile profile = new StockistCmsProfile();
|
||||
profile.setStockistName("Booth Alpha");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(MEMBER_UUID_STR);
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn(MEMBER_CODE);
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn(STOCKIST_UUID_STR);
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
when(eventService.saveCheckInBooth(any())).thenReturn(saved);
|
||||
when(stockistCmsService.findByStockistUuid(STOCKIST_UUID_STR)).thenReturn(Optional.of(profile));
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "CHECKED_IN");
|
||||
assertThat(res.getBody()).containsEntry("eventName", "Tastefully 2026");
|
||||
assertThat(res.getBody()).containsEntry("stockistName", "Booth Alpha");
|
||||
|
||||
// Verify saveCheckInBooth called with correct field values
|
||||
ArgumentCaptor<CheckInBooth> captor = ArgumentCaptor.forClass(CheckInBooth.class);
|
||||
verify(eventService).saveCheckInBooth(captor.capture());
|
||||
CheckInBooth recorded = captor.getValue();
|
||||
assertThat(recorded.getEventUuid()).isEqualTo(EVENT_UUID);
|
||||
assertThat(recorded.getStockistUuid()).isEqualTo(STOCKIST_UUID);
|
||||
assertThat(recorded.getMemberUuid()).isEqualTo(MEMBER_UUID);
|
||||
assertThat(recorded.getCreateBy()).isEqualTo(MEMBER_CODE);
|
||||
assertThat(recorded.getDoneBy()).isEqualTo(MEMBER_CODE);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 1b. Already checked in today at this booth ───────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_alreadyCheckedInToday_returnsAlreadyCheckedInAndDoesNotSave() {
|
||||
Event event = buildEvent();
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(MEMBER_UUID_STR);
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn(MEMBER_CODE);
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn(STOCKIST_UUID_STR);
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
// A check-in already exists for this (event, member, booth, today).
|
||||
when(eventService.findCheckInExisted(any())).thenReturn(true);
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "ALREADY_CHECKED_IN");
|
||||
assertThat(res.getBody()).containsEntry("eventName", "Tastefully 2026");
|
||||
// The dedup check ran against the correct booth/member/event...
|
||||
ArgumentCaptor<CheckInBooth> captor = ArgumentCaptor.forClass(CheckInBooth.class);
|
||||
verify(eventService).findCheckInExisted(captor.capture());
|
||||
CheckInBooth probed = captor.getValue();
|
||||
assertThat(probed.getEventUuid()).isEqualTo(EVENT_UUID);
|
||||
assertThat(probed.getStockistUuid()).isEqualTo(STOCKIST_UUID);
|
||||
assertThat(probed.getMemberUuid()).isEqualTo(MEMBER_UUID);
|
||||
// ...and no duplicate was persisted.
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
}
|
||||
|
||||
// ── 2. Wrong QR type ─────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_wrongQrType_returnsWrongQrType() {
|
||||
Map<String, String> body = Map.of("qrText", PT_PREFIX + "somePayload");
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "WRONG_QR_TYPE");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
|
||||
// ── 3. No active event ───────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_noActiveEvent_returnsNoActiveEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "NO_ACTIVE_EVENT");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
|
||||
// ── 4. Invalid stockist uuid ─────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_emptyDecryptResult_returnsInvalidQr() {
|
||||
Event event = buildEvent();
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
// decrypt returns empty → INVALID_QR
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn("");
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "INVALID_QR");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkIn_nonNumericStockistUuid_returnsInvalidQr() {
|
||||
Event event = buildEvent();
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
// decrypt returns non-numeric value
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn("not-a-number");
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "INVALID_QR");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
|
||||
// ── 5. Unresolved member → HTTP 401 ─────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_unresolvedMember_returns401() {
|
||||
Event event = buildEvent();
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn(STOCKIST_UUID_STR);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("");
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
}
|
||||
|
||||
// ── 6. Persistence failure ────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_persistenceFailure_returnsCheckInFailed() {
|
||||
Event event = buildEvent();
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn(STOCKIST_UUID_STR);
|
||||
when(eventService.saveCheckInBooth(any())).thenReturn(null);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(MEMBER_UUID_STR);
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn(MEMBER_CODE);
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "CHECK_IN_FAILED");
|
||||
verify(eventService).saveCheckInBooth(any());
|
||||
}
|
||||
}
|
||||
|
||||
// ── 7. Blank/empty qrText ────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_blankQrText_returnsInvalidQr() {
|
||||
Map<String, String> body = Map.of("qrText", "");
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "INVALID_QR");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
|
||||
// ── 8. Unrecognized/NA prefix ────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_unrecognizedPrefix_returnsWrongQrType() {
|
||||
Map<String, String> body = Map.of("qrText", "totally-unrecognized-prefix-payload");
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "WRONG_QR_TYPE");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.EventProduct;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
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.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class EventControllerCurrentConfigTest {
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private EventController controller;
|
||||
|
||||
private Event event(String tasteRewardsDoc) {
|
||||
Event e = new Event();
|
||||
e.setUuid(100L);
|
||||
e.setName("Wonderfood");
|
||||
e.setUploadTasteRewards(tasteRewardsDoc);
|
||||
return e;
|
||||
}
|
||||
|
||||
private EventProduct product(String name, double cost) {
|
||||
EventProduct p = new EventProduct();
|
||||
p.setDisplayName(name);
|
||||
p.setCostAmount(cost);
|
||||
return p;
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void returnsProductsWhenNoTasteRewardsDocument() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event("")));
|
||||
when(eventService.findEventProductByEventUuid(100L)).thenReturn(List.of(
|
||||
product("Massage Mat", 1000), product("Magnet", 800)));
|
||||
|
||||
Map<String, Object> body = controller.getCurrentEventConfig().getBody();
|
||||
|
||||
assertThat(body).doesNotContainKey("currentEventTasteRewards");
|
||||
List<EventProduct> products = (List<EventProduct>) body.get("currentEventTasteRewardsProductList");
|
||||
assertThat(products).extracting(EventProduct::getDisplayName).containsExactly("Magnet", "Massage Mat");
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsProductsAndDocumentWhenBothExist() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event("/EVENT_TASTE_REWARDS/x.png")));
|
||||
when(driveService.getPresignedUrl(any(), anyInt(), any(TimeUnit.class))).thenReturn("https://signed/x.png");
|
||||
when(eventService.findEventProductByEventUuid(100L)).thenReturn(List.of(product("Magnet", 800)));
|
||||
|
||||
Map<String, Object> body = controller.getCurrentEventConfig().getBody();
|
||||
|
||||
assertThat(body).containsEntry("currentEventTasteRewards", "https://signed/x.png");
|
||||
assertThat((List<?>) body.get("currentEventTasteRewardsProductList")).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullProductLookupReturnsEmptyList() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event(null)));
|
||||
when(eventService.findEventProductByEventUuid(100L)).thenReturn(null);
|
||||
|
||||
Map<String, Object> body = controller.getCurrentEventConfig().getBody();
|
||||
|
||||
assertThat((List<?>) body.get("currentEventTasteRewardsProductList")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void noCurrentEventReturnsEmptyBody() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getCurrentEventConfig();
|
||||
|
||||
assertThat(response.getBody()).isNull();
|
||||
}
|
||||
}
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.OrderEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.EventLuckyDrawTicket;
|
||||
import com.solvway.core.model.EventReceipt;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.mockito.ArgumentMatchers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventControllerLuckyDrawTest {
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private EventController controller;
|
||||
|
||||
private Event event() {
|
||||
Event e = new Event();
|
||||
e.setUuid(100L);
|
||||
e.setUploadLuckyDraw("ld/poster.png");
|
||||
return e;
|
||||
}
|
||||
|
||||
private Member member() {
|
||||
Member m = new Member();
|
||||
m.setUuid("200");
|
||||
return m;
|
||||
}
|
||||
|
||||
private EventReceipt receipt(LocalDateTime when, OrderEnum.EventReceiptReviewStatus status, double amount) {
|
||||
EventReceipt r = new EventReceipt();
|
||||
r.setUploadDateTime(when);
|
||||
r.setReviewStatus(status);
|
||||
r.setPurchaseAmount(amount);
|
||||
return r;
|
||||
}
|
||||
|
||||
private EventLuckyDrawTicket ticket(LocalDateTime when) {
|
||||
EventLuckyDrawTicket t = new EventLuckyDrawTicket();
|
||||
t.setCreateDateTime(when);
|
||||
return t;
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsTodayTicketCountNonPendingSpentAndPresignedPoster() {
|
||||
Event e = event();
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(e));
|
||||
when(eventService.findEventReceiptByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of(
|
||||
receipt(LocalDateTime.now(), OrderEnum.EventReceiptReviewStatus.A, 500.0),
|
||||
receipt(LocalDateTime.now(), OrderEnum.EventReceiptReviewStatus.R, 350.0),
|
||||
receipt(LocalDateTime.now(), OrderEnum.EventReceiptReviewStatus.P, 999.0),
|
||||
receipt(LocalDateTime.now().minusDays(1), OrderEnum.EventReceiptReviewStatus.A, 123.0)
|
||||
));
|
||||
when(eventService.findEventLuckyDrawTicketByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of(
|
||||
ticket(LocalDateTime.now()),
|
||||
ticket(LocalDateTime.now()),
|
||||
ticket(LocalDateTime.now().minusDays(1))
|
||||
));
|
||||
when(driveService.getPresignedUrl("ld/poster.png", 24, TimeUnit.HOURS)).thenReturn("https://signed/poster");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getLuckyDraw();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("ticketCount", 2);
|
||||
assertThat(res.getBody()).containsEntry("totalSpent", 850.0);
|
||||
assertThat(res.getBody()).containsEntry("posterUrl", "https://signed/poster");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void returns404WhenNoCurrentEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
ResponseEntity<Map<String, Object>> res = controller.getLuckyDraw();
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returns404WhenMemberNotFound() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(null);
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getLuckyDraw();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void omitsPosterUrlWhenEventHasNoPoster() {
|
||||
Event e = event();
|
||||
e.setUploadLuckyDraw(null);
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(e));
|
||||
when(eventService.findEventReceiptByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of());
|
||||
when(eventService.findEventLuckyDrawTicketByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of());
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getLuckyDraw();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).doesNotContainKey("posterUrl");
|
||||
assertThat(res.getBody()).containsEntry("ticketCount", 0);
|
||||
assertThat(res.getBody()).containsEntry("totalSpent", 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyReturnsRowsNewestFirstWithApprovedTicketsAndPresignedReceiptUrls() throws Exception {
|
||||
Event e = event();
|
||||
|
||||
EventReceipt pendingOlder = new EventReceipt();
|
||||
pendingOlder.setUuid(1L);
|
||||
pendingOlder.setUploadDateTime(java.time.LocalDateTime.now().minusHours(2));
|
||||
pendingOlder.setReviewStatus(OrderEnum.EventReceiptReviewStatus.P);
|
||||
pendingOlder.setUploadPath(List.of("r/1a.png"));
|
||||
|
||||
EventReceipt approvedNewer = new EventReceipt();
|
||||
approvedNewer.setUuid(2L);
|
||||
approvedNewer.setUploadDateTime(java.time.LocalDateTime.now().minusHours(1));
|
||||
approvedNewer.setReviewStatus(OrderEnum.EventReceiptReviewStatus.A);
|
||||
approvedNewer.setUploadPath(List.of("r/2a.png", "r/2b.png"));
|
||||
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(e));
|
||||
when(eventService.findEventReceiptByEventUuidAndMemberUuid(100L, 200L))
|
||||
.thenReturn(List.of(pendingOlder, approvedNewer));
|
||||
when(eventService.findEventLuckyDrawTicketByEventUuidAndReceiptUuid(100L, 2L))
|
||||
.thenReturn(List.of(ticket(java.time.LocalDateTime.now()), ticket(java.time.LocalDateTime.now())));
|
||||
when(driveService.getPresignedUrl("r/1a.png", 24, TimeUnit.HOURS)).thenReturn("https://s/1a");
|
||||
when(driveService.getPresignedUrl("r/2a.png", 24, TimeUnit.HOURS)).thenReturn("https://s/2a");
|
||||
when(driveService.getPresignedUrl("r/2b.png", 24, TimeUnit.HOURS)).thenReturn("https://s/2b");
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(java.time.LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getLuckyDrawHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
assertThat(body.get(0)).containsEntry("reviewStatus", "A");
|
||||
assertThat(body.get(0)).containsEntry("reviewStatusLabel", "Approved");
|
||||
assertThat(body.get(0)).containsEntry("ticketCount", 2);
|
||||
assertThat(body.get(0).get("receiptUrls")).isEqualTo(List.of("https://s/2a", "https://s/2b"));
|
||||
assertThat(body.get(1)).containsEntry("reviewStatus", "P");
|
||||
assertThat(body.get(1)).containsEntry("reviewStatusLabel", "Pending");
|
||||
assertThat(body.get(1)).containsEntry("ticketCount", 0);
|
||||
assertThat(body.get(1).get("receiptUrls")).isEqualTo(List.of("https://s/1a"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyReturns404WhenNoCurrentEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getLuckyDrawHistory();
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyReturnsEmptyListWhenNoReceiptsToday() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
when(eventService.findEventReceiptByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of());
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getLuckyDrawHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyRowHasEmptyReceiptUrlsWhenUploadPathNull() throws Exception {
|
||||
EventReceipt r = new EventReceipt();
|
||||
r.setUuid(5L);
|
||||
r.setUploadDateTime(java.time.LocalDateTime.now());
|
||||
r.setReviewStatus(OrderEnum.EventReceiptReviewStatus.P);
|
||||
r.setUploadPath(null);
|
||||
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
when(eventService.findEventReceiptByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of(r));
|
||||
when(dateTimeFormatterUtil.format(org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))).thenReturn("formatted");
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getLuckyDrawHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).hasSize(1);
|
||||
assertThat(res.getBody().get(0).get("receiptUrls")).isEqualTo(List.of());
|
||||
assertThat(res.getBody().get(0)).containsEntry("ticketCount", 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.OrderEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.EventRedeemCode;
|
||||
import com.solvway.core.model.StockistCmsProfile;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.core.utils.QrScanUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventControllerRedeemCodeHistoryTest {
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private QrScanUtil qrScanUtil;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private EventController controller;
|
||||
|
||||
private static final long MEMBER_UUID = 12345L;
|
||||
|
||||
private StockistCmsProfile profile(String name) {
|
||||
StockistCmsProfile p = new StockistCmsProfile();
|
||||
p.setStockistName(name);
|
||||
return p;
|
||||
}
|
||||
|
||||
private Event event(long uuid, String name) {
|
||||
Event e = new Event();
|
||||
e.setUuid(uuid);
|
||||
e.setName(name);
|
||||
return e;
|
||||
}
|
||||
|
||||
private EventRedeemCode redeemCode(long uuid, long eventUuid, long memberUuid, long stockistUuid,
|
||||
OrderEnum.EventRedeemCodeStatus status,
|
||||
LocalDateTime expiry, LocalDateTime redeemedDateTime,
|
||||
LocalDateTime createDateTime) {
|
||||
EventRedeemCode c = new EventRedeemCode();
|
||||
c.setUuid(uuid);
|
||||
c.setEventUuid(eventUuid);
|
||||
c.setMemberUuid(memberUuid);
|
||||
c.setStockistUuid(stockistUuid);
|
||||
c.setRedeemStatus(status);
|
||||
c.setExpiryDateTime(expiry);
|
||||
c.setRedeemedDateTime(redeemedDateTime);
|
||||
c.setCreateDateTime(createDateTime);
|
||||
c.setRedeemCode("REDEEM-" + uuid);
|
||||
return c;
|
||||
}
|
||||
|
||||
// ---------- Test 1: unresolved member ("" uuid) -> 401 ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_unresolvedMember_returns401() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("");
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
verify(eventService, never()).findEventRedeemCodeByMemberUuid(anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 2: returns only redeemed or expired codes ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_filtersToRedeemedOrExpired() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
// R code (redeemed) — should be included
|
||||
EventRedeemCode redeemed = redeemCode(1L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.R, now.plusDays(1), now, now.minusDays(2));
|
||||
// Y code expired yesterday — should be included
|
||||
EventRedeemCode expired = redeemCode(2L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.Y, now.minusDays(1), null, now.minusDays(1));
|
||||
// Y code expiring tomorrow — should be excluded
|
||||
EventRedeemCode valid = redeemCode(3L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.Y, now.plusDays(1), null, now);
|
||||
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(profile("Acme")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(redeemed, expired, valid));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
// The tomorrow code is absent
|
||||
assertThat(body).extracting("uuid").containsOnly(1L, 2L);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 3: newest first by createDateTime ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_sortedByCreateDateTimeDesc() {
|
||||
LocalDateTime older = LocalDateTime.now().minusDays(3);
|
||||
LocalDateTime newer = LocalDateTime.now().minusDays(1);
|
||||
|
||||
EventRedeemCode oldCode = redeemCode(1L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.R, null, LocalDateTime.now(), older);
|
||||
EventRedeemCode newCode = redeemCode(2L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.R, null, LocalDateTime.now(), newer);
|
||||
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(profile("Acme")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(oldCode, newCode));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
assertThat(body.get(0)).containsEntry("uuid", 2L);
|
||||
assertThat(body.get(1)).containsEntry("uuid", 1L);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 4: rows carry stockistName and eventName, no qrText ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_includesStockistNameAndEventNameWithoutQrText() throws Exception {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
EventRedeemCode code = redeemCode(1L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.R, now.minusDays(1), now, now.minusDays(2));
|
||||
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID)).thenReturn(List.of(code));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(profile("Acme Stockist")));
|
||||
when(eventService.findEventByUuid(100L)).thenReturn(Optional.of(event(100L, "Summer Fest 2026")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
Map<String, Object> row = res.getBody().get(0);
|
||||
assertThat(row).containsEntry("stockistName", "Acme Stockist");
|
||||
assertThat(row).containsEntry("eventName", "Summer Fest 2026");
|
||||
assertThat(row).doesNotContainKey("qrText");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 5: same stockist and event -> looked up once each ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_cachesStockistAndEventLookups() throws Exception {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
EventRedeemCode code1 = redeemCode(1L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.R, now.minusDays(1), now, now.minusDays(2));
|
||||
EventRedeemCode code2 = redeemCode(2L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.Y, now.minusDays(2), null, now.minusDays(3));
|
||||
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID)).thenReturn(List.of(code1, code2));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(profile("Acme Stockist")));
|
||||
when(eventService.findEventByUuid(100L)).thenReturn(Optional.of(event(100L, "Summer Fest 2026")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
verify(stockistCmsService, times(1)).findByStockistUuid("300");
|
||||
verify(eventService, times(1)).findEventByUuid(100L);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 6: empty list from service -> 200 with empty body ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_emptyList_returns200WithEmptyBody() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID)).thenReturn(List.of());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 7: never calls findCurrentEvent ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_neverCallsFindCurrentEvent() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID)).thenReturn(List.of());
|
||||
|
||||
controller.getRedeemCodeHistory();
|
||||
|
||||
verify(eventService, never()).findCurrentEvent();
|
||||
}
|
||||
}
|
||||
}
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.OrderEnum;
|
||||
import com.solvway.core.enums.PaymentEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.EventRedeemCode;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.model.StockistCmsProfile;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.core.utils.QrScanUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventControllerRedeemCodeTest {
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private QrScanUtil qrScanUtil;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private EventController controller;
|
||||
|
||||
private Event event() {
|
||||
Event e = new Event();
|
||||
e.setUuid(100L);
|
||||
return e;
|
||||
}
|
||||
|
||||
private Member member() {
|
||||
Member m = new Member();
|
||||
m.setUuid("200");
|
||||
return m;
|
||||
}
|
||||
|
||||
private EventRedeemCode redeemCode(long uuid, long eventUuid, long memberUuid, long stockistUuid,
|
||||
OrderEnum.EventRedeemCodeStatus status,
|
||||
LocalDateTime expiry, LocalDateTime createDateTime) {
|
||||
EventRedeemCode c = new EventRedeemCode();
|
||||
c.setUuid(uuid);
|
||||
c.setEventUuid(eventUuid);
|
||||
c.setMemberUuid(memberUuid);
|
||||
c.setStockistUuid(stockistUuid);
|
||||
c.setRedeemStatus(status);
|
||||
c.setExpiryDateTime(expiry);
|
||||
c.setCreateDateTime(createDateTime);
|
||||
c.setRedeemCode("REDEEM-" + uuid);
|
||||
return c;
|
||||
}
|
||||
|
||||
private void stubAuthenticatedMember() {
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
}
|
||||
|
||||
private StockistCmsProfile stockistProfile(String name) {
|
||||
StockistCmsProfile p = new StockistCmsProfile();
|
||||
p.setStockistUuid(BigInteger.valueOf(300L));
|
||||
p.setStockistName(name);
|
||||
return p;
|
||||
}
|
||||
|
||||
// ---------- GET /api/event/redeemCodes ----------
|
||||
|
||||
@Test
|
||||
void listReturnsNonExpiredCodesNewestFirstWithStockistName() throws Exception {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode older = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now().minusHours(2));
|
||||
EventRedeemCode newer = redeemCode(2L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.R,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now().minusHours(1));
|
||||
EventRedeemCode expired = redeemCode(3L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().minusHours(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByEventUuidAndMemberUuid(100L, 200L))
|
||||
.thenReturn(List.of(older, newer, expired));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(stockistProfile("Acme Stockist")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodes();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
assertThat(body.get(0)).containsEntry("uuid", 2L);
|
||||
assertThat(body.get(0)).containsEntry("redeemStatus", "R");
|
||||
assertThat(body.get(0)).containsEntry("stockistName", "Acme Stockist");
|
||||
assertThat(body.get(1)).containsEntry("uuid", 1L);
|
||||
assertThat(body.get(1)).containsEntry("redeemStatus", "Y");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReturns404WhenNoCurrentEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodes();
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReturnsEmptyListWhenNoCodes() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
when(eventService.findEventRedeemCodeByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of());
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodes();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void listOmitsStockistNameWhenLookupFails() throws Exception {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of(code));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.empty());
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodes();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody().get(0)).doesNotContainKey("stockistName");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- GET /api/event/redeemCode/{uuid} ----------
|
||||
|
||||
@Test
|
||||
void detailIncludesQrTextWhenActiveAndNotExpired() throws Exception {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(stockistProfile("Acme Stockist")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
when(authenticationService.encrypt("REDEEM-1")).thenReturn("encrypted-1");
|
||||
when(qrScanUtil.generateQrText("encrypted-1", PaymentEnum.QrScanCodeAction.RC)).thenReturn("RC_encrypted-1");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("uuid", 1L);
|
||||
assertThat(res.getBody()).containsEntry("stockistName", "Acme Stockist");
|
||||
assertThat(res.getBody()).containsEntry("redeemStatus", "Y");
|
||||
assertThat(res.getBody()).containsEntry("qrText", "RC_encrypted-1");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailOmitsQrTextWhenRedeemed() throws Exception {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.R,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(stockistProfile("Acme Stockist")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("redeemStatus", "R");
|
||||
assertThat(res.getBody()).doesNotContainKey("qrText");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailOmitsQrTextWhenExpired() throws Exception {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().minusHours(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(stockistProfile("Acme Stockist")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).doesNotContainKey("qrText");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailReturns404WhenCodeNotFound() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.empty());
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailReturns404WhenNotOwnedByMember() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 999L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailReturns404WhenNotBelongingToCurrentEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 999L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailReturns404WhenNoCurrentEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
// ---------- GET /api/event/redeemCode/{uuid}/status ----------
|
||||
|
||||
@Test
|
||||
void statusReturnsTrueWhenRedeemed() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.R,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCodeStatus(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("redeemed", true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReturnsFalseWhenActive() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCodeStatus(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("redeemed", false);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReturns404WhenNotFound() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.empty());
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCodeStatus(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReturns404WhenNotOwnedByMember() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 999L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCodeStatus(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Unit tests for the registration helper logic: canonical phone normalization
|
||||
* (duplicate-detection consistency) and failure-code → message mapping.
|
||||
*/
|
||||
class MemberControllerHelperTest {
|
||||
|
||||
@Test
|
||||
void canonicalLocalPhoneNo_stripsLeading60ThenZero() {
|
||||
assertThat(MemberController.canonicalLocalPhoneNo("123456789")).isEqualTo("123456789");
|
||||
assertThat(MemberController.canonicalLocalPhoneNo("0123456789")).isEqualTo("123456789");
|
||||
assertThat(MemberController.canonicalLocalPhoneNo("60123456789")).isEqualTo("123456789");
|
||||
}
|
||||
|
||||
@Test
|
||||
void canonicalLocalPhoneNo_nullSafe() {
|
||||
assertThat(MemberController.canonicalLocalPhoneNo(null)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void friendlyRegistrationMessage_mapsKnownCodes() {
|
||||
assertThat(MemberController.friendlyRegistrationMessage("DUPLICATE_USERNAME_ERROR"))
|
||||
.isEqualTo("This phone number is already registered. ");
|
||||
assertThat(MemberController.friendlyRegistrationMessage("NAME_ONLY_ALPHA"))
|
||||
.isEqualTo("Name contains invalid characters. ");
|
||||
assertThat(MemberController.friendlyRegistrationMessage("PHONE_NUMBER_ONLY_NUMERIC"))
|
||||
.isEqualTo("Phone number must contain digits only. ");
|
||||
}
|
||||
|
||||
@Test
|
||||
void friendlyRegistrationMessage_unknownOrNull_fallsBackToGeneric() {
|
||||
assertThat(MemberController.friendlyRegistrationMessage("SOMETHING_UNMAPPED"))
|
||||
.isEqualTo("Registration failed. ");
|
||||
assertThat(MemberController.friendlyRegistrationMessage(null))
|
||||
.isEqualTo("Registration failed. ");
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.model.OneTimePassword;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberControllerOtpTest {
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private GeoLocationHierarchyService geoLocationHierarchyService;
|
||||
@Mock private LocationHierarchyService locationHierarchyService;
|
||||
@Mock private OneTimePasswordService oneTimePasswordService;
|
||||
@Mock private SystemService systemService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
|
||||
@InjectMocks private MemberController controller;
|
||||
|
||||
private OneTimePassword otpWithCode() {
|
||||
OneTimePassword otp = new OneTimePassword();
|
||||
otp.setCode("987654321");
|
||||
otp.setPassword("246810");
|
||||
otp.setIdentityRef("member-uuid");
|
||||
otp.setShortRef("SR1");
|
||||
return otp;
|
||||
}
|
||||
|
||||
private User unverifiedUser() {
|
||||
User user = new User();
|
||||
user.setPhoneVerified(GeneralEnum.FlagYesNo.N);
|
||||
user.setEmailVerified(GeneralEnum.FlagYesNo.N);
|
||||
return user;
|
||||
}
|
||||
|
||||
private Member member() {
|
||||
Member member = new Member();
|
||||
member.setUuid("member-uuid");
|
||||
return member;
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void otpRequiredResponseExposesCodeReferenceButNotPasscode() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getUsernameFromToken("tok")).thenReturn("alice");
|
||||
when(userService.findByUsername("alice")).thenReturn(unverifiedUser());
|
||||
when(memberService.findByUsername("alice")).thenReturn(member());
|
||||
when(oneTimePasswordService.getOneTimePasswordByMember(any(), anyBoolean())).thenReturn(otpWithCode());
|
||||
when(validateUtil.maskPhoneNo(any())).thenReturn("***1234");
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getOtpRequired();
|
||||
|
||||
Map<String, Object> otpBean = (Map<String, Object>) response.getBody().get("otpBean");
|
||||
assertThat(otpBean).containsEntry("code", "987654321");
|
||||
assertThat(otpBean).containsEntry("identityRef", "member-uuid");
|
||||
assertThat(otpBean).containsEntry("shortRef", "SR1");
|
||||
assertThat(otpBean).doesNotContainKeys("password", "passwordPlain");
|
||||
assertThat(otpBean.toString()).doesNotContain("246810");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void otpRequiredResponseStillExposesNonSecretReferences() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getUsernameFromToken("tok")).thenReturn("alice");
|
||||
when(userService.findByUsername("alice")).thenReturn(unverifiedUser());
|
||||
when(memberService.findByUsername("alice")).thenReturn(member());
|
||||
when(oneTimePasswordService.getOneTimePasswordByMember(any(), anyBoolean())).thenReturn(otpWithCode());
|
||||
when(validateUtil.maskPhoneNo(any())).thenReturn("***1234");
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getOtpRequired();
|
||||
|
||||
Map<String, Object> otpBean = (Map<String, Object>) response.getBody().get("otpBean");
|
||||
assertThat(otpBean).containsEntry("maskedPhone", "***1234");
|
||||
assertThat(otpBean).containsEntry("shortRef", "SR1");
|
||||
}
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.enums.MemberEnum;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.Period;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberControllerProfileFlagTest {
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private GeoLocationHierarchyService geoLocationHierarchyService;
|
||||
@Mock private LocationHierarchyService locationHierarchyService;
|
||||
@Mock private OneTimePasswordService oneTimePasswordService;
|
||||
@Mock private SystemService systemService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
|
||||
@InjectMocks
|
||||
private MemberController controller;
|
||||
|
||||
@Test
|
||||
void getProfileIncludesEmrmProfileUpdateFlag() {
|
||||
Member m = new Member();
|
||||
m.setGender(MemberEnum.Gender.M);
|
||||
m.setEmrmProfileUpdate(GeneralEnum.FlagYesNo.N);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(m);
|
||||
when(geoLocationHierarchyService.generateAddress(any(), any())).thenReturn("");
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getProfile();
|
||||
|
||||
assertThat(res.getBody()).containsEntry("emrmProfileUpdate", "N");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getProfileDefaultsFlagToNWhenUnset() {
|
||||
Member m = new Member();
|
||||
m.setGender(MemberEnum.Gender.M);
|
||||
// emrmProfileUpdate left null
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(m);
|
||||
when(geoLocationHierarchyService.generateAddress(any(), any())).thenReturn("");
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getProfile();
|
||||
|
||||
assertThat(res.getBody()).containsEntry("emrmProfileUpdate", "N");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void editProfileSetsEmrmProfileUpdateToYOnSave() {
|
||||
Member m = new Member();
|
||||
m.setPrefix("MY");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(m);
|
||||
when(validateUtil.periodBtwLocalDate(any(), any())).thenReturn(Period.ofYears(30));
|
||||
JSONObject geo = new JSONObject();
|
||||
geo.put("valid", true);
|
||||
when(geoLocationHierarchyService.validateGeoLocationById(any())).thenReturn(geo);
|
||||
when(locationHierarchyService.findByCode(any())).thenReturn(null);
|
||||
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("name", "Jane");
|
||||
body.put("surname", "Doe");
|
||||
body.put("email", "jane@example.com");
|
||||
body.put("dob", "1990-01-01");
|
||||
body.put("gender", "M");
|
||||
body.put("addressLocation", "loc1");
|
||||
body.put("addressDetails", "1 Main St");
|
||||
body.put("postCode", "");
|
||||
|
||||
controller.editProfile(body);
|
||||
|
||||
ArgumentCaptor<Member> saved = ArgumentCaptor.forClass(Member.class);
|
||||
verify(memberService).save(saved.capture());
|
||||
assertThat(saved.getValue().getEmrmProfileUpdate()).isEqualTo(GeneralEnum.FlagYesNo.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberControllerReferralTest {
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private GeoLocationHierarchyService geoLocationHierarchyService;
|
||||
@Mock private LocationHierarchyService locationHierarchyService;
|
||||
@Mock private OneTimePasswordService oneTimePasswordService;
|
||||
@Mock private SystemService systemService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
@Mock private TastefullyPointService tastefullyPointService;
|
||||
|
||||
@InjectMocks
|
||||
private MemberController controller;
|
||||
|
||||
@Test
|
||||
void getReferralLinkReturnsAppRegisterUrl() {
|
||||
ReflectionTestUtils.setField(controller, "customerPortalBaseUrl", "https://app.example.com");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
|
||||
ResponseEntity<String> res = controller.getReferralLink();
|
||||
|
||||
assertThat(res.getStatusCode().is2xxSuccessful()).isTrue();
|
||||
assertThat(res.getBody()).isEqualTo("https://app.example.com/register?ref=M1");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getReferralLinkReturnsNotFoundWhenMemberCodeBlank() {
|
||||
ReflectionTestUtils.setField(controller, "customerPortalBaseUrl", "https://app.example.com");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("");
|
||||
|
||||
ResponseEntity<String> res = controller.getReferralLink();
|
||||
|
||||
assertThat(res.getStatusCode().is4xxClientError()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getReferralStatsReturnsJoinedAndEarnedWhenBothSubCallsSucceed() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("UUID1");
|
||||
when(memberService.countReferralsBySponsor("M1")).thenReturn(4);
|
||||
when(tastefullyPointService.sumReferralEarned("UUID1")).thenReturn(150.0d);
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getReferralStats();
|
||||
|
||||
assertThat(res.getStatusCode().is2xxSuccessful()).isTrue();
|
||||
assertThat(res.getBody()).containsEntry("joined", 4L).containsEntry("earned", 150.0d);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getReferralStatsDegradesGracefullyWhenJoinedLookupThrows() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("UUID1");
|
||||
when(memberService.countReferralsBySponsor("M1")).thenThrow(new RuntimeException("boom"));
|
||||
when(tastefullyPointService.sumReferralEarned("UUID1")).thenReturn(150.0d);
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getReferralStats();
|
||||
|
||||
assertThat(res.getStatusCode().is2xxSuccessful()).isTrue();
|
||||
assertThat(res.getBody()).containsEntry("joined", 0L).containsEntry("earned", 150.0d);
|
||||
}
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
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.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberControllerSponsorValidationTest {
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private GeoLocationHierarchyService geoLocationHierarchyService;
|
||||
@Mock private LocationHierarchyService locationHierarchyService;
|
||||
@Mock private OneTimePasswordService oneTimePasswordService;
|
||||
@Mock private SystemService systemService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
@Mock private TastefullyPointService tastefullyPointService;
|
||||
|
||||
@InjectMocks
|
||||
private MemberController controller;
|
||||
|
||||
@Test
|
||||
void validSponsorReturnsSponsorId() {
|
||||
when(memberService.existsActiveByMemberCode("M1")).thenReturn(true);
|
||||
Map<String, String> response = new HashMap<>();
|
||||
|
||||
String result = controller.validateAndNormalizeSponsorId("M1", response);
|
||||
|
||||
assertThat(result).isEqualTo("M1");
|
||||
assertThat(response).doesNotContainKey("errorMessage");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownOrInactiveSponsorReturnsNullWithError() {
|
||||
when(memberService.existsActiveByMemberCode("M1")).thenReturn(false);
|
||||
Map<String, String> response = new HashMap<>();
|
||||
|
||||
String result = controller.validateAndNormalizeSponsorId("M1", response);
|
||||
|
||||
assertThat(result).isNull();
|
||||
assertThat(response).containsEntry("result", "false");
|
||||
assertThat(response).containsEntry("errorMessage", "Invalid sponsor code. ");
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankSponsorReturnsDefaultCodeWithoutLookup() {
|
||||
Map<String, String> response = new HashMap<>();
|
||||
|
||||
String result = controller.validateAndNormalizeSponsorId("", response);
|
||||
|
||||
assertThat(result).isEqualTo("00000000");
|
||||
assertThat(response).isEmpty();
|
||||
verifyNoInteractions(memberService);
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.mobile.api.model.AppBanner;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
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.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PublicContentControllerBannerTest {
|
||||
|
||||
@Mock private BulletinService bulletinService;
|
||||
@Mock private AppBannerService appBannerService;
|
||||
@Mock private EventScheduleService eventScheduleService;
|
||||
@Mock private ArticleService articleService;
|
||||
@Mock private AlbumService albumService;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private HelpCenterService helpCenterService;
|
||||
@Mock private SystemService systemService;
|
||||
|
||||
@InjectMocks
|
||||
private PublicContentController controller;
|
||||
|
||||
@Test
|
||||
void getBannersReturnsActiveBanners() {
|
||||
when(appBannerService.findActive())
|
||||
.thenReturn(List.of(new AppBanner(1L, "Grand sale", "/store", "PROMO", 0)));
|
||||
|
||||
ResponseEntity<List<AppBanner>> res = controller.getBanners();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).extracting(AppBanner::getMessage).containsExactly("Grand sale");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getBannersReturnsEmptyWhenNoneActive() {
|
||||
when(appBannerService.findActive()).thenReturn(List.of());
|
||||
|
||||
ResponseEntity<List<AppBanner>> res = controller.getBanners();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.mobile.api.dto.HelpCenterContentResponse;
|
||||
import com.solvway.mobile.api.dto.HelpCenterNode;
|
||||
import com.solvway.mobile.api.dto.HelpCenterTreeResponse;
|
||||
import com.solvway.mobile.api.service.AlbumService;
|
||||
import com.solvway.mobile.api.service.AppBannerService;
|
||||
import com.solvway.mobile.api.service.AppPromoService;
|
||||
import com.solvway.mobile.api.service.ArticleService;
|
||||
import com.solvway.mobile.api.service.BulletinService;
|
||||
import com.solvway.mobile.api.service.EventScheduleService;
|
||||
import com.solvway.mobile.api.service.HelpCenterService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import com.solvway.mobile.api.service.SystemService;
|
||||
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.test.web.servlet.MockMvc;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@WebMvcTest(controllers = PublicContentController.class)
|
||||
class PublicContentControllerHelpCenterTest {
|
||||
|
||||
@Autowired MockMvc mockMvc;
|
||||
|
||||
@MockBean HelpCenterService helpCenterService;
|
||||
@MockBean BulletinService bulletinService;
|
||||
@MockBean AppBannerService appBannerService;
|
||||
@MockBean AppPromoService appPromoService;
|
||||
@MockBean EventScheduleService eventScheduleService;
|
||||
@MockBean ArticleService articleService;
|
||||
@MockBean AlbumService albumService;
|
||||
@MockBean StockistCmsService stockistCmsService;
|
||||
@MockBean SystemService systemService;
|
||||
|
||||
@Test
|
||||
void getHelpCenterTree_returns200WithCategories() throws Exception {
|
||||
HelpCenterNode n = new HelpCenterNode(
|
||||
BigInteger.valueOf(10), BigInteger.valueOf(1), "Account", 1, List.of());
|
||||
when(helpCenterService.getTree(eq("en_US")))
|
||||
.thenReturn(new HelpCenterTreeResponse("en_US", List.of(n)));
|
||||
|
||||
mockMvc.perform(get("/api/public/helpCenter").param("locale", "en_US"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.locale").value("en_US"))
|
||||
.andExpect(jsonPath("$.categories[0].label").value("Account"))
|
||||
.andExpect(jsonPath("$.categories[0].uuid").value(10))
|
||||
.andExpect(jsonPath("$.categories[0].sortIndex").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHelpCenterTree_defaultsLocaleToEnUs_whenOmitted() throws Exception {
|
||||
when(helpCenterService.getTree(eq("en_US")))
|
||||
.thenReturn(new HelpCenterTreeResponse("en_US", List.of()));
|
||||
|
||||
mockMvc.perform(get("/api/public/helpCenter"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.locale").value("en_US"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHelpCenterContent_returns200WhenContentPresent() throws Exception {
|
||||
when(helpCenterService.getLeafContent(eq(BigInteger.valueOf(42)), eq("en_US")))
|
||||
.thenReturn(Optional.of(new HelpCenterContentResponse(
|
||||
BigInteger.valueOf(42), "en_US", null, "<p>Hi</p>")));
|
||||
|
||||
mockMvc.perform(get("/api/public/helpCenter/42/content").param("locale", "en_US"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.content").value("<p>Hi</p>"))
|
||||
.andExpect(jsonPath("$.redirectUrl").value(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHelpCenterContent_returns200WhenRedirectPresent() throws Exception {
|
||||
when(helpCenterService.getLeafContent(eq(BigInteger.valueOf(42)), eq("en_US")))
|
||||
.thenReturn(Optional.of(new HelpCenterContentResponse(
|
||||
BigInteger.valueOf(42), "en_US", "https://example.com", null)));
|
||||
|
||||
mockMvc.perform(get("/api/public/helpCenter/42/content").param("locale", "en_US"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.redirectUrl").value("https://example.com"))
|
||||
.andExpect(jsonPath("$.content").value(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHelpCenterContent_returns404WhenServiceReturnsEmpty() throws Exception {
|
||||
when(helpCenterService.getLeafContent(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
mockMvc.perform(get("/api/public/helpCenter/42/content"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.mobile.api.service.*;
|
||||
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.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PublicContentControllerMessagesTest {
|
||||
|
||||
@Mock private BulletinService bulletinService;
|
||||
@Mock private EventScheduleService eventScheduleService;
|
||||
@Mock private ArticleService articleService;
|
||||
@Mock private AlbumService albumService;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private HelpCenterService helpCenterService;
|
||||
@Mock private SystemService systemService;
|
||||
|
||||
@InjectMocks
|
||||
private PublicContentController controller;
|
||||
|
||||
@Test
|
||||
void getMessagesReturnsCatalogForLocale() {
|
||||
when(systemService.findMessageCatalog("A", "en_US"))
|
||||
.thenReturn(Map.of("FirstName", "First Name"));
|
||||
|
||||
ResponseEntity<Map<String, String>> res = controller.getMessages("en_US");
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("FirstName", "First Name");
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.mobile.api.model.AppPromo;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
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.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PublicContentControllerPromoTest {
|
||||
|
||||
@Mock private BulletinService bulletinService;
|
||||
@Mock private AppBannerService appBannerService;
|
||||
@Mock private AppPromoService appPromoService;
|
||||
@Mock private EventScheduleService eventScheduleService;
|
||||
@Mock private ArticleService articleService;
|
||||
@Mock private AlbumService albumService;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private HelpCenterService helpCenterService;
|
||||
@Mock private SystemService systemService;
|
||||
|
||||
@InjectMocks
|
||||
private PublicContentController controller;
|
||||
|
||||
@Test
|
||||
void getPromosReturnsActivePromos() {
|
||||
when(appPromoService.findActive())
|
||||
.thenReturn(List.of(new AppPromo(1L, "IMAGE", "https://cdn/app-promo/a.jpg", "/store",
|
||||
"Grand sale", "Grand sale banner", null, null, true, 0)));
|
||||
|
||||
ResponseEntity<List<AppPromo>> res = controller.getPromos();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).extracting(AppPromo::getCaption).containsExactly("Grand sale");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPromosReturnsEmptyWhenNoneActive() {
|
||||
when(appPromoService.findActive()).thenReturn(List.of());
|
||||
|
||||
ResponseEntity<List<AppPromo>> res = controller.getPromos();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.model.Email;
|
||||
import com.solvway.mobile.api.model.form.ContactUsRequest;
|
||||
import com.solvway.mobile.api.service.EmailService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PublicFormControllerEscapingTest {
|
||||
|
||||
@Mock private EmailService emailService;
|
||||
|
||||
@InjectMocks private PublicFormController controller;
|
||||
|
||||
@Test
|
||||
void contactUsEscapesHtmlInUserSuppliedFields() {
|
||||
when(emailService.send(any())).thenReturn(Optional.of(new Email()));
|
||||
|
||||
ContactUsRequest request = new ContactUsRequest();
|
||||
request.setName("<script>alert(1)</script>");
|
||||
request.setEmail("attacker@example.com");
|
||||
request.setMessage("<img src=x onerror=alert(2)>");
|
||||
|
||||
controller.contactUs(request);
|
||||
|
||||
ArgumentCaptor<Email> captor = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService).send(captor.capture());
|
||||
String body = captor.getValue().getBody();
|
||||
|
||||
assertThat(body).doesNotContain("<script>");
|
||||
assertThat(body).doesNotContain("<img src=x");
|
||||
assertThat(body).contains("<script>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void contactUsEscapesHtmlInTheSubjectLine() {
|
||||
when(emailService.send(any())).thenReturn(Optional.of(new Email()));
|
||||
|
||||
ContactUsRequest request = new ContactUsRequest();
|
||||
request.setName("<b>bold</b>");
|
||||
request.setEmail("user@example.com");
|
||||
request.setMessage("hello");
|
||||
|
||||
controller.contactUs(request);
|
||||
|
||||
ArgumentCaptor<Email> captor = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService).send(captor.capture());
|
||||
|
||||
assertThat(captor.getValue().getSubject()).doesNotContain("<b>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void contactUsStillDeliversTheLegibleMessageText() {
|
||||
when(emailService.send(any())).thenReturn(Optional.of(new Email()));
|
||||
|
||||
ContactUsRequest request = new ContactUsRequest();
|
||||
request.setName("Alice");
|
||||
request.setEmail("alice@example.com");
|
||||
request.setMessage("Please call me");
|
||||
|
||||
controller.contactUs(request);
|
||||
|
||||
ArgumentCaptor<Email> captor = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService).send(captor.capture());
|
||||
String body = captor.getValue().getBody();
|
||||
|
||||
assertThat(body).contains("Alice");
|
||||
assertThat(body).contains("Please call me");
|
||||
}
|
||||
}
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.model.MemberVoucher;
|
||||
import com.solvway.core.model.MemberVoucherEligibility;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.service.MemberVoucherService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Ownership always comes from the token, never the request. Ineligible vouchers are still
|
||||
* returned, carrying a reason, so the member sees why rather than an empty list.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class VoucherControllerTest {
|
||||
|
||||
@Mock private MemberVoucherService memberVoucherService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private VoucherController controller;
|
||||
|
||||
/** Token -> memberCode -> Member, exactly as EventControllerRedeemCodeTest does it. */
|
||||
private void stubAuthenticatedMember() {
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M001");
|
||||
when(memberService.findByMemberCode("M001")).thenReturn(member());
|
||||
}
|
||||
|
||||
private static MemberVoucherEligibility eligibility(long uuid, boolean redeemable, String reason) {
|
||||
return eligibility(uuid, redeemable, reason, null);
|
||||
}
|
||||
|
||||
private static MemberVoucherEligibility eligibility(long uuid, boolean redeemable, String reason, String uploadPath) {
|
||||
MemberVoucher v = new MemberVoucher();
|
||||
v.setUuid(uuid);
|
||||
v.setName("New First-Time User");
|
||||
v.setCurrencySymbol("RM");
|
||||
v.setAmount(10d);
|
||||
v.setUploadPath(uploadPath);
|
||||
MemberVoucherEligibility e = new MemberVoucherEligibility();
|
||||
e.setVoucher(v);
|
||||
e.setRedeemable(redeemable);
|
||||
e.setReason(reason);
|
||||
return e;
|
||||
}
|
||||
|
||||
private static Member member() {
|
||||
Member m = new Member();
|
||||
m.setUuid("900");
|
||||
m.setMemberCode("M001");
|
||||
m.setEmrmProfileUpdate(GeneralEnum.FlagYesNo.Y);
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReturnsEveryVoucherWithItsRedeemableFlagAndReason() {
|
||||
when(memberVoucherService.findEligibility(900L, true)).thenReturn(List.of(
|
||||
eligibility(1L, true, null),
|
||||
eligibility(2L, false, "ALREADY_REDEEMED")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getBody()).hasSize(2);
|
||||
assertThat(response.getBody().get(0)).containsEntry("redeemable", true);
|
||||
assertThat(response.getBody().get(0)).containsEntry("amount", 10d);
|
||||
assertThat(response.getBody().get(1)).containsEntry("reason", "ALREADY_REDEEMED");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnauthenticatedRequestGetsNotFoundAndNeverQueriesVouchers() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn(null);
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getStatusCode().is4xxClientError()).isTrue();
|
||||
assertThat(response.getBody()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReportsRedeemedWhenTheVoucherIsNoLongerRedeemableBecauseItWasRedeemed() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, false, "ALREADY_REDEEMED")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucherStatus(1L);
|
||||
|
||||
assertThat(response.getBody()).containsEntry("redeemed", true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusIsNotRedeemedWhileTheVoucherIsStillRedeemable() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucherStatus(1L);
|
||||
|
||||
assertThat(response.getBody()).containsEntry("redeemed", false);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReportsRedeemableTrueAndNoReasonWhileStillRedeemable() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucherStatus(1L);
|
||||
|
||||
assertThat(response.getBody()).containsEntry("redeemable", true);
|
||||
assertThat(response.getBody()).containsKey("reason");
|
||||
assertThat(response.getBody().get("reason")).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReportsNotRedeemableWithReasonWhenExpired() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, false, "EXPIRED")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucherStatus(1L);
|
||||
|
||||
assertThat(response.getBody()).containsEntry("redeemed", false);
|
||||
assertThat(response.getBody()).containsEntry("redeemable", false);
|
||||
assertThat(response.getBody()).containsEntry("reason", "EXPIRED");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVoucherThatIsNotTheMembersReturnsNotFound() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucher(999L);
|
||||
|
||||
assertThat(response.getStatusCode().is4xxClientError()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVoucherWithAnUploadPathReturnsItVerbatimAsImageUrl() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null, "https://cdn.example.com/member-voucher/image.png")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getBody().get(0))
|
||||
.containsEntry("imageUrl", "https://cdn.example.com/member-voucher/image.png");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVoucherWithANullUploadPathReturnsNullImageUrl() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getBody().get(0)).containsEntry("imageUrl", null);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVoucherWithABlankUploadPathReturnsNullImageUrl() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null, " ")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getBody().get(0)).containsEntry("imageUrl", null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Snowflake uuids are ~3e18, far past JavaScript's Number.MAX_SAFE_INTEGER (~9e15). Serialised
|
||||
* as a JSON number, the browser's JSON.parse silently rounds it, and the id the customer-portal
|
||||
* then puts in a URL is a voucher that does not exist. Emitting a string is what keeps the id
|
||||
* intact across the wire; the long @PathVariable parses it back without any change.
|
||||
*/
|
||||
private static final long SNOWFLAKE_UUID = 3271922645582381056L;
|
||||
|
||||
@Test
|
||||
void listEmitsTheVoucherUuidAsAStringSoLargeIdsSurviveJsonParse() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(SNOWFLAKE_UUID, true, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getBody().get(0)).containsEntry("uuid", "3271922645582381056");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailEmitsTheVoucherUuidAsAStringSoLargeIdsSurviveJsonParse() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(SNOWFLAKE_UUID, true, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucher(SNOWFLAKE_UUID);
|
||||
|
||||
assertThat(response.getBody()).containsEntry("uuid", "3271922645582381056");
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.model.AppBanner;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AppBannerServiceTest {
|
||||
|
||||
@Mock
|
||||
private RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
private AppBannerService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new AppBannerService(restTemplateUtil);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findActiveReturnsBannerList() {
|
||||
AppBanner banner = new AppBanner(1L, "Grand sale", "/store", "PROMO", 0);
|
||||
when(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_BANNER_FIND_ACTIVE))
|
||||
.thenReturn("http://system/appBanner/findActive");
|
||||
when(restTemplateUtil.<List<AppBanner>>getForEntity(eq("http://system/appBanner/findActive"), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(banner)));
|
||||
|
||||
List<AppBanner> result = service.findActive();
|
||||
|
||||
assertThat(result).extracting(AppBanner::getMessage).containsExactly("Grand sale");
|
||||
assertThat(result).extracting(AppBanner::getStyle).containsExactly("PROMO");
|
||||
}
|
||||
|
||||
@Test
|
||||
void findActiveReturnsEmptyOnNonOkResponse() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_BANNER_FIND_ACTIVE))
|
||||
.thenReturn("http://system/appBanner/findActive");
|
||||
when(restTemplateUtil.<List<AppBanner>>getForEntity(any(String.class), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
|
||||
|
||||
List<AppBanner> result = service.findActive();
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.model.AppPromo;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AppPromoServiceTest {
|
||||
|
||||
@Mock
|
||||
private RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
private AppPromoService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new AppPromoService(restTemplateUtil);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findActiveReturnsPromoList() {
|
||||
AppPromo promo = new AppPromo(1L, "IMAGE", "https://cdn/app-promo/a.jpg", "/store", "Grand sale",
|
||||
"Grand sale banner", LocalDateTime.now().minusDays(1), LocalDateTime.now().plusDays(1), true, 0);
|
||||
when(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_PROMO_FIND_ACTIVE))
|
||||
.thenReturn("http://system/appPromo/findActive");
|
||||
when(restTemplateUtil.<List<AppPromo>>getForEntity(eq("http://system/appPromo/findActive"), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(promo)));
|
||||
|
||||
List<AppPromo> result = service.findActive();
|
||||
|
||||
assertThat(result).extracting(AppPromo::getMediaUrl).containsExactly("https://cdn/app-promo/a.jpg");
|
||||
assertThat(result).extracting(AppPromo::getCaption).containsExactly("Grand sale");
|
||||
}
|
||||
|
||||
@Test
|
||||
void findActiveReturnsEmptyOnNonOkResponse() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_PROMO_FIND_ACTIVE))
|
||||
.thenReturn("http://system/appPromo/findActive");
|
||||
when(restTemplateUtil.<List<AppPromo>>getForEntity(any(String.class), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
|
||||
|
||||
List<AppPromo> result = service.findActive();
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void findActiveReturnsEmptyOnNullBody() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_PROMO_FIND_ACTIVE))
|
||||
.thenReturn("http://system/appPromo/findActive");
|
||||
when(restTemplateUtil.<List<AppPromo>>getForEntity(any(String.class), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(ResponseEntity.ok(null));
|
||||
|
||||
List<AppPromo> result = service.findActive();
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import com.solvway.mobile.api.util.redis.RedisUtil;
|
||||
import com.solvway.mobile.api.util.redis.TokenCacheKeyUtil;
|
||||
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 static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AuthenticationServiceCacheKeyTest {
|
||||
|
||||
private static final String TOKEN = "eyJhbGciOiJIUzUxMiJ9.payload.signature";
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private RestTemplateCustomUtil restTemplateUtil;
|
||||
@Mock private RedisUtil<String> redisUtil;
|
||||
|
||||
@InjectMocks private AuthenticationService authenticationService;
|
||||
|
||||
@Test
|
||||
void usernameLookupUsesHashedTokenAsCacheKey() {
|
||||
String expectedKey = "mobile-api:auth:token-username:" + TokenCacheKeyUtil.hashToken(TOKEN);
|
||||
when(redisUtil.checkKeyExist(expectedKey)).thenReturn(true);
|
||||
when(redisUtil.getValue(expectedKey)).thenReturn("alice");
|
||||
|
||||
assertThat(authenticationService.getUsernameFromToken(TOKEN)).isEqualTo("alice");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cacheKeyNeverContainsTheRawToken() {
|
||||
String key = "mobile-api:auth:token-username:" + TokenCacheKeyUtil.hashToken(TOKEN);
|
||||
assertThat(key).doesNotContain(TOKEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void memberCodeLookupUsesHashedTokenAsCacheKey() {
|
||||
String expectedKey = "mobile-api:auth:token-member-code:" + TokenCacheKeyUtil.hashToken(TOKEN);
|
||||
when(redisUtil.checkKeyExist(expectedKey)).thenReturn(true);
|
||||
when(redisUtil.getValue(expectedKey)).thenReturn("M001");
|
||||
|
||||
assertThat(authenticationService.getMemberCodeFromToken(TOKEN)).isEqualTo("M001");
|
||||
}
|
||||
|
||||
@Test
|
||||
void memberUuidLookupUsesHashedTokenAsCacheKey() {
|
||||
String expectedKey = "mobile-api:auth:token-member-uuid:" + TokenCacheKeyUtil.hashToken(TOKEN);
|
||||
when(redisUtil.checkKeyExist(expectedKey)).thenReturn(true);
|
||||
when(redisUtil.getValue(expectedKey)).thenReturn("uuid-1");
|
||||
|
||||
assertThat(authenticationService.getMemberUuidFromToken(TOKEN)).isEqualTo("uuid-1");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.model.Email;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
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 org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EmailServiceTest {
|
||||
|
||||
@Mock
|
||||
private PubSubTemplate pubSubTemplate;
|
||||
|
||||
@Mock
|
||||
private PubSubUtil pubSubUtil;
|
||||
|
||||
@InjectMocks
|
||||
private EmailService emailService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ReflectionTestUtils.setField(emailService, "emailSaveRequestTopic", "email-save-request-topic");
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_publishesEmailToSaveRequestTopicAndReturnsEmail() {
|
||||
Email email = new Email();
|
||||
email.setSubject("Test Subject");
|
||||
|
||||
Optional<Email> result = emailService.send(email);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
verify(pubSubUtil).publishMessageWithCustomObjectMapper(
|
||||
eq(pubSubTemplate), eq("email-save-request-topic"), eq(email));
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_returnsEmptyWhenPublishThrows() {
|
||||
Email email = new Email();
|
||||
doThrow(new RuntimeException("publish failed"))
|
||||
.when(pubSubUtil).publishMessageWithCustomObjectMapper(any(), any(), any());
|
||||
|
||||
Optional<Email> result = emailService.send(email);
|
||||
|
||||
assertFalse(result.isPresent());
|
||||
}
|
||||
}
|
||||
+370
@@ -0,0 +1,370 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.GenericHierarchy;
|
||||
import com.solvway.core.model.GenericPostContent;
|
||||
import com.solvway.core.model.HelpCenterPost;
|
||||
import com.solvway.mobile.api.cache.MessageLabelCache;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.HelpCenterContentResponse;
|
||||
import com.solvway.mobile.api.dto.HelpCenterNode;
|
||||
import com.solvway.mobile.api.dto.HelpCenterTreeResponse;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
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.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class HelpCenterServiceTest {
|
||||
|
||||
@Mock
|
||||
RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
@Mock
|
||||
MessageLabelCache messageLabelCache;
|
||||
|
||||
@InjectMocks
|
||||
HelpCenterService helpCenterService;
|
||||
|
||||
private static final BigInteger UUID = BigInteger.valueOf(42);
|
||||
private static final String LOCALE = "en";
|
||||
|
||||
@Test
|
||||
void getLeafContent_returnsContent_whenLocalizedPostContentExists() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
HelpCenterPost post = new HelpCenterPost();
|
||||
post.setGenericPostUuid(BigInteger.valueOf(99));
|
||||
post.setRedirectUrl(null);
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
eq(HelpCenterPost.class), eq(UUID)))
|
||||
.thenReturn(ResponseEntity.ok(post));
|
||||
|
||||
GenericPostContent content = new GenericPostContent();
|
||||
content.setContent("Some help content");
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE),
|
||||
eq(GenericPostContent.class), eq(BigInteger.valueOf(99)), eq(LOCALE)))
|
||||
.thenReturn(ResponseEntity.ok(content));
|
||||
|
||||
Optional<HelpCenterContentResponse> result = helpCenterService.getLeafContent(UUID, LOCALE);
|
||||
|
||||
assertThat(result).isPresent();
|
||||
assertThat(result.get().content()).isEqualTo("Some help content");
|
||||
assertThat(result.get().redirectUrl()).isNull();
|
||||
assertThat(result.get().uuid()).isEqualTo(UUID);
|
||||
assertThat(result.get().locale()).isEqualTo(LOCALE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLeafContent_returnsRedirectUrl_whenPostHasRedirect() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
HelpCenterPost post = new HelpCenterPost();
|
||||
post.setRedirectUrl("https://example.com/redirect");
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
eq(HelpCenterPost.class), eq(UUID)))
|
||||
.thenReturn(ResponseEntity.ok(post));
|
||||
|
||||
Optional<HelpCenterContentResponse> result = helpCenterService.getLeafContent(UUID, LOCALE);
|
||||
|
||||
assertThat(result).isPresent();
|
||||
assertThat(result.get().redirectUrl()).isEqualTo("https://example.com/redirect");
|
||||
assertThat(result.get().content()).isNull();
|
||||
|
||||
verify(restTemplateUtil, never()).getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE),
|
||||
eq(GenericPostContent.class), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLeafContent_returnsEmpty_whenPostNotFound() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
eq(HelpCenterPost.class), eq(UUID)))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
|
||||
Optional<HelpCenterContentResponse> result = helpCenterService.getLeafContent(UUID, LOCALE);
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLeafContent_returnsEmpty_whenPostNotOk() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
eq(HelpCenterPost.class), eq(UUID)))
|
||||
.thenReturn(ResponseEntity.status(HttpStatus.NOT_FOUND).build());
|
||||
|
||||
Optional<HelpCenterContentResponse> result = helpCenterService.getLeafContent(UUID, LOCALE);
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLeafContent_returnsEmpty_whenNoLocalizedContent() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
HelpCenterPost post = new HelpCenterPost();
|
||||
post.setGenericPostUuid(BigInteger.valueOf(99));
|
||||
post.setRedirectUrl(null);
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
eq(HelpCenterPost.class), eq(UUID)))
|
||||
.thenReturn(ResponseEntity.ok(post));
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE),
|
||||
eq(GenericPostContent.class), eq(BigInteger.valueOf(99)), eq(LOCALE)))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
|
||||
Optional<HelpCenterContentResponse> result = helpCenterService.getLeafContent(UUID, LOCALE);
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
// ─── getTree helpers ───────────────────────────────────────────────────────
|
||||
|
||||
private static GenericHierarchy node(long uuid, long parentUuid, String name, String tag,
|
||||
int sortIndex, String status, String sysManaged,
|
||||
List<GenericHierarchy> children) {
|
||||
GenericHierarchy gh = new GenericHierarchy();
|
||||
gh.setUuid(BigInteger.valueOf(uuid));
|
||||
gh.setParentUuid(BigInteger.valueOf(parentUuid));
|
||||
gh.setName(name);
|
||||
gh.setMessageTag(tag);
|
||||
gh.setSortIndex(sortIndex);
|
||||
gh.setStatus(GeneralEnum.FlagYesNo.valueOf(status));
|
||||
gh.setSysManaged(GeneralEnum.FlagYesNo.valueOf(sysManaged));
|
||||
gh.setHierarchyType(GeneralEnum.GenericHierarchyType.HC);
|
||||
gh.setChildList(children);
|
||||
return gh;
|
||||
}
|
||||
|
||||
private void stubUrlPassthrough() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
}
|
||||
|
||||
private void stubRoot(GenericHierarchy root) {
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_HIERARCHY_FIND_ROOT_BY_TYPE),
|
||||
eq(GenericHierarchy.class), eq(GeneralEnum.GenericHierarchyType.HC)))
|
||||
.thenReturn(ResponseEntity.ok(root));
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_HIERARCHY_FIND_FULL_BY_TYPE_AND_UUID),
|
||||
eq(GenericHierarchy.class), eq(GeneralEnum.GenericHierarchyType.HC), eq(root.getUuid())))
|
||||
.thenReturn(ResponseEntity.ok(root));
|
||||
}
|
||||
|
||||
private void stubLabel(String code, String locale, String label) {
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
eq(String.class), eq(code), eq(locale)))
|
||||
.thenReturn(ResponseEntity.ok(label));
|
||||
}
|
||||
|
||||
private void stubLabelNotFound(String code, String locale) {
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
eq(String.class), eq(code), eq(locale)))
|
||||
.thenReturn(ResponseEntity.status(HttpStatus.NOT_FOUND).build());
|
||||
}
|
||||
|
||||
// ─── getTree tests ─────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void getTree_returnsEmptyCategories_whenNoHcRoot() {
|
||||
stubUrlPassthrough();
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_HIERARCHY_FIND_ROOT_BY_TYPE),
|
||||
eq(GenericHierarchy.class), eq(GeneralEnum.GenericHierarchyType.HC)))
|
||||
.thenReturn(ResponseEntity.ok(null));
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.locale()).isEqualTo("en_US");
|
||||
assertThat(result.categories()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTree_stripsRoot_returnsTopLevelChildrenSortedBySortIndex() {
|
||||
stubUrlPassthrough();
|
||||
|
||||
GenericHierarchy leaf1 = node(11, 1, "Cat B", "TAG.CAT_B", 2, "Y", "N", List.of());
|
||||
GenericHierarchy leaf2 = node(12, 1, "Cat A", "TAG.CAT_A", 1, "Y", "N", List.of());
|
||||
GenericHierarchy root = node(1, 0, "HC Root", null, 0, "Y", "Y", List.of(leaf1, leaf2));
|
||||
|
||||
stubRoot(root);
|
||||
|
||||
when(messageLabelCache.get("TAG.CAT_B", "en_US")).thenReturn(Optional.empty());
|
||||
when(messageLabelCache.get("TAG.CAT_A", "en_US")).thenReturn(Optional.empty());
|
||||
|
||||
stubLabel("TAG.CAT_B", "en_US", "Category B");
|
||||
stubLabel("TAG.CAT_A", "en_US", "Category A");
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.locale()).isEqualTo("en_US");
|
||||
assertThat(result.categories()).hasSize(2);
|
||||
// sorted by sortIndex: leaf2 (1) before leaf1 (2)
|
||||
assertThat(result.categories().get(0).label()).isEqualTo("Category A");
|
||||
assertThat(result.categories().get(1).label()).isEqualTo("Category B");
|
||||
|
||||
verify(messageLabelCache).put("TAG.CAT_A", "en_US", "Category A");
|
||||
verify(messageLabelCache).put("TAG.CAT_B", "en_US", "Category B");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTree_recursesArbitraryDepth() {
|
||||
stubUrlPassthrough();
|
||||
|
||||
GenericHierarchy leaf = node(30, 20, "Leaf", "TAG.LEAF", 1, "Y", "N", List.of());
|
||||
GenericHierarchy mid = node(20, 10, "Mid", "TAG.MID", 1, "Y", "N", List.of(leaf));
|
||||
GenericHierarchy top = node(10, 1, "Top", "TAG.TOP", 1, "Y", "N", List.of(mid));
|
||||
GenericHierarchy root = node(1, 0, "HC Root", null, 0, "Y", "Y", List.of(top));
|
||||
|
||||
stubRoot(root);
|
||||
|
||||
when(messageLabelCache.get("TAG.TOP", "en_US")).thenReturn(Optional.empty());
|
||||
when(messageLabelCache.get("TAG.MID", "en_US")).thenReturn(Optional.empty());
|
||||
when(messageLabelCache.get("TAG.LEAF", "en_US")).thenReturn(Optional.empty());
|
||||
|
||||
stubLabel("TAG.TOP", "en_US", "Top Category");
|
||||
stubLabel("TAG.MID", "en_US", "Mid Category");
|
||||
stubLabel("TAG.LEAF", "en_US", "Leaf Article");
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.categories()).hasSize(1);
|
||||
HelpCenterNode topNode = result.categories().get(0);
|
||||
assertThat(topNode.label()).isEqualTo("Top Category");
|
||||
assertThat(topNode.children()).hasSize(1);
|
||||
|
||||
HelpCenterNode midNode = topNode.children().get(0);
|
||||
assertThat(midNode.label()).isEqualTo("Mid Category");
|
||||
assertThat(midNode.children()).hasSize(1);
|
||||
|
||||
HelpCenterNode leafNode = midNode.children().get(0);
|
||||
assertThat(leafNode.label()).isEqualTo("Leaf Article");
|
||||
assertThat(leafNode.children()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTree_excludesInactiveNodesAndTheirDescendants() {
|
||||
stubUrlPassthrough();
|
||||
|
||||
GenericHierarchy activeLeaf = node(21, 10, "Active Leaf", "TAG.ACTIVE_LEAF", 1, "Y", "N", List.of());
|
||||
GenericHierarchy activeCat = node(10, 1, "Active Cat", "TAG.ACTIVE_CAT", 1, "Y", "N", List.of(activeLeaf));
|
||||
|
||||
GenericHierarchy hiddenChild = node(31, 20, "Hidden Child", "TAG.HIDDEN_CHILD", 1, "Y", "N", List.of());
|
||||
GenericHierarchy hiddenCat = node(20, 1, "Hidden Cat", "TAG.HIDDEN_CAT", 2, "N", "N", List.of(hiddenChild));
|
||||
|
||||
GenericHierarchy root = node(1, 0, "HC Root", null, 0, "Y", "Y", List.of(activeCat, hiddenCat));
|
||||
|
||||
stubRoot(root);
|
||||
|
||||
when(messageLabelCache.get("TAG.ACTIVE_CAT", "en_US")).thenReturn(Optional.empty());
|
||||
when(messageLabelCache.get("TAG.ACTIVE_LEAF", "en_US")).thenReturn(Optional.empty());
|
||||
|
||||
stubLabel("TAG.ACTIVE_CAT", "en_US", "Active Category");
|
||||
stubLabel("TAG.ACTIVE_LEAF", "en_US", "Active Leaf");
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.categories()).hasSize(1);
|
||||
assertThat(result.categories().get(0).label()).isEqualTo("Active Category");
|
||||
assertThat(result.categories().get(0).children()).hasSize(1);
|
||||
assertThat(result.categories().get(0).children().get(0).label()).isEqualTo("Active Leaf");
|
||||
|
||||
verify(restTemplateUtil, never()).getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
eq(String.class), eq("TAG.HIDDEN_CAT"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTree_fallsBackToName_whenMessageTagMissingOrUnresolved() {
|
||||
stubUrlPassthrough();
|
||||
|
||||
GenericHierarchy blankTag = node(11, 1, "Blank Tag Name", "", 1, "Y", "N", List.of());
|
||||
GenericHierarchy nullTag = node(12, 1, "Null Tag Name", null, 2, "Y", "N", List.of());
|
||||
GenericHierarchy notFoundTag = node(13, 1, "Not Found Name", "TAG.NOT_FOUND", 3, "Y", "N", List.of());
|
||||
GenericHierarchy root = node(1, 0, "HC Root", null, 0, "Y", "Y", List.of(blankTag, nullTag, notFoundTag));
|
||||
|
||||
stubRoot(root);
|
||||
|
||||
when(messageLabelCache.get("TAG.NOT_FOUND", "en_US")).thenReturn(Optional.empty());
|
||||
stubLabelNotFound("TAG.NOT_FOUND", "en_US");
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.categories()).hasSize(3);
|
||||
assertThat(result.categories().get(0).label()).isEqualTo("Blank Tag Name");
|
||||
assertThat(result.categories().get(1).label()).isEqualTo("Null Tag Name");
|
||||
assertThat(result.categories().get(2).label()).isEqualTo("Not Found Name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTree_usesCacheForHits_andCachesFreshFetches() {
|
||||
stubUrlPassthrough();
|
||||
|
||||
GenericHierarchy catA = node(11, 1, "Cat A Name", "TAG.A", 1, "Y", "N", List.of());
|
||||
GenericHierarchy catB = node(12, 1, "Cat B Name", "TAG.B", 2, "Y", "N", List.of());
|
||||
GenericHierarchy root = node(1, 0, "HC Root", null, 0, "Y", "Y", List.of(catA, catB));
|
||||
|
||||
stubRoot(root);
|
||||
|
||||
// TAG.A is a cache hit
|
||||
when(messageLabelCache.get("TAG.A", "en_US")).thenReturn(Optional.of("Cached A Label"));
|
||||
// TAG.B is a cache miss
|
||||
when(messageLabelCache.get("TAG.B", "en_US")).thenReturn(Optional.empty());
|
||||
|
||||
// Only stub TAG.B label endpoint
|
||||
stubLabel("TAG.B", "en_US", "Fresh B Label");
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.categories()).hasSize(2);
|
||||
assertThat(result.categories().get(0).label()).isEqualTo("Cached A Label");
|
||||
assertThat(result.categories().get(1).label()).isEqualTo("Fresh B Label");
|
||||
|
||||
// TAG.A should never hit the REST endpoint
|
||||
verify(restTemplateUtil, never()).getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
eq(String.class), eq("TAG.A"), anyString());
|
||||
|
||||
// TAG.B should be fetched and cached
|
||||
verify(restTemplateUtil).getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
eq(String.class), eq("TAG.B"), eq("en_US"));
|
||||
verify(messageLabelCache).put("TAG.B", "en_US", "Fresh B Label");
|
||||
|
||||
// TAG.A should NOT be put in cache (it was a hit)
|
||||
verify(messageLabelCache, never()).put(eq("TAG.A"), anyString(), anyString());
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.constant.api.RestApiMemberServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberServiceTest {
|
||||
|
||||
@Mock
|
||||
private RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
private MemberService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new MemberService(restTemplateUtil);
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveByMemberCodeReturnsTrueWhenOkAndBodyTrue() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_EXISTS_ACTIVE_BY_MEMBER_CODE))
|
||||
.thenReturn("http://member/member/existsActiveByMemberCode");
|
||||
when(restTemplateUtil.getForEntity(eq("http://member/member/existsActiveByMemberCode"), eq(Boolean.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(true));
|
||||
|
||||
boolean result = service.existsActiveByMemberCode("M1");
|
||||
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveByMemberCodeReturnsFalseWhenOkAndBodyFalse() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_EXISTS_ACTIVE_BY_MEMBER_CODE))
|
||||
.thenReturn("http://member/member/existsActiveByMemberCode");
|
||||
when(restTemplateUtil.getForEntity(eq("http://member/member/existsActiveByMemberCode"), eq(Boolean.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(false));
|
||||
|
||||
boolean result = service.existsActiveByMemberCode("M1");
|
||||
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveByMemberCodeReturnsFalseWhenOkAndBodyNull() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_EXISTS_ACTIVE_BY_MEMBER_CODE))
|
||||
.thenReturn("http://member/member/existsActiveByMemberCode");
|
||||
when(restTemplateUtil.getForEntity(eq("http://member/member/existsActiveByMemberCode"), eq(Boolean.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(null));
|
||||
|
||||
boolean result = service.existsActiveByMemberCode("M1");
|
||||
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveByMemberCodeReturnsFalseOnNonOkStatus() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_EXISTS_ACTIVE_BY_MEMBER_CODE))
|
||||
.thenReturn("http://member/member/existsActiveByMemberCode");
|
||||
when(restTemplateUtil.getForEntity(eq("http://member/member/existsActiveByMemberCode"), eq(Boolean.class), any()))
|
||||
.thenReturn(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
|
||||
|
||||
boolean result = service.existsActiveByMemberCode("M1");
|
||||
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.JwtTokenUtil;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AppAccessAspectAuthTest {
|
||||
|
||||
private static final String VALID_API_KEY = "valid-api-key";
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private PubSubConfig pubSubConfig;
|
||||
@Mock private PubSubTemplate pubSubTemplate;
|
||||
@Mock private PubSubUtil pubSubUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private JwtTokenUtil jwtTokenUtil;
|
||||
@Mock private ProceedingJoinPoint joinPoint;
|
||||
@Mock private MethodSignature methodSignature;
|
||||
|
||||
private AppAccessAspect aspect;
|
||||
|
||||
static class Target {
|
||||
@AppAuth
|
||||
public void secured() {
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
AuthAppKeyConfig authAppKeyConfig = new AuthAppKeyConfig();
|
||||
authAppKeyConfig.setList(List.of(VALID_API_KEY));
|
||||
aspect = new AppAccessAspect(memberService, userService, pubSubConfig, pubSubTemplate,
|
||||
pubSubUtil, authAppKeyConfig, authenticationService, jwtTokenUtil);
|
||||
|
||||
Method secured = Target.class.getMethod("secured");
|
||||
when(joinPoint.getSignature()).thenReturn(methodSignature);
|
||||
when(methodSignature.getMethod()).thenReturn(secured);
|
||||
when(methodSignature.toShortString()).thenReturn("Target.secured()");
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingApiKeyIsUnauthorized() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn("");
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidApiKeyIsUnauthorized() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn("wrong-key");
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingAuthorizationHeaderIsUnauthorizedNotBadRequest() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(VALID_API_KEY);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredTokenIsUnauthorizedNotServerError() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(VALID_API_KEY);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("expired-token");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
when(jwtTokenUtil.isTokenExpired("expired-token")).thenReturn(true);
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedTokenIsUnauthorizedNotServerError() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(VALID_API_KEY);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("garbage");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
when(jwtTokenUtil.isTokenExpired("garbage")).thenThrow(new RuntimeException("bad signature"));
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void validTokenProceedsToController() throws Throwable {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(VALID_API_KEY);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("good-token");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
when(jwtTokenUtil.isTokenExpired("good-token")).thenReturn(false);
|
||||
when(authenticationService.getUsernameFromToken("good-token")).thenReturn("alice");
|
||||
when(joinPoint.proceed()).thenReturn("controller-result");
|
||||
|
||||
Object result = aspect.appAccessAuthCheck(joinPoint);
|
||||
|
||||
assertThat(result).isEqualTo("controller-result");
|
||||
}
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum.FlagYesNo;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.JwtTokenUtil;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.controller.MemberController;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AppAccessAspectPhoneVerificationTest {
|
||||
|
||||
private static final String CP_KEY = "cp-key";
|
||||
private static final String APP_KEY = "app-key";
|
||||
private static final String JWT = "good-token";
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private PubSubConfig pubSubConfig;
|
||||
@Mock private PubSubTemplate pubSubTemplate;
|
||||
@Mock private PubSubUtil pubSubUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private JwtTokenUtil jwtTokenUtil;
|
||||
@Mock private ProceedingJoinPoint joinPoint;
|
||||
@Mock private MethodSignature methodSignature;
|
||||
|
||||
private AppAccessAspect aspect;
|
||||
|
||||
static class Target {
|
||||
@AppAuth
|
||||
public void secured() {
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@PhoneVerificationExempt
|
||||
public void exempt() {
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
public void open() {
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Throwable {
|
||||
AuthAppKeyConfig cfg = new AuthAppKeyConfig();
|
||||
cfg.setList(List.of(CP_KEY + ":CP", APP_KEY + ":APP"));
|
||||
aspect = new AppAccessAspect(memberService, userService, pubSubConfig, pubSubTemplate,
|
||||
pubSubUtil, cfg, authenticationService, jwtTokenUtil);
|
||||
when(joinPoint.getSignature()).thenReturn(methodSignature);
|
||||
when(methodSignature.toShortString()).thenReturn("Target.m()");
|
||||
when(jwtTokenUtil.isTokenExpired(JWT)).thenReturn(false);
|
||||
when(authenticationService.getUsernameFromToken(JWT)).thenReturn("alice");
|
||||
when(joinPoint.proceed()).thenReturn("result");
|
||||
}
|
||||
|
||||
private void useMethod(String name) throws Exception {
|
||||
when(methodSignature.getMethod()).thenReturn(Target.class.getMethod(name));
|
||||
}
|
||||
|
||||
private static User user(FlagYesNo phone, FlagYesNo email) {
|
||||
User u = new User();
|
||||
u.setPhoneVerified(phone);
|
||||
u.setEmailVerified(email);
|
||||
return u;
|
||||
}
|
||||
|
||||
private Object call(String apiKey) throws Throwable {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(apiKey);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn(JWT);
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
return aspect.appAccessAuthCheck(joinPoint);
|
||||
}
|
||||
}
|
||||
|
||||
private void assertForbidden(String apiKey) throws Throwable {
|
||||
assertThatThrownBy(() -> call(apiKey))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> {
|
||||
ResponseStatusException r = (ResponseStatusException) ex;
|
||||
assertThat(r.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
assertThat(r.getReason()).isEqualTo("Phone verification required.");
|
||||
assertThat(r.getHeaders().getFirst("X-Phone-Verification-Required")).isEqualTo("true");
|
||||
});
|
||||
verify(joinPoint, never()).proceed();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpUnverifiedIsForbiddenAndControllerNotRun() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenReturn(user(FlagYesNo.N, FlagYesNo.N));
|
||||
assertForbidden(CP_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpPhoneVerifiedProceeds() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenReturn(user(FlagYesNo.Y, FlagYesNo.N));
|
||||
assertThat(call(CP_KEY)).isEqualTo("result");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpEmailVerifiedProceeds() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenReturn(user(FlagYesNo.N, FlagYesNo.Y));
|
||||
assertThat(call(CP_KEY)).isEqualTo("result");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpExemptMethodProceedsWhenUnverified() throws Throwable {
|
||||
useMethod("exempt");
|
||||
when(userService.findByUsername("alice")).thenReturn(user(FlagYesNo.N, FlagYesNo.N));
|
||||
assertThat(call(CP_KEY)).isEqualTo("result");
|
||||
}
|
||||
|
||||
@Test
|
||||
void appPlatformUnverifiedProceedsWithoutLookup() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenReturn(user(FlagYesNo.N, FlagYesNo.N));
|
||||
assertThat(call(APP_KEY)).isEqualTo("result");
|
||||
verify(userService, never()).findByUsername(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipValidateMethodDoesNoUserLookup() throws Throwable {
|
||||
useMethod("open");
|
||||
assertThat(call(CP_KEY)).isEqualTo("result");
|
||||
verify(userService, never()).findByUsername(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpNullUserIsForbidden() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenReturn(null);
|
||||
assertForbidden(CP_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpLookupThrowingIsForbidden() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenThrow(new RuntimeException("system-service down"));
|
||||
assertForbidden(CP_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void otpEndpointsCarryPhoneVerificationExempt() throws Exception {
|
||||
Method required = MemberController.class.getMethod("getOtpRequired");
|
||||
Method verify = MemberController.class.getMethod("postOtpVerification", Map.class);
|
||||
assertThat(required.isAnnotationPresent(PhoneVerificationExempt.class)).isTrue();
|
||||
assertThat(verify.isAnnotationPresent(PhoneVerificationExempt.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstTimePasswordCarriesPhoneVerificationExempt() throws Exception {
|
||||
Method m = MemberController.class.getMethod("firstTimePassword", Map.class);
|
||||
assertThat(m.isAnnotationPresent(PhoneVerificationExempt.class)).isTrue();
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum.CmsPlatform;
|
||||
import com.solvway.core.model.ResponseTime;
|
||||
import com.solvway.core.utils.JwtTokenUtil;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** add-response-time-platform-attribution: rows carry the platform of the api-key that authorised the call. */
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AppAccessAspectResponseTimeTest {
|
||||
|
||||
private static final String TOPIC = "response-time-log-topic";
|
||||
|
||||
@Mock private ProceedingJoinPoint joinPoint;
|
||||
@Mock private MethodSignature methodSignature;
|
||||
@Mock private PubSubTemplate pubSubTemplate;
|
||||
@Mock private PubSubUtil pubSubUtil;
|
||||
@Mock private JwtTokenUtil jwtTokenUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
|
||||
private AppAccessAspect aspect;
|
||||
|
||||
static class Target {
|
||||
@AppAuth(skipValidate = true) public void publicEndpoint() {}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Throwable {
|
||||
AuthAppKeyConfig keys = new AuthAppKeyConfig();
|
||||
keys.setList(List.of("cpKey:CP", "legacyKey", "abcd1234:CP"));
|
||||
PubSubConfig pubSubConfig = mock(PubSubConfig.class);
|
||||
pubSubConfig.responseTimeLogTopic = TOPIC;
|
||||
aspect = new AppAccessAspect(mock(MemberService.class), mock(UserService.class), pubSubConfig,
|
||||
pubSubTemplate, pubSubUtil, keys, authenticationService, jwtTokenUtil);
|
||||
|
||||
when(joinPoint.getSignature()).thenReturn(methodSignature);
|
||||
when(methodSignature.getMethod()).thenReturn(Target.class.getMethod("publicEndpoint"));
|
||||
when(methodSignature.toShortString()).thenReturn("Target.publicEndpoint()");
|
||||
when(joinPoint.proceed()).thenReturn("ok");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
}
|
||||
|
||||
private void requestWithApiKey(String apiKey) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/public/banner");
|
||||
request.addHeader("api-key", apiKey);
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
|
||||
}
|
||||
|
||||
private ResponseTime published() {
|
||||
ArgumentCaptor<ResponseTime> captor = ArgumentCaptor.forClass(ResponseTime.class);
|
||||
verify(pubSubUtil).publishMessage(eq(pubSubTemplate), eq(TOPIC), captor.capture());
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void customerPortalKeyPassesGateAndPublishesCp() throws Throwable {
|
||||
requestWithApiKey("cpKey");
|
||||
|
||||
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
|
||||
|
||||
ResponseTime rt = published();
|
||||
assertThat(rt.getSourcePlatform()).isEqualTo(CmsPlatform.CP);
|
||||
assertThat(rt.getUrl()).isEqualTo("/api/public/banner");
|
||||
assertThat(rt.getMethod()).isEqualTo("GET");
|
||||
}
|
||||
|
||||
@Test
|
||||
void bareKeyPublishesApp() throws Throwable {
|
||||
requestWithApiKey("legacyKey");
|
||||
|
||||
aspect.appAccessAuthCheck(joinPoint);
|
||||
|
||||
assertThat(published().getSourcePlatform()).isEqualTo(CmsPlatform.APP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rawSuffixedTokenIsRejectedAndNotPublished() {
|
||||
requestWithApiKey("cpKey:CP");
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class,
|
||||
ex -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
verify(pubSubUtil, never()).publishMessage(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publisherFailureDoesNotBreakSuccessfulResponse() throws Throwable {
|
||||
requestWithApiKey("cpKey");
|
||||
doThrow(new RuntimeException("pubsub down")).when(pubSubUtil).publishMessage(any(), any(), any());
|
||||
|
||||
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectLogNeverPrintsAConfiguredKey() {
|
||||
requestWithApiKey("wrong-key");
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(AppAccessAspect.class);
|
||||
ListAppender<ILoggingEvent> appender = new ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
try {
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint)).isInstanceOf(ResponseStatusException.class);
|
||||
} finally {
|
||||
logger.detachAppender(appender);
|
||||
}
|
||||
|
||||
// An 8-character key with a platform suffix used to be printed in full by the masked allow-list.
|
||||
assertThat(appender.list).isNotEmpty()
|
||||
.allSatisfy(event -> assertThat(event.getFormattedMessage())
|
||||
.doesNotContain("abcd1234").doesNotContain("cpKey").doesNotContain("legacyKey"));
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
class PhoneVerificationHeaderMvcTest {
|
||||
|
||||
@RestController
|
||||
static class ThrowingController {
|
||||
@GetMapping("/gated")
|
||||
public String gated() {
|
||||
throw AppAccessAspect.phoneVerificationRequired();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void gateExceptionBecomes403WithHeaderOnTheHttpResponse() throws Exception {
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(new ThrowingController()).build();
|
||||
mvc.perform(get("/gated"))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(header().string("X-Phone-Verification-Required", "true"));
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.solvway.mobile.api.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class HeaderRedactionUtilTest {
|
||||
|
||||
@Test
|
||||
void redactsAuthorizationHeaderValue() {
|
||||
String headers = "{\"Authorization\":\"Bearer secret-token\",\"User-Agent\":\"junit\"}";
|
||||
|
||||
String redacted = HeaderRedactionUtil.redact(headers);
|
||||
|
||||
assertThat(redacted).doesNotContain("secret-token");
|
||||
assertThat(redacted).contains("[REDACTED]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesNonSensitiveHeaders() {
|
||||
String headers = "{\"Authorization\":\"Bearer secret-token\",\"User-Agent\":\"junit\"}";
|
||||
|
||||
String redacted = HeaderRedactionUtil.redact(headers);
|
||||
|
||||
assertThat(redacted).contains("junit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void redactsRegardlessOfHeaderNameCasing() {
|
||||
String headers = "{\"authorization\":\"Bearer secret-token\"}";
|
||||
|
||||
assertThat(HeaderRedactionUtil.redact(headers)).doesNotContain("secret-token");
|
||||
}
|
||||
|
||||
@Test
|
||||
void redactsApiKeyAndCookieHeaders() {
|
||||
String headers = "{\"api-key\":\"k123\",\"Cookie\":\"session=abc\"}";
|
||||
|
||||
String redacted = HeaderRedactionUtil.redact(headers);
|
||||
|
||||
assertThat(redacted).doesNotContain("k123");
|
||||
assertThat(redacted).doesNotContain("session=abc");
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyObjectForUnparseableInput() {
|
||||
assertThat(HeaderRedactionUtil.redact("not-json")).isEqualTo("{}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlesNullAndEmptyInput() {
|
||||
assertThat(HeaderRedactionUtil.redact(null)).isNull();
|
||||
assertThat(HeaderRedactionUtil.redact("")).isEmpty();
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.solvway.mobile.api.util.redis;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class TokenCacheKeyUtilTest {
|
||||
|
||||
@Test
|
||||
void hashesTokenToLowercaseHexSha256() {
|
||||
assertThat(TokenCacheKeyUtil.hashToken("abc"))
|
||||
.isEqualTo("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
|
||||
}
|
||||
|
||||
@Test
|
||||
void producesStableHashForSameToken() {
|
||||
assertThat(TokenCacheKeyUtil.hashToken("token-1"))
|
||||
.isEqualTo(TokenCacheKeyUtil.hashToken("token-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void producesDifferentHashesForDifferentTokens() {
|
||||
assertThat(TokenCacheKeyUtil.hashToken("token-1"))
|
||||
.isNotEqualTo(TokenCacheKeyUtil.hashToken("token-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void neverReturnsTheRawToken() {
|
||||
String token = "eyJhbGciOiJIUzUxMiJ9.payload.signature";
|
||||
assertThat(TokenCacheKeyUtil.hashToken(token)).doesNotContain(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyStringForNullOrEmptyToken() {
|
||||
assertThat(TokenCacheKeyUtil.hashToken(null)).isEmpty();
|
||||
assertThat(TokenCacheKeyUtil.hashToken("")).isEmpty();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user