pytest_addoption始终取默认值 Typer CLI传参不生效问题
问题原因
--app_file参数不生效是逻辑错误导致的,同时代码中还存在一个隐藏的subprocess传参bug:
- 核心原因:Typer命令和pytest子进程是两个完全独立的运行进程,你虽然在Typer层接收到了用户传入的
app_file=ghi参数,但构造pytest执行命令时,从未将该参数添加到命令列表中传递给pytest。pytest启动时没有收到--app_file入参,自然会读取conftest.py里pytest_addoption配置的默认值def。 - 隐藏bug:生成测试报告时,你把xml、html两个pytest参数拼接成了一个字符串塞入命令列表。
subprocess.run()接收列表格式的命令参数时,不会自动按空格拆分参数,会把整串内容识别为单个无效参数,导致报告生成功能也无法正常工作。 - 注意:你示例中执行命令写的
-markers='login'是错误写法,代码中定义的--markers是双横杠长参数,执行时必须写双横杠,否则会触发参数不存在的报错。
修复方案
- 修改
cli.py中的命令构造逻辑,将Typer接收到的app_file参数作为独立命令项,追加到pytest执行命令列表中。 - 拆分拼接的报告参数,把两个报告配置作为独立元素加入命令列表,避免subprocess传参解析错误。
修正后的run函数代码如下:
@app.command("run") def run( markers: str = typer.Option( "login", "--markers", help=( "Marker to run different tests. You can also use 'and', 'or'," " 'not' to select of deselect certain tests." ), ), report: bool = False, app_file: str = typer.Option( "abc", "--app_file", show_default=False, ), ): """Runs the tests for the given markers""" commands = ["pytest", "-m", markers, f"--app_file={app_file}"] if report: commands.append("--junitxml=test-reports/xml/report.xml") commands.append("--html=test-reports/html/report.html") logger.debug(f"Running command: {' '.join(commands)}") subprocess.run(commands)
- 执行命令时注意长参数使用双横杠前缀,正确命令格式为:
my_command run --markers='login' --app_file='ghi'
修改完成后重新执行命令,pytest即可正确接收到传入的ghi参数值,不会再读取默认值def。
内容的提问来源于stack exchange,提问作者pritom
相关产品推荐
相关产品推荐

