简体   繁体   English

Python 模拟补丁本地 function

[英]Python mock patch local function

I want to check if a local function (declared on the test itself) is called.我想检查是否调用了本地 function (在测试本身上声明)。

For example:例如:

def test_handle_action():
    action = "test"
    user = "uid"
    room = "room"
    content = "test"
    data = {}

    def test_this(user, room, content, data):
        pass

    handlers = {action: test_this}

    with mock.patch("handlers.handlers", handlers):
        with mock.patch(".test_this") as f:
            handle_action(action, user, room, content, data)

            f.assert_called_with()

How can I mock path the function test_this inside my test?如何在我的测试中模拟路径 function test_this

With .test_this I got the error:使用.test_this我得到了错误:

E       ValueError: Empty module name

If test_this is a mocked function, you can define test_this as a Mock object and define assertions upon it:如果test_this是一个模拟 function,您可以将test_this定义为一个模拟 object 并在其上定义断言:

from unittest import mock

def test_handle_action():
    # GIVEN
    action = "test"
    user = "uid"
    room = "room"
    content = "test"
    data = {}

    test_this = mock.Mock()

    handlers = {action: test_this}

    with mock.patch("handlers.handlers", handlers):
        # WHEN
        handle_action(action, user, room, content, data)

        # THEN
        test_this.assert_called_with(user, room, content, data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM