场景:
对于一个py文件中某些用例需要前置条件,某些用例不需要前置条件的情况,使用setup/teardown肯定是不方便的,
这时就需要自定义测试用例的前置条件。
1、fixture优点:
2、fixture参数传入(scope=‘function’)
针对函数有效,需要前置条件的传入fixture就行
scope 有四个级别参数 "function" (默认), "class", "module" or "session"
如下示例:用例1需要先登录,用例2不需要登录,用例3需要先登录
# 新建一个文件test_fixt.py # coding:utf-8 import pytest # 不带参数时默认scope="function" @pytest.fixture() def login(): print("输入账号,密码先登录") def test_s1(login): print("用例1:登录之后其它动作111") def test_s2(): # 不传login print("用例2:不需要登录,操作222") def test_s3(login): print("用例3:登录之后其它动作333")
3、conftest.py配置文件
上面一个案例是在同一个.py文件中,多个用例调用一个登陆功能,如果有多个.py的文件都需要调用这个登陆功能的话,那就不能把登陆写到用例里面去了。
此时应该要有一个配置文件,单独管理一些预置的操作场景,pytest里面默认读取conftest.py里面的配置
conftest.py配置注意点
__init__.py conftest.py # coding:utf-8 import pytest @pytest.fixture() def login(): print("输入账号,密码先登录") test_fix1.py # coding:utf-8 import pytest def test_s1(login): print("用例1:登录之后其它动作111") def test_s2(): # 不传login print("用例2:不需要登录,操作222") def test_s3(login): print("用例3:登录之后其它动作333") if __name__ == "__main__": pytest.main(["-s", "test_fix1.py"]) test_fix2.py # coding:utf-8 import pytest def test_s4(login): print("用例4:登录之后其它动作111") def test_s5(): # 不传login print("用例5:不需要登录,操作222") if __name__ == "__main__": pytest.main(["-s", "test_fix2.py"])
单独运行test_fix1.py和test_fix2.py都能调用到login()方法,这样就能实现一些公共的操作可以单独拿出来了
(参考悠悠博客)
原文:https://www.cnblogs.com/wulixia/p/12176949.html