【问题标题】:Mocking a function in a function在函数中模拟函数
【发布时间】:2019-07-05 15:19:03
【问题描述】:

我试图在一个函数中模拟几个函数调用,以便测试它们的行为。

我尝试了几种不同的方法,如代码所示,但 should_be_mocked 函数永远不会被模拟。我用的是python3,PyCharm,测试框架设置为pytest

test.py

from unittest import mock, TestCase
from unittest.mock import patch

from path import should_be_mocked
from other_path import flow


def test_flow(monkeypatch):
    def ret_val():
        return should_be_mocked("hi")

    monkeypatch.setattr('path', "should_be_mocked", ret_val())

    assert flow() == "hi"


def test_flow2(monkeypatch):
    monkeypatch.setattr('path.should_be_mocked', lambda x: "hi")
    assert flow() == "hi"


@patch('path.should_be_mocked')
def test_flow3(mocker):
    mocker.return_value = "hello returned"
    flow()
    mocker.test.assert_called_with("hello")


class TestStuff(TestCase):
    @patch('path.should_be_mocked')
    def test_flow4(self, mocker):
        mocker.return_value = "hello returned"
        flow()
        mocker.test.assert_called_with("hello")

路径

def should_be_mocked(hello):
    return hello

其他路径

def flow():
    # business logic here
    return should_be_mocked("hello")

所有测试都失败并从真实函数返回值。我哪里做错了?

添加信息。

尝试将路径更改为 other_path 导致

E       AttributeError: 'other_path' has no attribute 'should_be_mocked'

【问题讨论】:

  • 你应该嘲笑other_path.should_be_mocked而不是path.should_be_mocked。详情请见Where to patch

标签: python mocking pytest monkeypatching


【解决方案1】:

我在这里回答我自己的问题。感谢@hoefling,我发现这条路走错了。但是我无法运行第一个测试用例。其他的在像这样重新加工后工作。

def test_flow2(monkeypatch):
    monkeypatch.setattr('other_path', lambda x: "hi")
    assert flow() == "hi"


@patch('other_path.should_be_mocked')
def test_flow3(mocker):
    flow()
    mocker.assert_called_with("hello")


class TestStuff(TestCase):
    @patch('other_path.should_be_mocked')
    def test_flow4(self, mocker):
        flow()
        mocker.assert_called_with("hello")

第一个不起作用,第二个在更改路径后起作用。第 3 次和第 4 次需要从 assert 语句中删除 .test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多