pytest入门九:feature

fixture是pytest特有的功能,用以在测试执行前和执行后进行必要的准备和清理工作。使用pytest.fixture标识,定义在函数前面 。在你编写测试函数的时候,你可以将此函数名称做为传入参数,pytest将会以依赖注入方式,将该函数的返回值作为测试函数的传入参数。

主要的目的是为了提供一种可靠和可重复性的手段去运行那些最基本的测试内容。

从功能上看来,与setup、teardown相似,但是优势明显:

调用方法有2种:

  • 1、在测试用例/测试类上面加上:@pytest.mark.usefixture("fixture的函数名字")

  • 2、将fixture函数名,作为测试用例函数的参数。可以不加@pytest.mark.usefixture("fixture的函数名字")

复制代码
import pytest


@pytest.fixture()
def init2():
    print("用例执行之前,执行的代码")  # 只有模块执行之前的前置准备代码

@pytest.mark.usefixtures('init2')
def test_1():
    print('test_2')

@pytest.mark.usefixtures('init2')
def test_2():
    print('test_2')

if __name__ == "__main__":
    pytest.main(['-v', '-s','test3.py']) #
复制代码
import pytest

@pytest.fixture
def init():
    print("用例执行之前,执行的代码")  # 前置代码
    yield 'hello'
    print("用例执行之后,执行的代码")  # 后置代码


@pytest.fixture()
def init2():
    print("用例执行之前,执行的代码")  # 只有模块执行之前的前置准备代码


def test_1(init):
    print('test_2',init)

@pytest.mark.usefixtures('init2')
def test_2():
    print('test_2')

if __name__ == "__main__":
    pytest.main(['-v', '-s','test3.py']) #
复制代码
import pytest

@pytest.fixture
def init():
    print("用例执行之前,执行的代码")  # 前置代码
    yield 'hello'
    print("用例执行之后,执行的代码")  # 后置代码

@pytest.fixture()
def init2():
    print("用例执行之前,执行的代码")  # 只有模块执行之前的前置准备代码


def test_1(init):
    print('test_2',init)


@pytest.mark.usefixtures('init2')
def test_2():
    print('test_2')

@pytest.fixture()
def data():
    return "hello"

def test_data(data):
    print("============",data)




if __name__ == "__main__":
    pytest.main(['-v', '-s','test3.py']) #

feature 嵌套

复制代码
import pytest

@pytest.fixture
def init():
    print("用例执行之前,执行的代码")  # 前置代码
    yield 'hello'
    print("用例执行之后,执行的代码")  # 后置代码

@pytest.fixture
def init3(init):
    print("用例执行2之前,执行的代码")  # 前置代码
    yield init
    print("用例执行2之后,执行的代码")  # 后置代码


def test_3(init3):
    assert init3 == 'hello'





if __name__ == "__main__":
    pytest.main(['-v', '-s','test3.py']) #
相关推荐
春风又。2 天前
接口自动化——初识pytest
python·测试工具·自动化·pytest
南部余额2 天前
playwright解决重复登录问题,通过pytest夹具自动读取storage_state用户状态信息
前端·爬虫·python·ui·pytest·pylawright
小码哥说测试5 天前
接口自动化进阶 —— Pytest全局配置pytest.ini文件详解!
自动化测试·软件测试·测试工具·自动化·pytest·测试工程师
天才测试猿5 天前
Python常用自动化测试框架—Pytest
自动化测试·软件测试·python·功能测试·测试工具·测试用例·pytest
Rhys..6 天前
2、pytest核心功能(进阶用法)
开发语言·python·pytest
一只天蝎的晋升之路7 天前
Python中常用的测试框架-pytest和unittest
开发语言·python·pytest
明月与玄武7 天前
pytest-xdist 进行高效并行自动化测试
pytest·pytest-xdist·进行高效并行自动化测试
测试笔记(自看)7 天前
Python+Requests+Pytest+YAML+Allure接口自动化框架
python·自动化·pytest·allure
活跃家族8 天前
Jsonpath使用
python·pytest
Rhys..8 天前
4、pytest常用插件
pytest