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 8 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
65 changes: 27 additions & 38 deletions src/test/java/com/depromeet/DatabaseCleaner.java
Original file line number Diff line number Diff line change
@@ -1,52 +1,41 @@
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;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TransactionTemplate;

@Component
public class DatabaseCleaner implements InitializingBean {
public class DatabaseCleaner {

@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());
private DatabaseCleaner() {
throw new IllegalStateException("Utility class");
}

public void execute() {
entityManager.unwrap(Session.class).doWork(this::cleanUpDatabase);
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;
});
}

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();
}
}
61 changes: 61 additions & 0 deletions src/test/java/com/depromeet/NoTransactionExtension.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.depromeet;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.test.context.TestContextAnnotationUtils;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
public class NoTransactionExtension implements BeforeEachCallback {

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

if (!validateDataJpaTestAnnotationExists(extensionContext)) {
validateTransactionalAnnotationExists(extensionContext);
}
cleanDatabase(applicationContext);
}

private static boolean validateDataJpaTestAnnotationExists(ExtensionContext extensionContext) {
return TestContextAnnotationUtils.hasAnnotation(
extensionContext.getRequiredTestClass(), DataJpaTest.class);
}

// Transactional 어노테이션이 존재하는지 검증하는 메서드
private static void validateTransactionalAnnotationExists(ExtensionContext extensionContext) {
if (TestContextAnnotationUtils.hasAnnotation(
extensionContext.getRequiredTestClass(), Transactional.class)
|| TestContextAnnotationUtils.hasAnnotation(
extensionContext.getRequiredTestClass(),
jakarta.transaction.Transactional.class)) {
Assertions.fail(
"테스트 클래스에 @Transactional 또는 @jakarta.transaction.Transactional 어노테이션이 존재합니다.");
}

if (AnnotatedElementUtils.hasAnnotation(
extensionContext.getRequiredTestMethod(), Transactional.class)
|| AnnotatedElementUtils.hasAnnotation(
extensionContext.getRequiredTestMethod(),
jakarta.transaction.Transactional.class)) {
Assertions.fail(
"테스트 메서드에 @Transactional 또는 @jakarta.transaction.Transactional 어노테이션이 존재합니다.");
}
}

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
Loading
Loading