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

Pytest tmpdir的mkdir方法不支持关键字参数报错,求优雅解决方案

解决办法

有两个优雅的方案,都不用修改生产代码或手动管理测试目录:

方案1:改用tmp_path fixture(推荐)

pytest从3.9版本开始提供了tmp_path fixture,它直接返回标准库的pathlib.Path实例,完全支持mkdir(parents=True, exist_ok=True)这类参数。直接替换测试里的tmpdir就行:

import pytest
from your_module import Foo

def test_persist_stuff(tmp_path):
    foo = Foo()
    # 直接用tmp_path拼接目标目录,传给persist_stuff
    target_dir = tmp_path / "test_subdir"
    foo.persist_stuff(target_dir)
    # 这里加你的断言逻辑,比如验证目录是否存在
    assert target_dir.exists()

方案2:将LocalPath转换为标准Path对象

如果因为某些原因不能用tmp_path,可以把tmpdir返回的LocalPath转换成标准Path:

from pathlib import Path
import pytest
from your_module import Foo

def test_persist_stuff(tmpdir):
    # 把LocalPath转成标准Path
    temp_path = Path(tmpdir)
    foo = Foo()
    target_dir = temp_path / "test_subdir"
    foo.persist_stuff(target_dir)
    assert target_dir.exists()

这两个方案都依赖pytest自动清理临时目录的机制,不用你手动处理,也完全不碰生产代码。

内容的提问来源于stack exchange,提问作者Georg Plaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:40:54