pytest之fixture
fixture [fɪkstʃɚ] 固定装置 。一直有听说这个很好用,所以学习了一下。但是网上文档有点多,搞得我很混乱,所以想理一理,记录一下,可能有不正确的地方,欢迎指教。
一、conftest.py
pytest里面默认读取conftest.py里面的配置,可单独管理一些预置的操作场景,
conftest.py配置需要注意以下点:
1、conftest.py配置脚本名称是固定的,不能改名称
2、conftest.py与运行的用例要在同一个目录下,并且有__init__.py文件
3、不需要import导入 conftest.py,pytest用例会自动查找
二、scope参数可以控制fixture的作用范围:session>module>class>function 默认是function
-function:每一个函数或方法都可以调用
-class: 每一个类调用一次,一个类中可以有多个方法
-module:每一个.py文件调用一次,该文件内又有多个function和class
-session:是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
下面来尝试并验证一下
1、function
test_case01.py 文件
import pytest
def test_one(login1):
x = "this"
assert 'h' in x
def test_two(login2):
x = "this"
assert 'h' in x
def test_three(login1):
x = "this"
assert 'h' in x
class TestCase01():
def test_one(self,login1):
x = "this"
assert 'h' in x
def test_two(self,login2):
x = "this"
assert 'h' in x
def test_three(self,login1):
x = "this"
assert 'h' in x
if __name__ == "__main__":
pytest.main(['-s','test_case01.py'])
conftest.py文件
import pytest
@pytest.fixture()
def login1():
print("输入账号1,密码先登录")
@pytest.fixture(scope='function')
def login2():
print("输入账号2,密码先登录")
运行结果:
test_case01.py 输入账号1,密码先登录
.输入账号2,密码先登录
.输入账号1,密码先登录
.输入账号1,密码先登录
.输入账号2,密码先登录
.输入账号1,密码先登录
2、class
conftest.py文件改为如下
import pytest
@pytest.fixture(scope='class')
def login1():
print("输入账号1,密码先登录")
@pytest.fixture(scope='class')
def login2():
print("输入账号2,密码先登录")
运行结果:
test_case01.py 输入账号1,密码先登录
.输入账号2,密码先登录
.输入账号1,密码先登录
.输入账号1,密码先登录
.输入账号2,密码先登录
3、module
conftest.py文件改为如下
import pytest
@pytest.fixture(scope='module')
def login1():
print("输入账号1,密码先登录")
@pytest.fixture(scope='module')
def login2():
print("输入账号2,密码先登录")
运行结果:
test_case01.py 输入账号1,密码先登录
.输入账号2,密码先登录
4、session
conftest.py文件改为如下
import pytest
@pytest.fixture(scope='session')
def login1():
print("输入账号1,密码先登录")
@pytest.fixture(scope='session')
def login2():
print("输入账号2,密码先登录")
运行结果:
test_case01.py 输入账号1,密码先登录
.输入账号2,密码先登录
浙公网安备 33010602011771号