当前位置:网站首页>pytest 之 fixture的定义及作用域

pytest 之 fixture的定义及作用域

2022-08-09 13:06:00 沉觞流年

在 unittest 中 的前置与后置,是有固定名称的,通常是和测试类一起
例如: setupteardownsetupclassteardownclass

而 pytest 中 的前置与后置,与 unittest 却有着很大的区别:

  • 没有固定的名字。也就是没有像 unittest 中去调用 setupteardown函数
  • 前置后置放在一个函数里,通过 yield 关键字区分前置和后置
  • 独立的,不与测试类放在一起

pytest 中前置与后置的定义

pytest 中 的前置与后置,是通过定义函数实现的,在函数前加上 @pytest.fixture,那么这个函数就是 pytest 中 的前置与后置

@pytest.fixture
def init():
	pass

前置后置放在一个函数里,通过 yield 关键字区分前置和后置, yield 关键字前的内容为前置, yield 关键字后的内容为后置

@pytest.fixture
def init():
	driver = webdriver.Chrome()
	driver.get("http://www.baidu.com")
	yield
	driver.quit		

pytest 中前置与后置的作用域

pytest 中前置与后置的作用域可作用于 测试函数、类、模块、会话

@pytest.fixture(scope=?)
def init():
	pass

作用域:

  • function 默认值,作用于 测试函数。相当于unittest 中 的setupteardown,中间夹着一个对应函数的测试用例
  • class 作用于测试类,相当于unittest 中 的setupclassteardownclass,中间夹着一个测试类下的一个或多个测试用例
  • module 作用于测试模块(py文件)
  • session 作用于测试会话(本次运行收集到的所有用例)例如用于接口自动化连接数据库,前置用于连接数据库,后置用于关闭数据库

作用于函数

test_demo.py

import pytest

@pytest.fixture
def func_init():
    print("此处是用例的前置,作用于函数")
    yield
    print("此处是用例的后置,作用于函数")

def func(x):
    return x

def func2(x):
    return x+1

@pytest.mark.usefixtures("func_init")
def test_answer():

    assert func(5)==5


class TestDemo:

    @pytest.mark.usefixtures("func_init")
    def test_answer2(self):
        assert func(4) == 5


    def test_answer3(self):
        assert func2(4) == 5

在终端输入命令 pytest -s -v,可以发现
在这里插入图片描述

函数 test_answertest_answer2 调用了前置和后置里的内容。

如果把标识加在类上面呢?

test_demo2.py

import pytest

@pytest.fixture
def func_init():
    print("此处是用例的前置,作用于函数")
    yield
    print("此处是用例的后置,作用于函数")

def func(x):
    return x

def func2(x):
    return x+1

@pytest.mark.usefixtures("func_init")
class TestDemo2:

    def test_answer4(self):
        assert func(4) == 5


    def test_answer5(self):
        assert func2(4) == 5

在这里插入图片描述
可以发现,类里的每个函数,都调用了前置和后置。
所以说,pytest 中的函数或类通过打上 @pytest.fixture(scope=“function”) 标识时,只要执行了一次函数,就调用了前置和后置里的内容

作用于类

test_demo3.py

import pytest


@pytest.fixture(scope="class")
def class_init():
    print("此处是用例的前置,作用于类")
    yield
    print("此处是用例的后置,作用于类")


def func(x):
    return x

def func2(x):
    return x+1


@pytest.mark.usefixtures("class_init")
class TestDemo3:

    def test_answer6(self):
        assert func(4) == 5

    def test_answer7(self):
        assert func2(4) == 5

在终端输入命令 pytest -s -v,可以发现,虽然这个类里有两个函数,但前置和后置只调用了一次
在这里插入图片描述
也就是说,pytest 中的类通过打上 @pytest.fixture(scope=“class”) 标识时,执行了一次类里的内容,就调用了前置和后置里的内容

pytest 中前置和后置调用,通常都是在执行函数或类的时候调用,其余两种作用域,并不常用,就不再一一举例说明

原网站

版权声明
本文为[沉觞流年]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_44614026/article/details/114241916