Python 3.x 如何创建自己的pytest夹具?

Python 3.x 如何创建自己的pytest夹具?,python-3.x,pytest,fixtures,Python 3.x,Pytest,Fixtures,我想创建我自己的pytest夹具,在这里我可以插入我希望它在安装和拆卸阶段执行的操作 我正在寻找类似的内容(在本例中,我创建了测试所需的文件): 我希望能够像这样使用它: def test_my_function(file): file('/Users/Me/myapplication/info.txt', 'ham, eggs, orange juice') assert my_function('info') == ['ham', 'eggs', 'orange juice'

我想创建我自己的pytest夹具,在这里我可以插入我希望它在安装和拆卸阶段执行的操作

我正在寻找类似的内容(在本例中,我创建了测试所需的文件):

我希望能够像这样使用它:

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
fixture。不幸的是,该装置只在
/tmp
目录中的某个地方创建文件,我需要在我的应用程序中创建文件

谢谢

更新: 我已经很接近了。下面的方法几乎可以工作,但它没有像我预期的那样将PATH变量全局设置为fixture。我想知道我是否可以为我的装置创建一个类而不是一个函数

@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

这有点疯狂,但这里有一个解决方案:

@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

我不能分享我的具体解决方案,但它符合这个总体思路,而且似乎工作得很好。我的版本有一个堆栈,它跟踪创建的所有文件,然后在最后将它们全部删除。我还决定使用Send2Trash模块,这样删除的文件将被放入我的计算机的垃圾箱,而不是立即永久删除。如果代码失败等情况,这有助于进行故障排除。
@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