-
python pytest :: fixtures 사용해 보기Programming/Python 2023. 1. 3. 17:07반응형
아래 글은 공식 문서인 하단 링크를 참고하여 정리한 글 입니다.
https://docs.pytest.org/en/6.2.x/fixture.html
📍fixtures
fixture는 test를 위한 fixed baseline을 제공하는 도구이다.
즉 쉽게 말하면, test를 실행하기 전에 실행할 함수들을 정의하고, 그 함수들을 실행해서 테스트를 위한 고정된 환경을 구축할 수 있게 하는 도구이다.
테스트는 크게 4가지 단계로 이루어진다. Arrange, Act , Assert, Cleanup
fixture는 Arrage 단계에서 사용하게 되는데, 우리는 이 기능을 이용해 테스트를 위해 갖춰야할 환경들을 미리 갖춰 놓을 수 있다.
즉 쉽게 말하자면, test전에 실행되어야 할 함수를 정의하는데 사용하는 어노테이션이다~
//test_pytest_fixture.py import pytest class Fruit: def __init__(self, name): self.name = name def __eq__(self, other): return self.name == other.name @pytest.fixture def my_fruit(): return Fruit("apple") @pytest.fixture def fruit_basket(my_fruit): return [Fruit("banana"), my_fruit] def test_my_fruit_in_basket(my_fruit, fruit_basket): assert my_fruit in fruit_basket
✔️fixtures 호출하기, argument로 전달
basic하게 test에게 argument로 넘기는 방법 → test_my_fruit_in_basket(my_fruit, fruit_basket)
- pytest가 test를 실행하게 되면 function의 signature를 살펴보고 argument와 같은 이름을 가지고 있는 fixture를 찾는다.
- 찾은 후 이 fixture를 실행하고 return 값을 받아서 test function의 argument로 전달한다.
✔️ fixtures가 다른 Fixtures를 호출하는 방법
//test_pytest_fixture_request_fixtures.py import pytest #Arrage @pytest.fixture def first_entry(): return "a" #Arrange @pytest.fixture def order(first_entry): return [first_entry] def test_string(order): #Act order.append("b") #Assert assert order == ["a", "b"] def test_int(order): #Act order.append(2) #Assert assert order == ["a", 2]
- order 라는 fixtures를 재사용도 가능하다.
반응형'Programming > Python' 카테고리의 다른 글
[Python / pytest] pytest timeout, pytest 시간 제한하기 (0) 2023.05.11 데이터 추출과 삽질,,, 과정 기록 / python multi-threading (0) 2023.05.01 Python pytest 살펴보기, 예제 코드 (0) 2023.01.03 Python :: Non-ASCII character ‘xec’ (0) 2022.04.25