无法在范围为类的fixture中运行addfinalizer函数

时间:2015-08-10 13:59:58

标签: python testing pytest

这是我的测试代码:

import string
import pytest
import tempfile
import os

@pytest.fixture(scope='class')
def TempFile(request):
    (tmp_cfg_fd, tmp_cfg_file_path) = tempfile.mkstemp()
    os.close(tmp_cfg_fd)
    def RemoveTempFile():
        print("Removing %r" %(tmp_cfg_file_path))
        os.remove(tmp_cfg_file_path)
    request.addfinalizer(RemoveTempFile)
    return tmp_cfg_file_path

@pytest.mark.usefixtures(TempFile)
class Test:
    def test1(self):
        print("I'm in test1")

    def test2(self):
        print("I'm in test2")

当我在其上运行py.test时,我收到此错误:

test_4.py:17: in <module>
    @pytest.mark.usefixtures(TempFile)
test_4.py:14: in TempFile
    request.addfinalizer(RemoveTempFile)
E   AttributeError: class Test has no attribute 'addfinalizer'

当灯具有scope='class'时,Test类无法运行addfinalizer

但是如果灯具有scope='function',并且我在TempFiletest1函数中单独调用test2灯具,则addfinalizer正常运行。

如何让addfinalizerscope='class'一起运行?

1 个答案:

答案 0 :(得分:4)

如果您将标记更改为:

,则usefixtures标记采用字符串
@pytest.mark.usefixtures('TempFile')

它会正常工作。