天天看點

pytest架構進階自學系列 | fixture應用在初始化設定

作者:熱愛程式設計的通信人

書籍來源:房荔枝 梁麗麗《pytest架構與自動化測試應用》

一邊學習一邊整理老師的課程内容及實驗筆記,并與大家分享,侵權即删,謝謝支援!

附上彙總貼:pytest架構進階自學系列 | 彙總_熱愛程式設計的通信人的部落格-CSDN部落格

初始化過程一般進行資料初始化、連接配接初始化等。

常用場景:測試用例執行時,有的用例的資料是可讀取的,需要把資料讀進來再執行測試用例。setup和teardown可以實作。fixture可以靈活命名實作。

具體實作步驟:

(1)導入pytest。

(2)建立data()函數。

(3)在data()函數上加@pytest.fixture()。

(4)在要使用的測試方法test_login中傳入(data函數名稱),也就是先執行data()函數再執行測試方法。

(5)不傳入參數表明可以直接執行測試方法。

代碼如下:

import pytest
import csv

@pytest.fixture()
def data():
    test_data = {'name': 'linda', 'age': 18}
    return test_data

def test_login(data):
    name = data['name']
    age = data['age']
    print("筆者的名字叫:{},今年{}。".format(name, age))           

如果測試資料是從csv檔案中讀取的,執行操作步驟如下:

(1)建立userinfo.csv檔案,代碼如下:

import pytest
import csv

@pytest.fixture()
def data():
    test_data = {'name': 'linda', 'age': 18}
    return test_data

def test_login(data):
    name = data['name']
    age = data['age']
    print("筆者的名字叫:{},今年{}。".format(name, age))           

(2)在test_fixture_data.py中增加代碼如下:

import pytest
import csv

@pytest.fixture()
def data():
    test_data = {'name': 'linda', 'age': 18}
    return test_data

def test_login(data):
    name = data['name']
    age = data['age']
    print("筆者的名字叫:{},今年{}。".format(name, age))

@pytest.fixture()
def read_data():
    with open('userinfo.csv') as f:
        row = csv.reader(f, delimiter=',')
        next(row)
        users = []
        for r in row:
            users.append(r)
    return users

def test_logins(read_data):
    name = read_data[0][0]
    age = read_data[0][1]
    print("s筆者的名字叫:{},今年{}。".format(name, age))           

(3)滑鼠右擊選擇pytest執行。

D:\SynologyDrive\CodeLearning\WIN\pytest-book\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2022.1.3\plugins\python-ce\helpers\pycharm\_jb_pytest_runner.py" --path D:/SynologyDrive/CodeLearning/WIN/pytest-book/src/chapter-3/test_fixture_data.py
Testing started at 11:21 ...
Launching pytest with arguments D:/SynologyDrive/CodeLearning/WIN/pytest-book/src/chapter-3/test_fixture_data.py in D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-3

============================= test session starts =============================
platform win32 -- Python 3.7.7, pytest-5.4.1, py-1.11.0, pluggy-0.13.1 -- D:\SynologyDrive\CodeLearning\WIN\pytest-book\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\SynologyDrive\CodeLearning\WIN\pytest-book
collecting ... collected 2 items

test_fixture_data.py::test_login PASSED                                  [ 50%]筆者的名字叫:linda,今年18。

test_fixture_data.py::test_logins PASSED                                 [100%]s筆者的名字叫:linda,今年18。


============================== 2 passed in 0.01s ==============================

Process finished with exit code 0
           

繼續閱讀