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

[FEAT] truncate extension #45

merged 5 commits into from
Jul 23, 2024

Conversation

GIVEN53
Copy link
Member

@GIVEN53 GIVEN53 commented Jul 22, 2024

Issue Number

close #37

As-Is

  • 테스트간 격리 필요
  • 데이터를 삽입하는 sql 스크립트에 DDL과 DML 혼재

To-Be

  • DB의 모든 table들을 truncate하는 extension 적용
    • controller
    • service

@DataJpaTest는 제외

  • sql 스크립트에서 DDL 제거 및 formatting

Check List

  • 테스트가 전부 통과되었나요?
  • 모든 commit이 push 되었나요?
  • merge할 branch를 확인했나요?
  • Assignee를 지정했나요?
  • Label을 지정했나요?

Test Screenshot

스크린샷 2024-07-23 오전 1 38 16

(Optional) Additional Description

코드와 함께 설명을 첨부합니다

public class DatabaseCleanerExtension implements BeforeEachCallback { // (1)

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

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

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

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

    @SuppressWarnings("unchecked")
    private List<String> findTableNames(EntityManager em) {
        String tableSelectQuery = """
                SELECT TABLE_NAME
                FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = 'PUBLIC'
                """;
        return em.createNativeQuery(tableSelectQuery).getResultList(); // (8)
    }
}
  • (1) 각 테스트 케이스의 @BeforeEach 전에 실행할 작업을 정의하는 extension 인터페이스. (재사용성 증가)
  • (2) TestContext에서 ApplicationContext 추출.
  • (3) ApplicationContext bean 객체 추출.
  • (4) extension은 bean이 아니기 때문에 proxy로 동작하는 @Transactional 적용 불가. 따라서 TransactionTemplate을 사용하여 트랜잭션 제어.
  • (5) DB 참조 무결성 비활성화. (fk에 대한 참조 무결성을 비활성화하여 참조 순서와 상관없이 테이블 truncate)
  • (6) truncate DDL 실행 및 id counter 리셋.
  • (7) DB 참조 무결성 다시 활성화.
  • (8) 전체 테이블명 리턴.

@GIVEN53 GIVEN53 added ✅ test 테스트 관련 ✨ feat 기능 추가 🍃 BE back end labels Jul 22, 2024
@GIVEN53 GIVEN53 added this to the BE Sprint2 milestone Jul 22, 2024
@GIVEN53 GIVEN53 self-assigned this Jul 22, 2024
Copy link
Contributor

@leegwichan leegwichan left a comment

Choose a reason for hiding this comment

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

프린 고생많았어~

Comment on lines -21 to +24
Long recentContentId = 1L;
Long roomId = 1L;

// when
RoomContent actual = roomContentRepository.findTopByRoomIdOrderByCreatedAtDesc(recentContentId).get();
RoomContent actual = roomContentRepository.findTopByRoomIdOrderByCreatedAtDesc(roomId).get();
Copy link
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Member

@jhon3242 jhon3242 left a comment

Choose a reason for hiding this comment

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

응애 새로운거 많이 봤어요.. 나중에 또 물어볼게~ 응애

@GIVEN53 GIVEN53 merged commit 05adff1 into develop Jul 23, 2024
1 check passed
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이라 생각해서 사용했어요

Copy link
Member

@PgmJun PgmJun left a comment

Choose a reason for hiding this comment

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

LGTM🔥

@GIVEN53 GIVEN53 deleted the feat/#37 branch December 10, 2024 11:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🍃 BE back end ✨ feat 기능 추가 ✅ test 테스트 관련
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

[FEAT] truncate extension
4 participants