前言
写自动化测试项目的时候,经常要用到配置文件,比如读取数据库相关的配置,希望单独放到 config 配置文件,方便维护。
pytest 的内置 fixture 可以获取到配置相关的信息,request.config.rootdir 用于获取项目的跟目录。
config 配置文件
再项目下新建一个 config 文件,相关配置信息用 yaml 文件维护数据
在conftest.py 下写读取配置文件的 fixture, 这里我设置为 autouse=True 主要是为了查看打印读取到的目录
import pytest
import os
import yaml
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
@pytest.fixture(scope="session", autouse=True)
def dbinfo(request):
dbfile = os.path.join(request.config.rootdir,
"config",
"dbenv.yml")
print("dbinfo file path :%s" % dbfile)
with open(dbfile) as f:
dbenv_config = yaml.load(f.read(), Loader=yaml.SafeLoader)
print(dbenv_config)
return dbenv_config
rootdir 读取
打开 cmd 命令行,在项目的跟目录运行用例
pytest -s
D:\wangyiyun\webauto>pytest -s
========