python - 如何为 Pytest 模拟库类

标签 python mocking pytest

我是模拟和测试 python 代码(任何代码)的新手。

我正在尝试测试我的函数 main.py

def get_channel_list():
    sc = SlackClient(get_token())
    channels_list_json = sc.api_call("channels.list")
    if channels_list_json['ok'] == True:
        return channels_list_json

这是我要测试的功能

我需要模拟补丁 sc.api_call("channels.list") 来返回 JSON 对象 但我找不到任何这样的例子来帮助我弄清楚如何去做。

我发现的一切都像这个例子Mocking a class method...

我认为它看起来像这样:

@patch.object(SlackClient, 'api_call')
def test_get_channel_list():
    assert get_channel_list() != ""

我不必测试库我需要测试我之前提到的函数中的其余代码。 感谢您的帮助,我真的很满意这个测试。

最佳答案

您需要编写一个单独的模拟函数来返回一个 JSON 对象。

你可以试试这个:

@pytest.fixture
def mock_api_call(monkeypatch):
    monkeypatch.setattr(SlackClient, 'api_call', lambda self, arg: {"ok": True})

def test(mock_api_call):
    sc = SlackClient(get_token())
    channels_list_json = sc.api_call("channels.list")
    assert True == channels_list_json['ok']

def test_get_channel_list(mock_api_call):
    channels_list_json = get_channels_list()
    assert dict == type(channels_list_json)

关于python - 如何为 Pytest 模拟库类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51171428/

相关文章:

python - 如何导入和猴子修补与测试位于不同包中的 Python 模块?

python - 我可以在 Mac OS X 上将 enthought python 重新链接到新版本的 openssl 吗?

Python 脚本不会运行

python - 自定义包导入问题--属性错误

python - Pytest 模拟补丁 - 如何排除故障?

c# - 单元测试 HttpContext.Current.Cache 或 C# 中的其他服务器端方法?

c# - 模拟一个稍后实例化的接口(interface)?

Python-将文本文件放入字典中

postgresql - py.test 混合装置和 asyncio 协程

python - 尝试使用 pandas 进行 pytest 测试时出现 Keyerror