Test fixture on Pytest

Dahun Yoo·2021년 1월 16일
0

Introduce to Pytest

목록 보기
3/6
post-thumbnail

Pytest에서는 테스트를 위해 테스트 데이터의 생성이라던지, 테스트 준비를 위한 환경셋업 등을 위해 Test fixture 라는 기능을 제공해줍니다.

Test fixture

Test fixture란?
Software test fixtures initialize test functions. They provide a fixed baseline so that tests execute reliably and produce consistent, repeatable, results. Initialization may setup services, state, or other operating environments.
These are accessed by test functions through arguments; for each fixture used by a test function there is typically a parameter (named after the fixture) in the test function’s definition.

fixture

fixture는 테스트 프로젝트 내에 어떤 테스트케이스에서라도 접근할 수 있어야합니다.
Pytest에서는 이를 위해 특정 룰을 정하고 있는데요, fixture는 conftest.py 라는 이름의 파일 안에 선언을 해주어야합니다.

## conftest.py

from pytest import fixture
from selenium import webdriver

@fixture(scope='function')
def chrome_browser():
    # browser = webdriver.Chrome()
    browser = "Chrome"
    return browser

일단 fixture 를 사용하기 위해서는, pytest에서 fixture를 import를 해주고,
사용하고자하는 함수에 @fixture를 선언하고 scope를 지정해줍니다.

Scope
function: the default scope, the fixture is destroyed at the end of the test.
class: the fixture is destroyed during teardown of the last test in the class.
module: the fixture is destroyed during teardown of the last test in the module.
package: the fixture is destroyed during teardown of the last test in the package.
session: the fixture is destroyed at the end of the test session.

요컨데 scope는, fixture가 호출가능한 범위라고 생각하시면 될 것 같습니다. 예를들어 function 으로 지정하면, 각 함수마다 객체가 생성되고, 소멸됩니다.
session 으로 지정하면, 최초 테스트 실행시 단 한 번만 객체가 실행되며, 각각의 테스트에서 이 하나의 객체가 호출되는 형식입니다.


이후 사용할때에는 아래와 같이 사용합니다.

@mark.body
class BodyTests:

@mark.ui
def test_can_navigate_to_body_page(self, chrome_browser):
		first_browser = chrome_browser
		second_browser = chrome_browser
	    assert True
        

즉, 사용하고자하는 테스트케이스에서 파라미터로, fixture 함수의 이름을 지정해주면, 사용할 수 있게됩니다.

이렇게 fixture를 사용한다면, 테스트용 데이터들의 생성 및 검증이나, 환경설정 시에도 유용하게 사용할 수 있습니다.


yield

테스트 실행 후에 환경정리, 테스트 데이터들을 정리할때,
함수에서 yield 키워드를 사용해서 정리할 수 있습니다.
yield 는 호출한 테스트케이스가 실행종료되어도 마지막까지 실행되게끔 해주는 키워드입니다.

import pytest

from users_db import Users


@pytest.fixture
def db():
    users = Users()
    yield users

    print()
    for v in users.all():
        print(v)


def test_one(db):
    db.insert('Bob', 10)


def test_two(db):
    db.insert('Tom', 15)
    db.insert('Alice', 12)

실행 결과는 아래와 같습니다.

$ pytest -vs test_teardown_sample.py
============================= test session starts ==============================
platform darwin -- Python 3.7.1, pytest-4.1.1, py-1.7.0, pluggy-0.8.1 -- /Users/gaizaku/.pyenv/versions/3.7.1/envs/pytest_learning/bin/python
cachedir: .pytest_cache
rootdir: /Users/gaizaku/Develop/pytest_learning, inifile:
collected 2 items

test_teardown_sample.py::test_one PASSED
{'id': 1, 'name': 'Bob', 'age': 10}

test_teardown_sample.py::test_two PASSED
{'id': 1, 'name': 'Tom', 'age': 15}
{'id': 2, 'name': 'Alice', 'age': 12}


=========================== 2 passed in 0.01 seconds ===========================

Ref:
https://docs.pytest.org/en/latest/fixture.html
https://qiita.com/_akiyama_/items/9ead227227d669b0564e

profile
QA Engineer

0개의 댓글