[TDD]pytestを使用したTDD


👉 pytest?


pythonをテストするためのフレームワーク

👉 使用


使用する前に、


pytestを使用するには、まずpytestを追加する必要があります.
$> pip install pytest

# poetry를 사용한다면 개발자 옵션으로 pytest dependency 추가
$> poetry add -D pytest
pytestを追加した場合は、テストするファイルを作成するだけで済みます.
テストに使用するファイルはtestsという名前の個別ディレクトリで管理され、テストに使用する関数はtestで始まる必要があり、ファイル名もpytestでテストを検出して実行する必要があります.

▼▼▼pytestを実行


テストコードが作成されている場合は、テストコードが正常に動作していることを確認するために実行します.
$> py.test -ssv #전체 실행
$> py.test -ssv 파일명.py #특정 파일에 존재하는 test 함수 실행
$> py.test -ssv 파일명.py::함수이름 #특정 파일의 특정 함수만 실행

#or
$> pytest 파일명.py 

$> pytest -v #더 자세한 테스트 결과를 확인할 수 있음
pytest # 존재하는 모든 test를 모두 실행

$> pytest [dir경로] # 해당 directory에 존재하는 모든 test_...py 파일 모두 실행

$> pytest [파일 경로] # 해당 파일에 존재하는 모든 test 함수 실행

$> pytest [파일 경로]::테스트함수명 # 특정 test 함수만 실행

それ以外のオプションは$> pytest --helpで確認できます.

▼▼▼pytestを利用


- pytest.fixture()
重複する部分に対してfixtureを宣言し、fixture関数をパラメータとしてテストします.
fixtureを使用すると、宣言するたびに必要な値をparameterで簡単に取得できます.
import pytest

@pytest.fixture
def calculator():
	calculator = Calculator()
	return calculator

def test_add(calculator):
	#calculator = Calculator() >> 원래 반복적으로 선언해줘야 했던 부분
	assert calculator.add(1, 2) == 3
	
def test_subtract(calculator):
	#calculator = Calculator()
	assert calculator.subtract(5, 1) == 4
これらのfixtureは、すべてのテストコードで共有および書き込みできるように、conftest.pyというファイルにマージして宣言できます.

  • Dir構造👇
    tests
         L conftest.py
         L clacl.py->Calc()存在
         L test_clac.py

  • conftest.py 👇
  • from calc import Calc
    
    import pytest
    
    @pytest.fixture
    def calc():
    	calc = Calc()
    	return calc
  • test_calc.py 👇
  • def test_add_two_numbers(calc):
    	res = calc.add(3,4)
    	
    	assert res == 7
    
    def test_sub_two_numbers(calc):
    	res = calc.sub(5,1)
    
    
    	assert res == 4
    - pytest.昇格(Error名)
    エラーが発生したテストを作成し、エラーが発生したかどうかを確認できます.
    import pytest
    
    def test_func():
    	with pytest.raises(Error명):
    		#error가 발생하기를 바라는 코드
            
    	# 예외에 대한 직접적인 정보를 얻고자 할 때 사용
    	with pytest.raises(error) as e:
    		# 코드
    
    	# 스트링으로 나타낸 예외 상황과 넘겨 받은 파라미터가 일치하는지 확인
    	# -> 예외의 메세지 값
    	with pytest.raises(error, match=""):
    		# 코드
    - pytest.おおよそ
    import pytest
    
    def test_func():
    	res = 실행
    	
    	assert res == pytest.approx() #적힌 값과 유사한 값이 도출되는지 검사
    - pytest.mark.skip(メッセージ)
    テストコードを実行したくない場合に使用します.
    @pytest.mark.skip('message')
    def test_img_src_factory():
        # 테스트 내용.....
    - pytest.mark.order(シーケンス値)
    所定の手順でテストを行いたい場合に使用します.
    @pytest.mark.order(순서)
    def test_order():
    	# 테스트 내용...
    pytest orderを使用するには、pytest-orderプラグインをインストールする必要があります.
    👉 pytest-order docs
    $> pip install pytest-order
    
    # poetry 사용 시
    $> poetry add -D pytest-order
    - debugging
    $> pytest --pdb #모든 실패마다 멈춤
    $> pytest -x --pdb #첫번째 실패에 멈추고 test session 종료
    $> pytest -pdb --maxfail=n #n번째 실패까지
    
    $> pytest --trace #debugging처럼 진행 과정을 따라갈 수 있음(매 test마다 멈춤)