Python单元测试相关函数

2024-04-20 02:38:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pytest编写一些单元测试,并想知道测试“依赖”函数的最佳方法是什么。假设我有两个函数:

def set_file(filename, filecontents):
    # stores file as key in memcache

def get_file(filename):
    # returns the contents of the filename if it exists in cache

目前,我有一个“快乐路径”单元测试,看起来像这样:

^{pr2}$

我的问题是这种方法是否有效?当测试get_file时,我是否应该尝试模拟set_file的数据,以获得一个没有{}创建的依赖关系的单元测试?如果是这样的话,我该如何嘲笑它,尤其是因为set_file正在使用pymemcached?在


Tags: the方法key函数ingetpytestdef
1条回答
网友
1楼 · 发布于 2024-04-20 02:38:30

你的单元测试看起来非常有效。在测试期间将文件设置为pymemcache并没有什么坏处,因为所有内容都保留在本地内存中。在测试中有这样的“设置”依赖项也是完全可以的。在

如果您注意到开始有多个测试依赖于同一个设置,则可以使用pytest fixtures来设置此类设置和拆卸依赖关系。示例代码如下所示:

import pytest

FILENAME = "test-file"
TEST_CONTENT = "some content"


@pytest.fixture()
def set_file_contents():
    assert not get_file(FILENAME)
    set_file(FILENAME, TEST_CONTENT)
    yield FILENAME, TEST_CONTENT  # These values are provided to the test
    delete_file(FILENAME)  # This is run after the test
    assert not get_file(FILENAME)


class TestFileContents:

    def test_get_file(self, set_file_contents):
        filename, file_contents = set_file_contents
        assert get_file(filename) == file_contents

在您的案例中,使用fixture是一种过度使用,但是您看到了基本的想法。在

相关问题 更多 >