在函数中模拟函数

2024-05-17 03:19:54 发布

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

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

我尝试了两种不同的方法,如代码中所示,但应该是mock函数永远不会被mock。我使用python3,PyCharm,测试框架设置为pytest

你知道吗测试.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")

所有测试都失败并返回实函数的值。我哪里出错了?你知道吗

添加了信息。你知道吗

尝试将路径更改为其他路径会导致

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

Tags: pathfromtestimporthelloreturndefbe
1条回答
网友
1楼 · 发布于 2024-05-17 03:19:54

我在这里回答我自己的问题。多亏了@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")

第一个不起作用,第二个在改变路径后起作用。第三个和第四个需要从assert语句中删除.test

相关问题 更多 >