Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat : 각 도메인별 테스트 코드 추가 및 수정 및 각 멤버 별(보호자, 시니또) 할 수 있는 행동 제약 추가 #131

Merged
merged 19 commits into from
Nov 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
92dcc15
feat : 보호자만 시니어 등록할 수 있도록 createSenior 메소드 수정
2iedo Oct 31, 2024
adfa3d7
refactor : 시니또 제거하는 메소드 삭제
2iedo Oct 31, 2024
1cd271f
Test : Guard 도메인의 서비스 레이어 테스트 코드 작성.
2iedo Oct 31, 2024
98c5253
test : Sinitto 도메인에 대한 서비스 레이어의 테스트 코드 작성
2iedo Oct 31, 2024
3bda2cc
refactor : verify 메소드 사용하여 테스트 코드 수정
2iedo Oct 31, 2024
f7f5763
test : GuardGuideline 도메인의 서비스 레이어 테스트 코드 작성
2iedo Oct 31, 2024
82771a2
refactor : accessToken 만료시간 10분으로 변경
2iedo Nov 1, 2024
212ba9a
refactor : accessToken의 만료시간 5분으로 변경
2iedo Nov 1, 2024
7002795
refactor : refreshToken 만료 시 InvalidJwtException 에러 발생하도록 변경
2iedo Nov 1, 2024
4b8974a
test : auth 도메인의 서비스 레이어 테스트 코드 작성
2iedo Nov 1, 2024
7372237
refactor : 오탈자 수정
2iedo Nov 2, 2024
715ce7e
refactor : 변수명 변경
2iedo Nov 2, 2024
d2bd0a0
Merge branch 'Weekly' into Feat/issue-#125
2iedo Nov 2, 2024
0d3b390
test : Member 도메인의 서비스 레이어에 대한 테스트 코드 작성
2iedo Nov 2, 2024
298392a
Merge branch 'Feat/issue-#125' of https://github.com/kakao-tech-campu…
2iedo Nov 2, 2024
1afcb1a
test : HelloCall 도메인의 서비스 레이어 테스트 코드 작성
2iedo Nov 2, 2024
f066c46
style : intellij로 코드 서식 변경
2iedo Nov 2, 2024
838819f
refactor : 사용하지 않는 mock 객체 삭제
2iedo Nov 3, 2024
36fc726
refactor : update 메소드 관련 테스트 코드 수정
2iedo Nov 3, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
@Service
public class TokenService {

private static final long ACCESS_TEN_HOURS = 1000 * 60 * 5;
private static final long ACCESS_FIVE_MINUTES = 1000 * 60 * 5;

private static final long REFRESH_SEVEN_DAYS = 1000 * 60 * 60 * 24 * 7;

private final Key secretKey;
Expand All @@ -36,7 +37,7 @@ public String generateAccessToken(String email) {
return Jwts.builder()
.setSubject(email)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + ACCESS_TEN_HOURS))
.setExpiration(new Date(System.currentTimeMillis() + ACCESS_FIVE_MINUTES))
.signWith(secretKey, SignatureAlgorithm.HS256)
.compact();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.sinitto.guard.service;

import com.example.sinitto.common.exception.BadRequestException;
import com.example.sinitto.common.exception.NotFoundException;
import com.example.sinitto.guard.dto.GuardRequest;
import com.example.sinitto.guard.dto.GuardResponse;
Expand Down Expand Up @@ -56,6 +57,7 @@ public void createSenior(Long memberId, SeniorRequest seniorRequest) {
Member member = memberRepository.findById(memberId).orElseThrow(
() -> new NotFoundException("이메일에 해당하는 멤버를 찾을 수 없습니다.")
);
if (member.isSinitto()) throw new BadRequestException("보호자만 이용할 수 있습니다.");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍👍


Senior senior = new Senior(seniorRequest.seniorName(), seniorRequest.seniorPhoneNumber(), member);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,4 @@ public ResponseEntity<String> updateSinittoBankInfo(@MemberId Long memberId, @Re
sinittoService.updateSinittoBankInfo(memberId, sinittoBankRequest);
return ResponseEntity.ok("시니또 정보가 수정되었습니다.");
}

@Operation(summary = "시니또 삭제", description = "관리자용")
@DeleteMapping
public ResponseEntity<String> deleteSinitto(@MemberId Long memberId) {
sinittoService.deleteSinitto(memberId);
return ResponseEntity.ok("시니또가 삭제되었습니다.");
}


2iedo marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,4 @@ public void updateSinittoBankInfo(Long memberId, SinittoBankRequest sinittoBankR
);
sinittoBankInfo.updateSinitto(sinittoBankRequest.bankName(), sinittoBankRequest.accountNumber());
}

