- 유닛테스트와 TDD
- 유닛테스트란?
- 하나의 모듈을 기준으로 독립적으로 진행되는 가장 작은 단위의 테스트
- TDD란?
- 테스트가 주도하는 개발
- 항상 실패하는 테스트를 먼저 작성 (RED)
- 테스트가 통과하는 프로덕션 코드를 작성 (GREEN)
- 테스트가 통과하면 프로덕션 코드를 리펙토링
pip install pytest
pip install pytest-watch
pip freeze > requirements.txt
- pytest
- fixture
- pytest가 테스트를 진행하면서 공통적으로 이용할 수 있는 자원
-
데코레이터를 사용하여 정의
- scope (범위)
- default – function
- Higher-scoped fixtures are executed first (상위 범위가 먼저 실행되게 하려면 fixture 범위[scope] 설정)
- lower-scoped fixtures : such as
function or class
- higher-scopes fixtures: such as
session
import pytest
@pytest.fixture(scope="session")
def order():
return []
@pytest.fixture
def func(order):
order.append("function")
@pytest.fixture(scope="class")
def cls(order):
order.append("class")
@pytest.fixture(scope="module")
def mod(order):
order.append("module")
@pytest.fixture(scope="package")
def pack(order):
order.append("package")
@pytest.fixture(scope="session")
def sess(order):
order.append("session")
class TestClass:
def test_order(self, func, cls, mod, pack, sess, order):
assert order == ["session", "package", "module", "class", "function"]
- conftest.py
- Test시 fixture 를 이곳에서 초기 설정
- pytest 실행시 함께 실행
- 파일을 분리할 때 fixture들은 conftest 파일로 정리하는 것이 좋습니다
import pytest
@pytest.fixture
def order():
return []
@pytest.fixture
def outer(order, inner):
order.append("outer")
class TestOne:
@pytest.fixture
def inner(self, order):
order.append("one")
def test_order(self, order, outer):
assert order == ["one", "outer"]
class TestTwo:
@pytest.fixture
def inner(self, order):
order.append("two")
def test_order(self, order, outer):
assert order == ["two", "outer"]
- configs.py
- pytest 실행 시 테스트 환경으로 어플리케이션에 설정해야할 환경 변수
- __test__ : 테스트 대상 여부
- test prefix : Test로 시작하는 함수, _test로 시작하는 파일
- SQLALCHEMY_DATABASE_URI
class TestingConfig(DevelopmentConfig):
TESTING = True
SQLALCHEMY_DATABASE_URI = f'sqlite:///{os.path.join(BASE_PATH, "sqlite_test.db")}'
# 해당 내용이 test prefix에 걸리지만 test 리스트에서 제외되도록 하는 옵션
__test__ = False
- pytest.ini
- pytest 명령시 함께 실행되는 기본 설정 파일
[pytest]
addopts = -sv
참고 자료