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

test: Database cleaner 리팩토링 #389

Merged
merged 9 commits into from
Jun 16, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
69 changes: 27 additions & 42 deletions src/test/java/com/depromeet/DatabaseCleaner.java
Original file line number Diff line number Diff line change
@@ -1,52 +1,37 @@
package com.depromeet;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;
import org.hibernate.Session;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class DatabaseCleaner implements InitializingBean {

@PersistenceContext private EntityManager entityManager;
private List<String> tableNames;

@Override
public void afterPropertiesSet() {
entityManager.unwrap(Session.class).doWork(this::extractTableNames);
}

private void extractTableNames(Connection conn) {
tableNames =
entityManager.getMetamodel().getEntities().stream()
.map(e -> e.getName().replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase())
.collect(Collectors.toList());
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TransactionTemplate;

public abstract class DatabaseCleaner {
char-yb marked this conversation as resolved.
Show resolved Hide resolved

public static void clear(ApplicationContext applicationContext) {
var entityManager = applicationContext.getBean(EntityManager.class);
var jdbcTemplate = applicationContext.getBean(JdbcTemplate.class);
var transactionTemplate = applicationContext.getBean(TransactionTemplate.class);

transactionTemplate.execute(
status -> {
entityManager.clear();
deleteAll(jdbcTemplate, entityManager);
return null;
});
}

public void execute() {
entityManager.unwrap(Session.class).doWork(this::cleanUpDatabase);
}

private void cleanUpDatabase(Connection conn) throws SQLException {
Statement statement = conn.createStatement();
statement.executeUpdate("SET REFERENTIAL_INTEGRITY FALSE");

for (String tableName : tableNames) {
statement.executeUpdate("TRUNCATE TABLE " + tableName);
statement.executeUpdate(
"ALTER TABLE "
+ tableName
+ " ALTER COLUMN "
+ tableName
+ "_id RESTART WITH 1");
private static void deleteAll(JdbcTemplate jdbcTemplate, EntityManager entityManager) {
entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
for (String tableName : findDatabaseTableNames(jdbcTemplate)) {
entityManager
.createNativeQuery("TRUNCATE TABLE %s".formatted(tableName))
.executeUpdate();
}
entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY TRUE").executeUpdate();
}

statement.executeUpdate("SET REFERENTIAL_INTEGRITY TRUE");
private static List<String> findDatabaseTableNames(JdbcTemplate jdbcTemplate) {
return jdbcTemplate.query("SHOW TABLES", (rs, rowNum) -> rs.getString(1)).stream().toList();
}
}
26 changes: 26 additions & 0 deletions src/test/java/com/depromeet/NoTransactionExtension.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.depromeet;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@Slf4j
public class NoTransactionExtension implements BeforeEachCallback {

@Override
public void beforeEach(ExtensionContext extensionContext) {
var applicationContext = SpringExtension.getApplicationContext(extensionContext);
cleanDatabase(applicationContext);
}

private static void cleanDatabase(ApplicationContext applicationContext) {
try {
DatabaseCleaner.clear(applicationContext);
} catch (NoSuchBeanDefinitionException e) {
log.debug("Database Cleaning not supported.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;

import com.depromeet.DatabaseCleaner;
import com.depromeet.NoTransactionExtension;
import com.depromeet.domain.comment.dao.CommentRepository;
import com.depromeet.domain.comment.dto.request.CommentCreateRequest;
import com.depromeet.domain.comment.dto.request.CommentUpdateRequest;
Expand All @@ -22,9 +22,9 @@
import com.depromeet.global.security.PrincipalDetails;
import java.time.Duration;
import java.time.LocalDateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
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.security.authentication.UsernamePasswordAuthenticationToken;
Expand All @@ -34,22 +34,17 @@

@SpringBootTest
@ActiveProfiles("test")
@ExtendWith(NoTransactionExtension.class)
class CommentServiceTest {

private static final LocalDateTime NOW = LocalDateTime.of(2024, 3, 26, 5, 0, 0);

@Autowired private CommentService commentService;
@Autowired private CommentRepository commentRepository;
@Autowired private DatabaseCleaner databaseCleaner;
@Autowired private MemberRepository memberRepository;
@Autowired private MissionRepository missionRepository;
@Autowired private MissionRecordRepository missionRecordRepository;

@BeforeEach
void setUp() {
databaseCleaner.execute();
}

private Member saveAndRegisterMember() {
SecurityContextHolder.clearContext();
OauthInfo oauthInfo =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import static org.assertj.core.api.Assertions.*;

import com.depromeet.DatabaseCleaner;
import com.depromeet.NoTransactionExtension;
import com.depromeet.domain.comment.dao.CommentRepository;
import com.depromeet.domain.comment.domain.Comment;
import com.depromeet.domain.feed.domain.FeedVisibility;
Expand All @@ -26,9 +26,9 @@
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
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.data.domain.PageRequest;
Expand All @@ -41,22 +41,17 @@

@SpringBootTest
@ActiveProfiles("test")
@ExtendWith(NoTransactionExtension.class)
class FeedServiceTest {

@Autowired private FeedService feedService;
@Autowired private DatabaseCleaner databaseCleaner;
@Autowired private MemberRepository memberRepository;
@Autowired private MissionRepository missionRepository;
@Autowired private MissionRecordRepository missionRecordRepository;
@Autowired private ReactionRepository reactionRepository;
@Autowired private CommentRepository commentRepository;
@Autowired private MemberRelationRepository memberRelationRepository;

@BeforeEach
void setUp() {
databaseCleaner.execute();
}

private void logoutAndReloginAs(Long memberId) {
SecurityContextHolder.clearContext(); // 현재 회원 로그아웃
PrincipalDetails principalDetails = new PrincipalDetails(memberId, "USER");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.*;

import com.depromeet.DatabaseCleaner;
import com.depromeet.NoTransactionExtension;
import com.depromeet.domain.follow.dao.MemberRelationRepository;
import com.depromeet.domain.follow.domain.MemberRelation;
import com.depromeet.domain.follow.dto.request.FollowCreateRequest;
Expand All @@ -27,6 +27,7 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
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.security.authentication.UsernamePasswordAuthenticationToken;
Expand All @@ -36,8 +37,8 @@

@SpringBootTest
@ActiveProfiles("test")
@ExtendWith(NoTransactionExtension.class)
class FollowServiceTest {
@Autowired private DatabaseCleaner databaseCleaner;
@Autowired private MemberRepository memberRepository;
@Autowired private MemberRelationRepository memberRelationRepository;
@Autowired private MissionRepository missionRepository;
Expand All @@ -46,7 +47,6 @@ class FollowServiceTest {

@BeforeEach
void setUp() {
databaseCleaner.execute();
PrincipalDetails principal = new PrincipalDetails(1L, "USER");
Authentication authentication =
new UsernamePasswordAuthenticationToken(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import static org.assertj.core.api.AssertionsForClassTypes.*;

import com.depromeet.DatabaseCleaner;
import com.depromeet.NoTransactionExtension;
import com.depromeet.domain.image.domain.ImageFileExtension;
import com.depromeet.domain.image.dto.request.MissionRecordImageCreateRequest;
import com.depromeet.domain.image.dto.request.MissionRecordImageUploadCompleteRequest;
Expand Down Expand Up @@ -30,6 +30,7 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
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.security.authentication.UsernamePasswordAuthenticationToken;
Expand All @@ -39,8 +40,8 @@

@SpringBootTest
@ActiveProfiles("test")
@ExtendWith(NoTransactionExtension.class)
class ImageServiceTest {
@Autowired private DatabaseCleaner databaseCleaner;
@Autowired private MemberRepository memberRepository;
@Autowired private ImageService imageService;
@Autowired private MissionRecordService missionRecordService;
Expand All @@ -49,7 +50,6 @@ class ImageServiceTest {

@BeforeEach
void setUp() {
databaseCleaner.execute();
PrincipalDetails principal = new PrincipalDetails(1L, "USER");
Authentication authentication =
new UsernamePasswordAuthenticationToken(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.*;

import com.depromeet.DatabaseCleaner;
import com.depromeet.NoTransactionExtension;
import com.depromeet.domain.auth.domain.OauthProvider;
import com.depromeet.domain.follow.dao.MemberRelationRepository;
import com.depromeet.domain.follow.domain.MemberRelation;
Expand All @@ -24,6 +24,7 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
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.security.authentication.UsernamePasswordAuthenticationToken;
Expand All @@ -35,20 +36,15 @@
@SpringBootTest
@ActiveProfiles("test")
@WithMockUser
@ExtendWith(NoTransactionExtension.class)
class MemberServiceTest {

@Autowired EntityManager em;
@Autowired DatabaseCleaner databaseCleaner;
@Autowired MemberUtil memberUtil;
@Autowired MemberService memberService;
@Autowired MemberRepository memberRepository;
@Autowired MemberRelationRepository memberRelationRepository;

@BeforeEach
void setUp() {
databaseCleaner.execute();
}

private void saveAndRegisterMember(OauthInfo oauthInfo) {
Member member = Member.createNormalMember(oauthInfo, "testNickname");
memberRepository.save(member);
Expand Down Expand Up @@ -123,7 +119,6 @@ class 닉네임으로_회원을_검색할_때 {

@BeforeEach
void setUp() {
databaseCleaner.execute();
PrincipalDetails principal = new PrincipalDetails(1L, "USER");
Authentication authentication =
new UsernamePasswordAuthenticationToken(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import static org.assertj.core.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.*;

import com.depromeet.DatabaseCleaner;
import com.depromeet.NoTransactionExtension;
import com.depromeet.domain.member.dao.MemberRepository;
import com.depromeet.domain.member.domain.Member;
import com.depromeet.domain.member.domain.OauthInfo;
Expand All @@ -27,6 +27,7 @@
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
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.dao.DataIntegrityViolationException;
Expand All @@ -37,17 +38,16 @@

@SpringBootTest
@ActiveProfiles("test")
@ExtendWith(NoTransactionExtension.class)
class MissionServiceTest {

@Autowired private MissionService missionService;
@Autowired private MissionRepository missionRepository;
@Autowired private MemberRepository memberRepository;
@Autowired private DatabaseCleaner databaseCleaner;
@Autowired private MemberUtil memberUtil;

@BeforeEach
void setUp() {
databaseCleaner.execute();
PrincipalDetails principal = new PrincipalDetails(1L, "USER");
Authentication authentication =
new UsernamePasswordAuthenticationToken(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;

import com.depromeet.DatabaseCleaner;
import com.depromeet.NoTransactionExtension;
import com.depromeet.domain.member.dao.MemberRepository;
import com.depromeet.domain.member.domain.Member;
import com.depromeet.domain.member.domain.OauthInfo;
Expand All @@ -26,13 +26,15 @@
import java.time.LocalDateTime;
import java.time.LocalTime;
import org.junit.jupiter.api.*;
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;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest
@ActiveProfiles("test")
@ExtendWith(NoTransactionExtension.class)
class MissionRecordServiceTest {

private final LocalDateTime now = LocalDateTime.now();
Expand All @@ -43,14 +45,12 @@ class MissionRecordServiceTest {
@Autowired MissionRepository missionRepository;
@Autowired MissionRecordRepository missionRecordRepository;
@Autowired ReactionRepository reactionRepository;
@Autowired DatabaseCleaner databaseCleaner;
@MockBean SecurityUtil securityUtil;
private Member member;
private Mission mission;

@BeforeEach
void setUp() {
databaseCleaner.execute();
when(securityUtil.getCurrentMemberId()).thenReturn(1L);

member =
Expand Down
Loading
Loading