@Transactional
public void deleteSinitto(Long memberId) {
Member member = memberRepository.findById(memberId).orElseThrow(
() -> new NotFoundException("이메일에 해당하는 멤버를 찾을 수 없습니다.")
);
memberRepository.delete(member);
}


}
2iedo marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package com.example.sinitto.auth.service;

import com.example.sinitto.common.exception.BadRequestException;
import com.example.sinitto.common.properties.KakaoProperties;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoSettings;
import org.springframework.beans.factory.annotation.Value;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

@MockitoSettings
public class KakaoApiServiceTest {
@Mock
private HttpServletRequest httpServletRequest;

@Mock
private KakaoProperties kakaoProperties;

@Value("kakao.clientId")
private String clientId;

@Value("kakao.devRedirectUri")
private String devRedirectUri;

@Value("kakao.redirectUri")
private String redirectUri;

@InjectMocks
KakaoApiService kakaoApiService;

@Test
@DisplayName("getAuthorizationUrl 메소드 테스트 - devUri 포홤 시")
void getAuthorizationUrlTestWithDevUri() {
//given
when(httpServletRequest.getHeader("Referer")).thenReturn("http://localhost:5173");
when(kakaoProperties.devRedirectUri()).thenReturn(devRedirectUri);
when(kakaoProperties.clientId()).thenReturn(clientId);

//when
String result = kakaoApiService.getAuthorizationUrl(httpServletRequest);
String expect = "https://kauth.kakao.com/oauth" + "/authorize?response_type=code&client_id="
+ clientId
+ "&redirect_uri="
+ devRedirectUri;

//then
assertEquals(result, expect);
}

@Test
@DisplayName("getAuthorizationUrl 메소드 테스트 - 배포 uri 포홤 시")
void getAuthorizationUrlTestWithAwsUri() {
//given
when(httpServletRequest.getHeader("Referer")).thenReturn("http://sinitto.s3-website.ap-northeast-2.amazonaws.com");
when(kakaoProperties.redirectUri()).thenReturn(redirectUri);
when(kakaoProperties.clientId()).thenReturn(clientId);

//when
String result = kakaoApiService.getAuthorizationUrl(httpServletRequest);
String expect = "https://kauth.kakao.com/oauth" + "/authorize?response_type=code&client_id="
+ clientId
+ "&redirect_uri="
+ redirectUri;

//then
assertEquals(result, expect);
}

@Test
@DisplayName("getAuthorizationUrl 메소드 테스트 - 이외의 주소 포함 시 실패")
void getAuthorizationUrlTestWithAnotherUri() {
//given
when(httpServletRequest.getHeader("Referer")).thenReturn("http://test-uri.com");

//when, then
assertThrows(BadRequestException.class, () -> kakaoApiService.getAuthorizationUrl(httpServletRequest));
}

@Test
@DisplayName("getAuthorizationUrl 메소드 테스트 - 주소가 null일 시 실패")
void getAuthorizationUrlTestWithNullUri() {
//given
when(httpServletRequest.getHeader("Referer")).thenReturn(null);

//when, then
assertThrows(BadRequestException.class, () -> kakaoApiService.getAuthorizationUrl(httpServletRequest));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.example.sinitto.auth.service;

import com.example.sinitto.auth.dto.KakaoTokenResponse;
import com.example.sinitto.auth.entity.KakaoToken;
import com.example.sinitto.auth.repository.KakaoTokenRepository;
import com.example.sinitto.common.exception.InvalidJwtException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoSettings;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

@MockitoSettings
public class KakaoTokenServiceTest {
@Mock
private KakaoTokenRepository kakaoTokenRepository;

@InjectMocks
private KakaoTokenService kakaoTokenService;

@Test
@DisplayName("saveKakaoToken 메소드 테스트")
void saveKakaoTokenTestInRepository() {
//given
String email = "[email protected]";
KakaoTokenResponse kakaoTokenResponse = mock(KakaoTokenResponse.class);
KakaoToken kakaoToken = mock(KakaoToken.class);

when(kakaoTokenRepository.findByMemberEmail(email)).thenReturn(Optional.of(kakaoToken));

//when
kakaoTokenService.saveKakaoToken(email, kakaoTokenResponse);

//then
verify(kakaoToken, times(1)).updateKakaoToken(kakaoTokenResponse.accessToken(), kakaoTokenResponse.refreshToken(),
kakaoTokenResponse.expiresIn(), kakaoTokenResponse.refreshTokenExpiresIn());
verify(kakaoTokenRepository, times(1)).save(any(KakaoToken.class));
}

@Test
@DisplayName("getValidAccessTokenInServer 메소드 테스트 - accessToken 만료 전")
void getValidAccessTokenInServerTestWhenAccessTokenIsNotExpired() {
//given
String email = "[email protected]";
KakaoToken kakaoToken = mock(KakaoToken.class);

when(kakaoTokenRepository.findByMemberEmail(email)).thenReturn(Optional.of(kakaoToken));
when(kakaoToken.isAccessTokenExpired()).thenReturn(false);
//when
String result = kakaoTokenService.getValidAccessTokenInServer(email);

//then
assertEquals(kakaoToken.getAccessToken(), result);
}

@Test
@DisplayName("getValidAccessTokenInServer 메소드 테스트 - accessToken 및 refreshToken 만료 후")
void getValidAccessTokenInServerTestWhenAccessTokenAndRefreshTokenIsExpired() {
//given
String email = "[email protected]";
KakaoToken kakaoToken = mock(KakaoToken.class);

when(kakaoTokenRepository.findByMemberEmail(email)).thenReturn(Optional.of(kakaoToken));
when(kakaoToken.isAccessTokenExpired()).thenReturn(true);
when(kakaoToken.isRefreshTokenExpired()).thenReturn(true);

//when, then
assertThrows(InvalidJwtException.class, () -> kakaoTokenService.getValidAccessTokenInServer(email));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.example.sinitto.auth.service;

import com.example.sinitto.common.exception.InvalidJwtException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoSettings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

@MockitoSettings
public class TokenServiceTest {
@Mock
private RedisTemplate<String, String> redisTemplate;

@Mock
private ValueOperations<String, String> valueOperations;

private TokenService tokenService;

String key = "thisistestkeynotrealkeythisistestkeynotrealkey";
2iedo marked this conversation as resolved.
Show resolved Hide resolved

@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
String secretKey = Base64.getEncoder().encodeToString(this.key.getBytes());
tokenService = new TokenService(secretKey, redisTemplate);
}

@Test
@DisplayName("generateAccessToken 메소드 테스트 - extractEmail 메소드도 함께 사용")
void generateAccessTokenTest() {
//given
String email = "[email protected]";

//when
String token = tokenService.generateAccessToken(email);
String resultEmail = tokenService.extractEmail(token);

//then
assertNotNull(token);
assertTrue(token.startsWith("ey"));
assertEquals(email, resultEmail);
}

@Test
@DisplayName("generateRefreshToken 메소드 테스트 - extractEmail 메소드도 함께 사용")
void generateRefreshTokenTest() {
//given
String email = "[email protected]";

when(redisTemplate.opsForValue()).thenReturn(valueOperations);
2iedo marked this conversation as resolved.
Show resolved Hide resolved

//when
String token = tokenService.generateRefreshToken(email);
String resultEmail = tokenService.extractEmail(token);

//then
assertNotNull(token);
assertTrue(token.startsWith("ey"));
assertEquals(email, resultEmail);
}
}
Loading