当前位置:网站首页>pytest 之 fixture的定义及作用域
pytest 之 fixture的定义及作用域
2022-08-09 13:06:00 【沉觞流年】
pytest 之 fixture的定义及作用域
在 unittest 中 的前置与后置,是有固定名称的,通常是和测试类一起
例如: setup
、teardown
;setupclass
、teardownclass
而 pytest 中 的前置与后置,与 unittest 却有着很大的区别:
- 没有固定的名字。也就是没有像 unittest 中去调用
setup
、teardown
函数 - 前置后置放在一个函数里,通过
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 中 的
setup
、teardown
,中间夹着一个对应函数的测试用例 - class 作用于测试类,相当于unittest 中 的
setupclass
、teardownclass
,中间夹着一个测试类下的一个或多个测试用例 - 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_answer
和 test_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 中前置和后置调用,通常都是在执行函数或类的时候调用,其余两种作用域,并不常用,就不再一一举例说明
边栏推荐
猜你喜欢
随机推荐
ARM board adds routing function
FFmpeg相机花屏花图问题解决方法
陈强教授《机器学习及R应用》课程 第十七章作业
乐东消防救援大队应邀为干部开展消防安全培训
R语言kaggle 游戏数据探索与可视化
为什么文字不贴合边
19、学习MySQL 索引
GIN Bind mode to get parameters and form validation
FFmpeg av_interleaved_write_frame错误
从房产中介到程序员--80后张江男
GIN初探,环境安装
kustomize entry example and basic syntax instructions
LeetCode 37. Solve Sudoku
Q_06_03 表达式
【瑞吉外卖】day05:增、删、改、查分类以及公共字段自动填充
X264性能优化
Microsoft 10/11 命令行打开系统设置页(WUAP,!WIN32)
技嘉显卡 RGBFusion 不能调光解决方法
RTSP协议的实现
An Offer 21. Adjust the array in order to make odd in even the front (loop invariant)