我想创建我自己的pytest fixture,我可以在设置和拆卸阶段插入我想要它做的事情。
我正在寻找类似的东西(在这个例子中,我创建了一个测试所需的文件):
@pytest.fixture
def file(path, content):
def setup():
# check that file does NOT exist
if os.path.isfile(path):
raise Exception('file already exists')
# put contents in the file
with open(path, 'w') as file:
file.write(content)
def teardown():
os.remove(path)
我希望能够像这样使用它:
def test_my_function(file):
file('/Users/Me/myapplication/info.txt', 'ham, eggs, orange juice')
assert my_function('info') == ['ham', 'eggs', 'orange juice']
我知道pytest中已经有一个具有类似功能的tempdir
灯具。不幸的是,该夹具只在/tmp
目录中的某个位置创建文件,我需要在我的应用程序中使用文件。
谢谢!
更新: 我变得非常接近。以下几乎可以正常工作,但它没有像我预期的那样将PATH变量全局设置为夹具。我想知道我是否可以为我的灯具创建一个类而不是一个函数。
@pytest.fixture
def file(request):
PATH = None
def setup(path, content):
PATH = path
# check that file does NOT exist
if os.path.isfile(PATH):
raise Exception('file already exists')
# put contents in the file
with open(PATH, 'w+') as file:
file.write(content)
def teardown():
os.remove(PATH)
request.addfinalizer(teardown)
return setup
答案 0 :(得分:1)
这有点疯狂,但这是一个解决方案:
@pytest.fixture
def file(request):
class File:
def __call__(self, path, content):
self.path = path
# check that file does NOT exist
if os.path.isfile(self.path):
raise Exception('file already exists')
# put contents in the file
with open(self.path, 'w+') as file:
file.write(content)
def teardown(self):
os.remove(self.path)
obj = File()
request.addfinalizer(obj.teardown)
return obj