【问题标题】:Python Unit Test Dependent FunctionsPython 单元测试相关函数
【发布时间】:2019-08-09 22:41:03
【问题描述】:

我正在使用 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

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

def test_happy_path():
    assert not get_file('unit test') # check that return of non-existent file is None
    set_file('unit test', 'test content') # set file contents
    assert get_file('unit test') == 'test content'  # check that return matches input

我的问题是这种方法是否有效?在测试get_file 时,我是否应该尝试模拟set_file 的数据以进行没有set file 创建的依赖项的单元测试?如果是这样,我将如何模拟它,尤其是因为 set_file 正在使用 pymemcached?

【问题讨论】:

  • 对我来说,你的test_happy_path 似乎是有效的......

标签: python unit-testing mocking pytest


【解决方案1】:

您的单元测试看起来完全有效。在测试期间将文件设置为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

在您的情况下使用固定装置是一种矫枉过正,但您会看到基本思想。

【讨论】:

  • 我刚刚意识到,如果您在代码中连接到外部memcached 数据库,您肯定需要模拟或使用测试数据库。测试时在应用程序代码中使用pymemcache 中的MockMemcacheClient 应该很容易模拟。
猜你喜欢
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
相关资源
最近更新 更多