1. 程式人生 > 實用技巧 >【PYTEST】第四章Fixture

【PYTEST】第四章Fixture

知識點:

  • 利用fixture共享資料
  • conftest.py共享fixture
  • 使用多個fixture
  • fixture作用範圍
  • usefixture
  • 重新命名

1.利用fixture共享資料

test_data中包含了一個fixture名為data,pytest會優先搜尋fixture,返回data值

pytest/ch3/test_one.py

import pytest

"""
fixture :
    @pytest.fixture
    聲明瞭一個fixture,如果測試函式中用到fixture名,那麼pytest會檢測到,並且再執行測試用例前,先執行fixture
"""

@pytest.fixture()
def data():
    return 3

def test_data(data):
    assert data == 4

2.conftest.py

  針對fixture,可以單獨放在一個檔案裡,如果你希望測試檔案共享fixture, 那麼在你當前的目錄下建立conftest.py檔案,將所有的fixture放進去,注意如果你只想作用於某一個資料夾,那麼在那個資料夾建立contest.py

pytest/ch3/conftest.py

import pytest
import requests

"""
如果想多個測試用例共享fixture,可以單獨建立一個conftest.py 檔案,可以看成提供測試用例使用的一個fixture倉庫
"""


@pytest.fixture()
def login():
    url = 'http://api.shoumilive.com:83/api/p/login/login/pwd'
    data = {"phone": "18860910", "pwd": "123456"}
    res = requests.post(url, data)
    return res.text

pytest/ch3/test_conftest.py

import json

import pytest

"""
通過conftest 建立公共倉庫,testcase獲取公共倉庫
"""
@pytest.mark.login
def test_conftest(login):
    data = json.loads(login)
    print(data['code'])
    assert data['code'] == '200'

if __name__ == '__main__':
pytest.main(["--setup-show", "-m", "login", "-s", "-v"])

3.使用多個fixture

pytest/ch3/conftest.py

@pytest.fixture()
def one():
    return 1

@pytest.fixture()
def two():
    return 2

pytest/ch3/test_muti.py

def test_muti(one, two):
    assert one == two

4. fixture 作用範圍

  用scope來指定作用範圍, 作用範圍有固定的待選值,fucntion, class, module, session(預設為function)

5.usefixture

  指定fixture ,使用@pytest.mark.usefixtures('')標記測試函式,或者測試類

6. 重新命名

  如果一個測試命名過長的話,我們可以使用name引數,給她重名了,我們使用fixture的時候,只需要傳入name值即可

@pytest.fixture(name='maoyan')
def test_maoyan_page_001():
    return 2