如何在非测试类Server中使用conftest.py的fixture获取pytest命令行参数
pytest 命令行--stack参数传入Server类属性实现方案
原有代码
Server.py
class Server(): def __init__(self, certral=None, user=None, password=None): cwd = os.path.dirname(__file__) self.propPath = cwd + "/../server-profiles.json" print(os.path.normpath(self.propPath)) with open(os.path.normpath(self.propPath)) as data_file: data = json.load(data_file) self.propertyDataJson = data self.testcategory = data['generic']['category']
原代码中
self.propertyDataJson = data行缩进不符合Python语法规范,运行会直接触发语法报错,后续修改版本已经修复该问题。
conftest.py
def pytest_addoption(parser): parser.addoption( "--stack", action="store", default="sanity", help="my option: sanity or qa" ) @pytest.fixture def cmdopt(request): return request.config.getoption("--stack")
目标
执行pytest xyz.py --stack=sanity/pytest xyz.py --stack=qa命令时,命令行传入的--stack值会自动赋值给Server实例的self.testcategory属性。
修改步骤
- 修正Server类构造方法,新增可选入参接收外部传入的category值,优先使用外部传值,无传值时回退读取本地配置文件的默认值,修改后Server.py代码:
import os import json class Server(): # 新增testcategory可选参数 def __init__(self, certral=None, user=None, password=None, testcategory=None): cwd = os.path.dirname(__file__) self.propPath = cwd + "/../server-profiles.json" norm_prop_path = os.path.normpath(self.propPath) print(norm_prop_path) with open(norm_prop_path) as data_file: data = json.load(data_file) self.propertyDataJson = data # 优先取外部传入的testcategory,没传就用配置文件默认值 self.testcategory = testcategory if testcategory is not None else data['generic']['category']
- 调整conftest.py,新增Server实例的fixture,把命令行解析到的
--stack参数值在实例化时传入Server:
import pytest # 按你实际的项目路径调整Server的导入语句 from your_module.Server import Server def pytest_addoption(parser): parser.addoption( "--stack", action="store", default="sanity", help="option: sanity or qa" ) @pytest.fixture def stack_val(request): return request.config.getoption("--stack") @pytest.fixture def server(stack_val): # 实例化时把命令行拿到的stack值传入 return Server(testcategory=stack_val)
测试用例调用示例
在测试文件里直接注入server fixture即可拿到配置好的实例:
# xyz.py def test_demo(server): # 执行pytest xyz.py --stack=qa时,这里打印值为qa # 执行pytest xyz.py --stack=sanity时,这里打印值为sanity print(server.testcategory) assert server.testcategory in ("sanity", "qa")
内容的提问来源于stack exchange,提问作者RR HS
相关产品推荐
相关产品推荐

