Skip to content

Commit

Permalink
add: rollback 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
leehjhjhj committed Jul 20, 2024
1 parent 512aa5b commit b0ef67a
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions python/나만의 pytest.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,23 @@ def test_date():
```python
@pytest.fixture(scope="function")
def db(self):
session = SessionMaker()
```

### rollback

- 본격적으로 롤백에 대해서 알아보자. 지속적으로 테스트를 진행하다보면 미리 준비된 fixture sql문을 실행한다.

```python
class TestMatching:
sql_file_path = 'tests/fixture.sql'
```

- 그리고 해당 sql문을 읽고 `excute`한 DB 세션을 yield한다. 이것을 fixture로 생성한다.

```python
@pytest.fixture(scope="function")
def db(self):
session = SessionLocal_Write()
with open(self.sql_file_path, 'r') as file:
sql_statements = file.read()
for statement in sql_statements.strip().split(';'):
Expand All @@ -72,4 +88,10 @@ def test_date():
yield session
session.rollback()
session.close()
```
```

- `rollback()`을 하지 않으면 테스트 하나 당 SQL 문이 반복적으로 돌기 때문에 pk 중복 등 테스트가 정상적으로 작동하지 않는다.
- 하지만 더 중요한 것은 테스트 내에서 `commit()` 이다. 저장이나 수정 로직이 정상적으로 실행됐는지 알기 위해서는 commit을 한 뒤의 결과를 알아야 한다.
- 하지만 앞서 탐구했듯, 한 `trasaction`에서는 하나의 commit과 rollback 만 허용되고, 이 이후에는 트랜잭션을 종료시킨다.
- 따라서 commit이 반복적으로 이뤄지는 로직에 `with session.begin_nested():` 을 추가하여 nested trasaction을 생성한다.
- 이렇게 되면 transaction 하나에 하나의 commit이 보장되고, 테스트를 안정적으로 할 수 있다.

0 comments on commit b0ef67a

Please sign in to comment.