如何在类作用域fixture中使用pytest临时文件夹?
类内测试用例共享临时文件夹的解决方法
你遇到的ScopeMismatch错误,是因为tmp_path是函数作用域的fixture(每个测试函数都会生成独立临时目录),而你定义的new_path是类作用域,pytest不允许高作用域fixture引用低作用域fixture。下面是两种实现类内测试用例共享临时文件夹的可行方案:
方法一:利用tmp_path_factory创建类作用域临时目录
tmp_path_factory是会话作用域的fixture,支持生成任意作用域的临时路径,刚好可以用来实现类内共享:
import pytest class TestMyClass: @pytest.fixture(scope='class') def class_shared_tmp(self, tmp_path_factory): # 创建类专属的临时目录,同一类的所有用例复用该目录 return tmp_path_factory.mktemp("class_shared_dir") def test_this(self, class_shared_tmp): subdir = class_shared_tmp / 'subdir' subdir.mkdir() assert subdir.exists() def test_that(self, class_shared_tmp): # 验证前一个测试创建的子目录仍存在,说明目录是共享的 assert (class_shared_tmp / 'subdir').exists()
这种方式会自动处理临时目录的清理,无需手动维护。
方法二:手动实现类作用域临时目录管理
如果不想依赖tmp_path_factory,可以手动创建并清理临时目录:
import pytest import tempfile import shutil from pathlib import Path class TestMyClass: @pytest.fixture(scope='class') def class_shared_tmp(self): # 创建临时目录 tmp_dir = tempfile.mkdtemp() path = Path(tmp_dir) yield path # 测试类执行完毕后删除临时目录 shutil.rmtree(tmp_dir) def test_this(self, class_shared_tmp): subdir = class_shared_tmp / 'subdir' subdir.mkdir() assert subdir.exists() def test_that(self, class_shared_tmp): assert (class_shared_tmp / 'subdir').exists()
原代码报错原因回顾
pytest的fixture作用域遵循高作用域不能依赖低作用域的规则:类作用域 > 函数作用域,你用类作用域的new_path去引用函数作用域的tmp_path,直接违反了这个规则,因此触发ScopeMismatch错误。
内容的提问来源于stack exchange,提问作者MCornejo
相关产品推荐
相关产品推荐

