这是我的测试代码:
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'
,并且我在TempFile
和test1
函数中单独调用test2
灯具,则addfinalizer
正常运行。
如何让addfinalizer
与scope='class'
一起运行?
答案 0 :(得分:4)
如果您将标记更改为:
,则usefixtures标记采用字符串@pytest.mark.usefixtures('TempFile')
它会正常工作。