python - py.test setup_class 中的 tmpdir

标签 python pytest

我使用 py.test 进行测试。

setup_class() 中,我需要为我的类构造函数使用 tmpdir:

class TestMyClass:
    def setup_class(self):
        self.t = MyClass(path=tmpdir)

    def test_test(self):
        assert True

我有一个错误:

NameError: name 'tmpdir' is not defined

我不能使用 setup_class(self, tmpdir)

如果我使用这段代码:

def test_needsfiles(tmpdir):
    print(tmpdir)
    assert 0

它可以工作,但我的类构造函数中需要 tmpdir

如何做到这一点?

谢谢!

UPD

我尝试这样做:

@pytest.yield_fixture()
def constructor(tmpdir):
    _t = MyClass(path=str(tmpdir))
    yield _t

class TestMyClass:

    def test_test(self, constructor):
        pass

但是我不能在 fixture 中使用作用域:

ScopeMismatch:您尝试使用“模块”范围的请求对象访问“功能”范围的 fixture “tmpdir”,涉及工厂

最佳答案

我这样做:

class TestMyClass:
    @pytest.fixture(autouse=True)
    def setup(self, tmpdir):
        self.tmpdir = tmpdir.strpath

关于python - py.test setup_class 中的 tmpdir,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36372034/

相关文章:

Python Numpy 矩阵乘法使用循环将多个矩阵相乘

python - 模块未找到错误 : No module named 'importlib.util'

python - os.system 或子进程将命令传递给 shell

python - 你如何在 Heroku 上使用 APScheduler 安排 cron 作业?

python - 在 pytest 中执行teardown_method后测试失败

python - py.test : get KeyboardInterrupt to call teardown

python - 如何使用 OpenCV 交换图像中的蓝色和红色 channel

python - 检查 pytest 是否引发异常

python - 如何动态获取 pytest fixture 数据

python - Pytest 未运行任何测试