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文件,代码如下:

username,age
linda,18
tom,8
steven,28

(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

猜你喜欢

转载自blog.csdn.net/guolianggsta/article/details/131593358