You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pytest脚本中传递development.ini中的db_str配置变量?

问题:如何把development.ini里的db_str配置传给pytest测试脚本?

我最近在做测试的时候遇到个麻烦:想把development.ini里定义的配置变量db_str传递给我的pytest脚本test_script.py,但试了两种方法都没搞定:

  • 首先试了命令 pytest -c development.ini regression_tests/test_script.py,结果完全没生效,脚本跑起来直接抛KeyError: 'db_string'
  • 后来又写了conftest.py来加命令行参数,代码如下,但还是没解决问题:
import pytest
def pytest_addoption(parser):
    parser.addoption("--set-db_st", action="store",help="host='localhost' dbname='xyz' us...")

下面给你两种靠谱的解决思路,亲测有效:

方案1:直接在conftest里读取development.ini的配置

首先要搞清楚:pytest -c这个参数是用来指定pytest自己的配置文件(比如设置测试超时、启用插件这类pytest专属配置),不是用来加载你的项目业务配置的,所以之前用这个命令肯定拿不到db_str。

我们可以用Python自带的configparser模块直接解析development.ini,把配置读到fixture里,供测试脚本调用:

修改你的conftest.py:

import pytest
import configparser

def pytest_addoption(parser):
    # 可选:加个参数让用户可以指定配置文件路径,默认用当前目录的development.ini
    parser.addoption("--config", action="store", default="development.ini", help="Path to your project config file")

@pytest.fixture(scope="session")  # 会话级fixture,只加载一次
def db_str(request):
    # 获取配置文件路径
    config_path = request.config.getoption("--config")
    # 解析ini文件
    config = configparser.ConfigParser()
    config.read(config_path)
    # 这里要替换成你ini文件里的section名称,比如[app:main]或者[database]
    return config.get("your_section_name", "db_str")

然后在test_script.py里直接用这个fixture:

def test_database_connection(db_str):
    # 现在就能拿到db_str的值了
    print(f"拿到的数据库连接串:{db_str}")
    # 这里写你的测试逻辑,比如初始化数据库连接之类的

运行命令:

# 默认用当前目录的development.ini
pytest regression_tests/test_script.py

# 如果配置文件在别的路径,指定一下
pytest --config=/path/to/your/development.ini regression_tests/test_script.py

方案2:用命令行直接传递db_str参数

如果不想读配置文件,想直接在命令行传db_str,那需要修正你的conftest.py,加上传递参数的fixture:

更新conftest.py:

import pytest

def pytest_addoption(parser):
    parser.addoption("--db-str", action="store", required=True, 
                     help="Database connection string, e.g. host='localhost' dbname='xyz' user='test'")

@pytest.fixture(scope="session")
def db_str(request):
    # 把命令行参数的值返回给测试脚本
    return request.config.getoption("--db-str")

同样在test_script.py里使用db_str fixture:

def test_db_operation(db_str):
    # 验证参数是否传递成功
    assert db_str is not None, "数据库连接串不能为空"
    # 你的测试代码

运行命令:

pytest --db-str="host='localhost' dbname='xyz' user='test' password='123456'" regression_tests/test_script.py

顺便说下你之前踩的坑

  1. pytest -c的用途理解错了:它是给pytest自己用的配置,不是你的项目配置,所以用它加载development.ini没用;
  2. 之前的conftest.py只加了命令行参数,但没写fixture把参数传递给测试脚本,所以测试脚本根本拿不到这个值;
  3. 报错是KeyError: 'db_string',但你要的变量是db_str,注意检查下测试脚本里的变量名拼写是不是错了!

内容的提问来源于stack exchange,提问作者ghanisht nagpal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:16:47