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

[BE] 테스트 데이터 클리너 구현 #199

Merged
merged 4 commits into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -7,14 +7,13 @@
import static server.haengdong.domain.action.MemberActionStatus.OUT;

import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import server.haengdong.application.response.MemberBillReportAppResponse;
import server.haengdong.domain.action.Action;
import server.haengdong.domain.action.ActionRepository;
import server.haengdong.domain.action.BillAction;
import server.haengdong.domain.action.BillActionRepository;
import server.haengdong.domain.action.MemberAction;
Expand All @@ -23,7 +22,9 @@
import server.haengdong.domain.event.EventRepository;
import server.haengdong.exception.HaengdongErrorCode;
import server.haengdong.exception.HaengdongException;
import server.haengdong.support.extension.DatabaseCleanerExtension;

@ExtendWith(DatabaseCleanerExtension.class)
@SpringBootTest
class ActionServiceTest {

Expand All @@ -33,23 +34,12 @@ class ActionServiceTest {
@Autowired
private EventRepository eventRepository;

@Autowired
private ActionRepository actionRepository;

@Autowired
private BillActionRepository billActionRepository;

@Autowired
private MemberActionRepository memberActionRepository;

@AfterEach
void tearDown() {
billActionRepository.deleteAllInBatch();
memberActionRepository.deleteAllInBatch();
actionRepository.deleteAllInBatch();
eventRepository.deleteAllInBatch();
}

@DisplayName("참여자별 정산 현황을 조회한다.")
@Test
void getMemberBillReports() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
import static org.junit.jupiter.api.Assertions.assertAll;

import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import server.haengdong.application.request.BillActionAppRequest;
Expand All @@ -20,29 +20,21 @@
import server.haengdong.domain.event.Event;
import server.haengdong.domain.event.EventRepository;
import server.haengdong.exception.HaengdongException;
import server.haengdong.support.extension.DatabaseCleanerExtension;

@ExtendWith(DatabaseCleanerExtension.class)
@SpringBootTest
class BillActionServiceTest {

@Autowired
private BillActionService billActionService;

@Autowired
private ActionRepository actionRepository;

@Autowired
private EventRepository eventRepository;

@Autowired
private BillActionRepository billActionRepository;

@AfterEach
void tearDown() {
billActionRepository.deleteAllInBatch();
actionRepository.deleteAllInBatch();
eventRepository.deleteAllInBatch();
}

@DisplayName("지출 내역을 생성한다.")
@Test
void saveAllBillAction() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
import static server.haengdong.domain.action.MemberActionStatus.OUT;

import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
Expand All @@ -22,44 +22,34 @@
import server.haengdong.application.response.EventDetailAppResponse;
import server.haengdong.application.response.MembersAppResponse;
import server.haengdong.domain.action.Action;
import server.haengdong.domain.action.ActionRepository;
import server.haengdong.domain.action.BillAction;
import server.haengdong.domain.action.BillActionRepository;
import server.haengdong.domain.action.MemberAction;
import server.haengdong.domain.action.MemberActionRepository;
import server.haengdong.domain.event.Event;
import server.haengdong.domain.event.EventRepository;
import server.haengdong.domain.event.EventTokenProvider;
import server.haengdong.support.extension.DatabaseCleanerExtension;
import server.haengdong.exception.HaengdongException;

@ExtendWith(DatabaseCleanerExtension.class)
@SpringBootTest
class EventServiceTest {

@Autowired
private EventService eventService;

@MockBean
private EventTokenProvider eventTokenProvider;

@Autowired
private EventRepository eventRepository;

@Autowired
private ActionRepository actionRepository;

@Autowired
private BillActionRepository billActionRepository;

@Autowired
private MemberActionRepository memberActionRepository;

@AfterEach
void tearDown() {
billActionRepository.deleteAllInBatch();
memberActionRepository.deleteAllInBatch();
actionRepository.deleteAllInBatch();
eventRepository.deleteAllInBatch();
}
@MockBean
private EventTokenProvider eventTokenProvider;

@DisplayName("행사를 생성한다")
@Test
Expand Down Expand Up @@ -102,10 +92,10 @@ void findActionsTest() {

assertThat(actionAppResponses).hasSize(3)
.extracting(ActionAppResponse::actionId,
ActionAppResponse::name,
ActionAppResponse::price,
ActionAppResponse::sequence,
ActionAppResponse::actionTypeName)
ActionAppResponse::name,
ActionAppResponse::price,
ActionAppResponse::sequence,
ActionAppResponse::actionTypeName)
.containsExactly(
tuple(1L, "토다리", null, 1L, "IN"),
tuple(2L, "쿠키", null, 2L, "IN"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,24 @@
import static org.assertj.core.api.Assertions.tuple;

import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import server.haengdong.application.request.MemberActionSaveAppRequest;
import server.haengdong.application.request.MemberActionsSaveAppRequest;
import server.haengdong.domain.action.Action;
import server.haengdong.domain.action.CurrentMembers;
import server.haengdong.domain.event.Event;
import server.haengdong.domain.action.MemberAction;
import server.haengdong.domain.action.MemberActionRepository;
import server.haengdong.domain.action.MemberActionStatus;
import server.haengdong.domain.action.ActionRepository;
import server.haengdong.domain.event.Event;
import server.haengdong.domain.event.EventRepository;
import server.haengdong.domain.action.MemberActionRepository;
import server.haengdong.exception.HaengdongException;
import server.haengdong.support.extension.DatabaseCleanerExtension;

@ExtendWith(DatabaseCleanerExtension.class)
@SpringBootTest
class MemberActionFactoryTest {

Expand All @@ -32,19 +33,9 @@ class MemberActionFactoryTest {
@Autowired
private MemberActionRepository memberActionRepository;

@Autowired
private ActionRepository actionRepository;

@Autowired
private EventRepository eventRepository;

@AfterEach
void tearDown() {
memberActionRepository.deleteAllInBatch();
actionRepository.deleteAllInBatch();
eventRepository.deleteAllInBatch();
}

@DisplayName("이전 멤버 액션이 시퀀스 기준으로 정렬되지 않은 상태에서 새로운 멤버 액션 요청을 검증한다.")
@Test
void createMemberActionsTest() {
Expand Down Expand Up @@ -80,7 +71,7 @@ void createMemberActionsTest1() {

CurrentMembers currentMembers = CurrentMembers.of(List.of(memberAction));
List<MemberAction> memberActions = memberActionFactory.createMemberActions(memberActionsSaveAppRequest,
currentMembers, startAction
currentMembers, startAction
);

assertThat(memberActions).hasSize(1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,23 @@
import static server.haengdong.domain.action.MemberActionStatus.OUT;

import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import server.haengdong.application.request.MemberActionSaveAppRequest;
import server.haengdong.application.request.MemberActionsSaveAppRequest;
import server.haengdong.domain.action.Action;
import server.haengdong.domain.action.ActionRepository;
import server.haengdong.domain.action.MemberAction;
import server.haengdong.domain.action.MemberActionRepository;
import server.haengdong.domain.action.MemberActionStatus;
import server.haengdong.domain.event.Event;
import server.haengdong.domain.event.EventRepository;
import server.haengdong.exception.HaengdongException;
import server.haengdong.support.extension.DatabaseCleanerExtension;

@ExtendWith(DatabaseCleanerExtension.class)
@SpringBootTest
class MemberActionServiceTest {

Expand All @@ -36,16 +37,6 @@ class MemberActionServiceTest {
@Autowired
private EventRepository eventRepository;

@Autowired
private ActionRepository actionRepository;

@AfterEach
void tearDown() {
memberActionRepository.deleteAllInBatch();
actionRepository.deleteAllInBatch();
eventRepository.deleteAllInBatch();
}

@DisplayName("현재 행사에 참여하고 있는 경우에 나갈 수 있다.")
@Test
void saveMemberActionTest() {
Expand Down Expand Up @@ -118,7 +109,7 @@ void deleteMember() {
memberActionService.deleteMember(token, "참여자");

List<MemberAction> memberActions = memberActionRepository.findAll();

assertThat(memberActions).hasSize(5)
.extracting("memberName", "status")
.containsExactly(
Expand Down
Copy link
Contributor

Choose a reason for hiding this comment

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

c: 다음과 같이 truncateTablesQuery를 미리 저장해 놓는 방식으로 해 봐도 좋을 것 같아요

@PostConstruct
    public void getTableNames() {
        String sql = """
                SELECT TABLE_NAME
                FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = 'PUBLIC'
                """;
        List<String> tableNames = em.createNativeQuery(sql).getResultList();
        StringBuilder stringBuilder = new StringBuilder();

        for (String tableName : tableNames) {
            String truncateQuery = String.format(TRUNCATE_FORMAT, tableName);
            stringBuilder.append(truncateQuery);
        }
        truncateTablesQuery = stringBuilder.toString();
    }

    private void truncate() {
        em.createNativeQuery(String.format(REFERENTIAL_FORMAT, false)).executeUpdate();
        em.createNativeQuery(truncateTablesQuery).executeUpdate();
        em.createNativeQuery(String.format(REFERENTIAL_FORMAT, true)).executeUpdate();
    }

실행 결과
image

Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package server.haengdong.support.extension;

import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
class DatabaseCleaner {

private static final String REFERENTIAL_FORMAT = "set referential_integrity %b;";
private static final String TRUNCATE_FORMAT = "truncate table %s restart identity;";

@PersistenceContext
private EntityManager em;
private String truncateTablesQuery;

@PostConstruct
public void createTruncateQuery() {
List<String> tableNames = getTableNames();
StringBuilder stringBuilder = new StringBuilder();

for (String tableName : tableNames) {
String truncateQuery = String.format(TRUNCATE_FORMAT, tableName);
stringBuilder.append(truncateQuery);
}
truncateTablesQuery = stringBuilder.toString();
}

private List<String> getTableNames() {
String sql = """
select table_name
from information_schema.tables
where table_schema = 'PUBLIC'
""";
return em.createNativeQuery(sql).getResultList();
}

@Transactional
public void clear() {
em.clear();
truncate();
}

private void truncate() {
em.createNativeQuery(String.format(REFERENTIAL_FORMAT, false)).executeUpdate();
em.createNativeQuery(truncateTablesQuery).executeUpdate();
em.createNativeQuery(String.format(REFERENTIAL_FORMAT, true)).executeUpdate();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package server.haengdong.support.extension;

import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;

public class DatabaseCleanerExtension implements AfterEachCallback {

@Override
public void afterEach(ExtensionContext context) {
DatabaseCleaner databaseCleaner = getDataCleaner(context);
databaseCleaner.clear();
}

private DatabaseCleaner getDataCleaner(ExtensionContext extensionContext) {
return SpringExtension.getApplicationContext(extensionContext)
.getBean(DatabaseCleaner.class);
}
}
Loading