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
相关产品推荐
相关产品推荐

