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

refactor: 테스트 코드 내 로그인 중복 제거 #453

Merged
merged 31 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
773a0c9
feat: id를 사용하는 entity는 BaseEntity를 상속하도록 수정 (#293)
thdwoqor Sep 12, 2023
83c6004
refactor: 룸 업로드 페이지 리팩터링 (#307)
Songusika Sep 17, 2023
3f6489b
refactor: 룸, 트랙, 미디어소스 역정규화 (#309)
0chil Sep 18, 2023
24f03e3
feat: 카카오 소셜 로그인 기능을 구현한다. (#301)
kong-hana01 Sep 19, 2023
07c88f8
chore: 데이터 베이스 테이블 컬럼 수정 (#311)
thdwoqor Sep 19, 2023
a1b2d4f
feat: IdTokenResolver가 Provider에 맞게 동작한다 (#314)
0chil Sep 21, 2023
9db7cc6
feat: 게스트로 로그인한다 (#316)
0chil Sep 21, 2023
009f9fd
chore: 중복된 ci 파일 제거 (#323)
kong-hana01 Sep 21, 2023
c817a18
Merge branch 'backend' of https://github.com/woowacourse-teams/2023-d…
kong-hana01 Sep 27, 2023
9abac13
Merge branch 'backend' of https://github.com/woowacourse-teams/2023-d…
kong-hana01 Oct 25, 2023
dddb165
Merge branch 'backend' of https://github.com/woowacourse-teams/2023-d…
kong-hana01 Dec 10, 2023
9ab764f
fix: 피드백 검증을 하지 않는 문제 해결
kong-hana01 Dec 10, 2023
fc5acb1
chore: 컨벤션 통일
kong-hana01 Dec 10, 2023
9dea15a
refactor: DatabaseCleaner 인터페이스 및 구현체 구현
kong-hana01 Jan 24, 2024
8760bed
refactor: AuthDatabaseCleaner 구현
kong-hana01 Jan 24, 2024
3c3a33f
refactor: 외부에서 값을 주입받아 빈을 생성하도록 변경
kong-hana01 Jan 24, 2024
c5eb0da
chore: 패키지 구조 변경(util -> config)
kong-hana01 Jan 24, 2024
ce345b8
refactor: ControllerTest의 profile 설정
kong-hana01 Jan 25, 2024
ca9faac
feat: MockLogin 객체 구현
kong-hana01 Jan 25, 2024
6bfa6b3
feat: MockLogin 객체 구현
kong-hana01 Jan 28, 2024
cbe2ec2
refactor: default 환경을 구성하는 컨트롤러 테스트 격리
kong-hana01 Jan 29, 2024
f7ca27f
feat: 로그인을 담당하는 mock 서버 구현
kong-hana01 Jan 29, 2024
8271418
refactor: 로그인 환경을 설정하는 ControllerTestConfig 객체 구현
kong-hana01 Jan 29, 2024
b05d9c9
refactor: 멤버 정보를 재사용해서 테스트를 하도록 변경
kong-hana01 Jan 29, 2024
44ba455
fix: FeedbackControllerTest에서 캐싱사용하도록 변경
kong-hana01 Jan 30, 2024
c619ef4
docs: 예외 로그 확인 ci 파일 추가
kong-hana01 Jan 31, 2024
17fe93a
refactor: TestInstance 단위를 class로 변경
kong-hana01 Feb 5, 2024
2a8bb20
refactor: MockLoginServer의 빈 스코프를 프로토타입으로 변경
kong-hana01 Feb 5, 2024
403e93e
docs: ci 파일 복구
kong-hana01 Feb 5, 2024
5f2fe81
refactor: 테스트 내 환경을 @TestConfiguration으로 변경
kong-hana01 Feb 14, 2024
327601f
chore: 사용하지 않는 콘솔 출력 제거
kong-hana01 Mar 4, 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
@@ -1,32 +1,36 @@
package com.digginroom.digginroom.feedback.controller;

import com.digginroom.digginroom.controller.Auth;
import com.digginroom.digginroom.domain.member.Member;
import com.digginroom.digginroom.feedback.FeedbackService;
import com.digginroom.digginroom.feedback.dto.FeedbackRequest;
import com.digginroom.digginroom.feedback.dto.FeedbackResponse;
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/feedbacks")
public class FeedbackController {

private final FeedbackService feedbackService;

@PostMapping("/feedbacks")
public ResponseEntity<Void> takeFeedbackFrom(final @Auth Long memberId, final @RequestBody FeedbackRequest feedback) {
@PostMapping
public ResponseEntity<Void> takeFeedbackFrom(
@Auth final Long memberId,
@Valid @RequestBody final FeedbackRequest feedback
) {
feedbackService.accept(memberId, feedback);
return ResponseEntity.ok().build();
}

@GetMapping("/feedbacks")
@GetMapping
Comment on lines 32 to +33
Copy link
Collaborator

Choose a reason for hiding this comment

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

제가 싼 💩을 치워주셨군요..👍

public ResponseEntity<List<FeedbackResponse>> showFeedbacks() {
return ResponseEntity.ok().body(feedbackService.getAll());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class Feedback extends BaseEntity {
private Long writerId;
private String content;

public Feedback(Long writerId, String content) {
public Feedback(final Long writerId, final String content) {
this.writerId = writerId;
this.content = content;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.digginroom.digginroom.config;

import static com.digginroom.digginroom.config.DatabaseTableName.MEMBER;
import static com.digginroom.digginroom.config.DatabaseTableName.MEMBER_GENRE;
import static com.digginroom.digginroom.config.DatabaseTableName.SPRING_SESSION;
import static com.digginroom.digginroom.config.DatabaseTableName.SPRING_SESSION_ATTRIBUTES;

import java.util.Set;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.web.reactive.function.client.WebClient;

@TestConfiguration
public class ControllerTestConfig {

@Bean
@Profile("default")
public DatabaseCleaner getDatabaseCleanerBean() {
return new DatabaseCleaner(Set.of());
}

@Bean
@Profile("auth")
public DatabaseCleaner getAuthDatabaseCleanerBean() {
return new DatabaseCleaner(Set.of(MEMBER, MEMBER_GENRE, SPRING_SESSION, SPRING_SESSION_ATTRIBUTES));
}

Comment on lines +25 to +28
Copy link
Collaborator

Choose a reason for hiding this comment

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

명확해서 좋습니다!
하나 마음에 걸리는 건 테이블 이름에 종속적이라는 것이네요.
하지만 그런 일은 잘 안생기니까 당장은 괜찮다고 생각합니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

인정합니다!
flyway로 관리하니까 잘하면 어찌저찌해볼 순 있겠지만 어떻게 해야할지는 잘 모르겠네요 ㅎㅎ..

@Bean
@Profile("auth")
public WebClient.Builder getWebClientBuilder() {
return WebClient.builder();
}
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,33 @@
package com.digginroom.digginroom.util;
package com.digginroom.digginroom.config;

import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityManager;
import jakarta.transaction.Transactional;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DatabaseCleaner {

@Autowired
private EntityManager entityManager;
private List<String> tableNames;
private final Set<DatabaseTableName> filterDatabaseTableNames;

public DatabaseCleaner(final Set<DatabaseTableName> filterDatabaseTableNames) {
this.filterDatabaseTableNames = filterDatabaseTableNames;
}

@PostConstruct
private void setUpDatabaseTableNames() {
public void setUpDatabaseTableNames() {
this.tableNames = getTableNames();
}

private List<String> getTableNames() {
return getTableMetaData().stream().map(this::getTableName).toList();
return getTableMetaData().stream()
.map(this::getTableName)
.filter(tableName -> !filterDatabaseTableNames.contains(DatabaseTableName.of(tableName)))
.toList();
}

@SuppressWarnings("unchecked")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.digginroom.digginroom.util;
package com.digginroom.digginroom.config;

import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.digginroom.digginroom.config;

import java.util.Arrays;

public enum DatabaseTableName {

MEMBER("member"),
MEMBER_GENRE("member_genre"),
SPRING_SESSION("spring_session"),
SPRING_SESSION_ATTRIBUTES("spring_session_attributes"),
EMPTY("");

private final String name;

DatabaseTableName(final String name) {
this.name = name;
}

public static DatabaseTableName of(final String name) {
return Arrays.stream(values())
.filter(databaseTableName -> databaseTableName.getName().equalsIgnoreCase(name))
.findFirst()
.orElse(EMPTY);
}

public String getName() {
return name;
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package com.digginroom.digginroom.controller;

import static com.digginroom.digginroom.TestFixture.COMMENT_UPDATE_REQUEST;
import static com.digginroom.digginroom.TestFixture.MEMBER2_LOGIN_REQUEST;
import static com.digginroom.digginroom.TestFixture.MEMBER_LOGIN_REQUEST;
import static com.digginroom.digginroom.TestFixture.나무;
import static com.digginroom.digginroom.TestFixture.블랙캣;
import static com.digginroom.digginroom.TestFixture.차이;
import static com.digginroom.digginroom.TestFixture.파워;
import static org.assertj.core.api.Assertions.assertThat;

import com.digginroom.digginroom.TestFixture;
import com.digginroom.digginroom.controller.mock.MockLoginServer;
import com.digginroom.digginroom.domain.comment.Comment;
import com.digginroom.digginroom.domain.member.Member;
import com.digginroom.digginroom.domain.room.Room;
Expand All @@ -19,45 +16,50 @@
import com.digginroom.digginroom.service.dto.CommentRequest;
import com.digginroom.digginroom.service.dto.CommentResponse;
import com.digginroom.digginroom.service.dto.CommentsResponse;
import com.digginroom.digginroom.service.dto.MemberLoginRequest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import java.util.List;
import java.util.stream.Collectors;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ActiveProfiles;

@ActiveProfiles("auth")
@SuppressWarnings("NonAsciiCharacters")
class CommentControllerTest extends ControllerTest {

@Autowired
private MemberRepository memberRepository;
@Autowired
private RoomRepository roomRepository;
@Autowired
private CommentRepository commentRepository;

private MockLoginServer mockLoginServer;
private Room 나무;
private Room 차이;
private Member 파워;

@Autowired
public CommentControllerTest(MemberRepository memberRepository,
RoomRepository roomRepository,
CommentRepository commentRepository,
ObjectProvider<MockLoginServer> mockLoginServerObjectProvider
) {
this.memberRepository = memberRepository;
this.roomRepository = roomRepository;
this.commentRepository = commentRepository;
this.mockLoginServer = mockLoginServerObjectProvider.getObject();
}

@Override
@BeforeEach
void setUp() {
super.setUp();
파워 = memberRepository.save(파워());
memberRepository.save(블랙캣());
나무 = roomRepository.save(나무());
차이 = roomRepository.save(차이());
}

@Test
void 댓글을_작성_할_수_있다() {
String cookie = login(MEMBER_LOGIN_REQUEST);
String cookie = login(port);

RestAssured.given().log().all()
.cookie(cookie)
Expand All @@ -75,7 +77,7 @@ void setUp() {

@Test
void 댓글은_500자_이하여야한다() {
String cookie = login(MEMBER_LOGIN_REQUEST);
String cookie = login(port);

RestAssured.given().log().all()
.cookie(cookie)
Expand All @@ -88,7 +90,7 @@ void setUp() {

@Test
void 댓글은_1자_이상이여야한다() {
String cookie = login(MEMBER_LOGIN_REQUEST);
String cookie = login(port);

RestAssured.given().log().all()
.cookie(cookie)
Expand All @@ -101,7 +103,7 @@ void setUp() {

@Test
void 유저는_자신의_댓글을_삭제할_수_있다() {
String cookie = login(MEMBER_LOGIN_REQUEST);
String cookie = login(port);

CommentResponse commentResponse = commentRequest(cookie, "댓글");

Expand All @@ -115,13 +117,12 @@ void setUp() {

@Test
void 유저는_다른_유저의_댓글을_삭제할_수_없다() {
String powerCookie = login(MEMBER_LOGIN_REQUEST);
String blackcatCookie = login(MEMBER2_LOGIN_REQUEST);
List<String> cookies = mockLoginServer.getCachedLoginValues(port, 2);

CommentResponse commentResponse = commentRequest(blackcatCookie, "댓글");
CommentResponse commentResponse = commentRequest(cookies.get(0), "댓글");

RestAssured.given().log().all()
.cookie(powerCookie)
.cookie(cookies.get(1))
.contentType(ContentType.JSON)
.when().delete("/rooms/" + 나무.getId() + "/comments/" + commentResponse.id())
.then().log().all()
Expand All @@ -130,10 +131,10 @@ void setUp() {

@Test
void 유저는_존재하지_않은_댓글을_삭제할_수_없다() {
String powerCookie = login(MEMBER_LOGIN_REQUEST);
String cookie = login(port);

RestAssured.given().log().all()
.cookie(powerCookie)
.cookie(cookie)
.contentType(ContentType.JSON)
.when().delete("/rooms/" + 나무.getId() + "/comments/" + Long.MAX_VALUE)
.then().log().all()
Expand All @@ -142,11 +143,13 @@ void setUp() {

@Test
void 유저가_마지막으로_본_댓글과_볼_댓글_개수를_전달하지_않으면_최신_댓글_10개의_댓글들을_볼_수_있다() {
Member 파워 = memberRepository.save(파워());

for (int i = 1; i <= 15; i++) {
commentRepository.save(new Comment(나무.getId(), "댓글" + i, 파워));
}

String cookie = login(MEMBER_LOGIN_REQUEST);
String cookie = login(port);

List<String> comments = RestAssured.given().log().all()
.cookie(cookie)
Expand All @@ -167,11 +170,13 @@ void setUp() {

@Test
void 유저가_마지막으로_본_댓글을_전달하면_더_이전에_작성한_룸의_댓글들을_볼_수_있다() {
Member 파워 = memberRepository.save(파워());

for (int i = 1; i <= 15; i++) {
commentRepository.save(new Comment(나무.getId(), "댓글" + i, 파워));
}

String cookie = login(MEMBER_LOGIN_REQUEST);
String cookie = login(port);

List<String> comments = RestAssured.given().log().all()
.cookie(cookie)
Expand All @@ -190,11 +195,13 @@ void setUp() {

@Test
void 유저가_볼_댓글_개수를_전달하면_최대_전달한_개수만큼의_룸의_댓글들을_볼_수_있다() {
Member 파워 = memberRepository.save(파워());

for (int i = 1; i <= 15; i++) {
commentRepository.save(new Comment(나무.getId(), "댓글" + i, 파워));
}

String cookie = login(MEMBER_LOGIN_REQUEST);
String cookie = login(port);

List<String> comments = RestAssured.given().log().all()
.cookie(cookie)
Expand All @@ -213,11 +220,13 @@ void setUp() {

@Test
void 유저가_마지막으로_본_댓글과_볼_댓글_개수를_전달하면_더_이전에_작성한_댓글들을_최대_전달한_개수만큼_볼_수_있다() {
Member 파워 = memberRepository.save(파워());

for (int i = 1; i <= 15; i++) {
commentRepository.save(new Comment(나무.getId(), "댓글" + i, 파워));
}

String cookie = login(MEMBER_LOGIN_REQUEST);
String cookie = login(port);

List<String> comments = RestAssured.given().log().all()
.cookie(cookie)
Expand All @@ -234,14 +243,8 @@ void setUp() {
assertThat(comments).containsExactly("댓글6", "댓글5");
}

private static String login(final MemberLoginRequest loginRequest) {
Response response = RestAssured.given().log().all()
.body(loginRequest)
.contentType(ContentType.JSON)
.when()
.post("/login");

return response.header("Set-Cookie");
private String login(final int port) {
return mockLoginServer.getCachedLoginValue(port);
}

private CommentResponse commentRequest(final String cookie, final String comment) {
Expand All @@ -256,19 +259,19 @@ private CommentResponse commentRequest(final String cookie, final String comment

@Test
void 유저는_자신의_댓글을_수정할_수_있다() {
Comment comment = commentRepository.save(new Comment(나무.getId(), "댓글1", 파워));
String cookie = login(MEMBER_LOGIN_REQUEST);
String cookie = login(port);
CommentResponse comment = commentRequest(cookie, "안녕");

RestAssured.given().log().all()
.cookie(cookie)
.contentType(ContentType.JSON)
.body(COMMENT_UPDATE_REQUEST)
.when().patch("/rooms/" + 나무.getId() + "/comments/" + comment.getId())
.when().patch("/rooms/" + 나무.getId() + "/comments/" + comment.id())
.then().log().all()
.statusCode(HttpStatus.OK.value())
.extract().as(CommentResponse.class);

Comment updatedComment = commentRepository.getCommentById(comment.getId());
Comment updatedComment = commentRepository.getCommentById(comment.id());
assertThat(updatedComment.getComment()).isEqualTo(COMMENT_UPDATE_REQUEST.comment());
}
}
Loading
Loading