【问题标题】:How do I create my own pytest fixture?如何创建自己的 pytest 夹具?
【发布时间】:2016-10-04 02:54:54
【问题描述】:

我想创建自己的 pytest 夹具,我可以在其中插入我希望它在设置和拆卸阶段执行的操作。

我正在寻找这样的东西(在这个例子中,我创建了一个测试所需的文件):

@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

【问题讨论】:

    标签: python-3.x pytest fixtures


    【解决方案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
    

    【讨论】:

    • 我无法分享我的具体解决方案,但它符合这个总体思路,并且看起来效果很好。我的版本有一个堆栈,可以跟踪创建的所有文件,然后在最后将它们全部删除。我还决定使用 Send2Trash 模块,以便删除的文件会进入我计算机的垃圾箱,而不是立即被永久删除。如果代码失败等,这对于故障排除很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多