본문 바로가기
C.W.K.
Stream
Lesson 05 of 10 · published

테스트 전략 — In-Memory + Fixture

~12 min · testing, fixtures, production

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

테스트 DB로 쓸 때 SQLite는 거의 반칙이야

SQLite는 테스트 준비를 거의 공짜로 만들어줘. 잘 테스트된 codebase마다 빠지지 않고 나오는 전략이 셋 있어.

  • 테스트마다 :memory:sqlite3.connect(':memory:')로 열고, migration을 돌리고, 테스트를 굴리면, 프로세스가 끝날 때 DB도 같이 사라져. 준비가 가장 빨라.
  • 테스트마다 tempfile — :memory:와 같은데 파일로 남아. 코드가 connection을 닫았다 다시 열어야 할 때 필요해.
  • 템플릿 하나 만들어두고 복사 — fixture DB를 한 번 만들어두고 테스트마다 파일을 복사해 써. migration이 비쌀 때 빨라.
Self-reference: 피파 테스트는 pytest fixture로 :memory: 패턴을 써. store 계층 테스트마다 밀리초 안에 텅 빈 새 DB가 나와. 테스트가 100개 넘는 backend suite가 2초쯤에 끝나는 게 그래서야.

Code

pytest fixture — 테스트마다 새 store·python
import pytest, asyncio, aiosqlite

@pytest.fixture
async def store(tmp_path):
    # tempfile 로 file locking 도 운동
    path = tmp_path / 'test.db'
    s = await ConversationStore.open(str(path))
    yield s
    await s.conn.close()

async def test_create_and_list(store):
    cid = await store.create_conversation('Hello')
    convs = await store.list_conversations()
    assert len(convs) == 1
    assert convs[0]['id'] == cid
순수 :memory: — 가장 빠름, file I/O 없음·python
import sqlite3

def test_pure_in_memory():
    conn = sqlite3.connect(':memory:')
    conn.execute('CREATE TABLE t(id INTEGER PRIMARY KEY, v TEXT)')
    conn.execute('INSERT INTO t(v) VALUES (?)', ('hello',))
    assert conn.execute('SELECT v FROM t').fetchone() == ('hello',)

External links

Exercise

sqlite3를 쓰는 Python 프로젝트에 — 네 것이든 피파 것이든 — 테스트마다 새 DB를 주는 pytest fixture를 붙여봐. 테스트 사이에 상태가 새지 않고 suite가 잘 도는지 확인해. 그리고 tempfile과 WAL을 쓰는 변형도 하나 만들어서, 일반적인 CRUD 테스트에서는 동작이 같은지 검증해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.