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] truncate extension #45

Merged
merged 5 commits into from
Jul 23, 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
@@ -1,13 +1,18 @@
package ddangkong.controller;


import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment;

import ddangkong.support.extension.DatabaseCleanerExtension;
import io.restassured.RestAssured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.jdbc.Sql;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(DatabaseCleanerExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@Sql(scripts = "/init-test.sql")
public abstract class BaseControllerTest {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import org.springframework.test.context.jdbc.Sql;

@DataJpaTest
@Sql(scripts = "/init-test.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/init-test.sql")
public abstract class BaseRepositoryTest {

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ class 방의_최신_질문_조회 {
@Test
void 방의_가장_최신의_질문을_조회할_수_있다() {
// given
Long recentContentId = 1L;
Long roomId = 1L;

// when
RoomContent actual = roomContentRepository.findTopByRoomIdOrderByCreatedAtDesc(recentContentId).get();
RoomContent actual = roomContentRepository.findTopByRoomIdOrderByCreatedAtDesc(roomId).get();
Comment on lines -21 to +24
Copy link
Contributor

Choose a reason for hiding this comment

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

오타 수정 감사합니다~~ ㅠ_ㅠ


// then
assertThat(actual.getId()).isEqualTo(2L);
Expand Down
7 changes: 6 additions & 1 deletion backend/src/test/java/ddangkong/service/BaseServiceTest.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package ddangkong.service;

import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment;

import ddangkong.support.extension.DatabaseCleanerExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;

@SpringBootTest
@ExtendWith(DatabaseCleanerExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
@Sql(scripts = "/init-test.sql")
public abstract class BaseServiceTest {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package ddangkong.support.extension;

import jakarta.persistence.EntityManager;
import java.util.List;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.support.TransactionTemplate;

public class DatabaseCleanerExtension implements BeforeEachCallback {

@Override
public void beforeEach(ExtensionContext extensionContext) {
ApplicationContext context = SpringExtension.getApplicationContext(extensionContext);
cleanup(context);
}

private void cleanup(ApplicationContext context) {
EntityManager em = context.getBean(EntityManager.class);
TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class);

transactionTemplate.execute(action -> {
em.clear();
truncateTables(em);
return null;
});
}

private void truncateTables(EntityManager em) {
em.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
for (String tableName : findTableNames(em)) {
em.createNativeQuery("TRUNCATE TABLE %s RESTART IDENTITY".formatted(tableName)).executeUpdate();
}
em.createNativeQuery("SET REFERENTIAL_INTEGRITY TRUE").executeUpdate();
}

@SuppressWarnings("unchecked")
Copy link
Member

Choose a reason for hiding this comment

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

질문) 이건 무슨 에노테이션인가요??

Copy link
Member Author

Choose a reason for hiding this comment

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

IDE warning을 제거하는 애노테이션입니다 Query 인터페이스의 getResultList()의 리턴 타입이 List인데, List<String>으로 받아서 그렇습니당
스크린샷 2024-07-23 오후 6 10 44

무시해도 될 warning이라 생각해서 사용했어요

private List<String> findTableNames(EntityManager em) {
String tableNameSelectQuery = """
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC'
""";
return em.createNativeQuery(tableNameSelectQuery).getResultList();
}
}
66 changes: 32 additions & 34 deletions backend/src/test/resources/init-test.sql
Original file line number Diff line number Diff line change
@@ -1,34 +1,32 @@
SET REFERENTIAL_INTEGRITY FALSE;

TRUNCATE TABLE member;
TRUNCATE TABLE balance_option;
TRUNCATE TABLE balance_content;
TRUNCATE TABLE balance_vote;
TRUNCATE TABLE room;
TRUNCATE TABLE room_content;

ALTER TABLE member ALTER COLUMN ID RESTART WITH 1;
ALTER TABLE balance_option ALTER COLUMN ID RESTART WITH 1;
ALTER TABLE balance_content ALTER COLUMN ID RESTART WITH 1;
ALTER TABLE balance_vote ALTER COLUMN ID RESTART WITH 1;
ALTER TABLE room ALTER COLUMN ID RESTART WITH 1;
ALTER TABLE room_content ALTER COLUMN ID RESTART WITH 1;

INSERT INTO room() VALUES ();

INSERT INTO member(nickname, room_id)
VALUES ('mohamedeu al katan', 1), ('deundeun', 1), ('rupi', 1), ('rapper lee', 1);

INSERT INTO room_content(room_id, balance_content_id, created_at)
VALUES (1, 2, '2024-07-18 19:50:00.000'), (1, 1, '2024-07-18 20:00:00.000');

INSERT INTO balance_content(category, name)
VALUES ('EXAMPLE', '민초 vs 반민초'), ('EXAMPLE', '월 200 백수 vs 월 500 직장인');

INSERT INTO balance_option(name, balance_content_id)
VALUES ('민초', 1), ('반민초', 1), ('월 200 백수', 2), ('월 200 직장인', 2);

INSERT INTO balance_vote(balance_option_id, member_id)
VALUES (4, 1), (4, 2), (4, 3), (4, 4), (1, 1), (1, 2), (1, 3), (2, 4);

SET REFERENTIAL_INTEGRITY TRUE;
INSERT INTO room ()
VALUES ();

INSERT INTO member (nickname, room_id)
VALUES ('mohamedeu al katan', 1),
('deundeun', 1),
('rupi', 1),
('rapper lee', 1);

INSERT INTO balance_content (category, name)
VALUES ('EXAMPLE', '민초 vs 반민초'),
('EXAMPLE', '월 200 백수 vs 월 500 직장인');

INSERT INTO room_content (room_id, balance_content_id, created_at)
VALUES (1, 2, '2024-07-18 19:50:00.000'),
(1, 1, '2024-07-18 20:00:00.000');

INSERT INTO balance_option (name, balance_content_id)
VALUES ('민초', 1),
('반민초', 1),
('월 200 백수', 2),
('월 200 직장인', 2);

INSERT INTO balance_vote (balance_option_id, member_id)
VALUES (4, 1),
(4, 2),
(4, 3),
(4, 4),
(1, 1),
(1, 2),
(1, 3),
(2, 4);