小编Nik*_*hin的帖子

断言传递给python mock中的模拟方法的对象

假设我有一个名为Client的类,它创建Request类的对象并将其传递给Connection对象的方法:

class Client(object):
    def __init__(self, connection):
        self._conn = connection

    def sendText(plaintext):
        self._conn.send(Request(0, plaintext))
Run Code Online (Sandbox Code Playgroud)

我想断言传递给Connection.send方法的对象来检查它的属性.我首先创建一个模拟的Connection类:

conn = Mock()

client = Client(conn)
client.sendText('some message')
Run Code Online (Sandbox Code Playgroud)

然后我想要这样的东西:

conn.send.assert_called_with(
    (Request,
    {'type': 0, 'text': 'some message'})
)
Run Code Online (Sandbox Code Playgroud)

其中'type'和'text'是Request的属性.有没有办法在python的模拟中执行此操作?我在文档中找到的只是简单的数据示例.我可以用mock.patch装饰器完成它,用一个断言对象字段的方法替换原来的'send'方法:

def patchedSend(self, req):
    assert req.Type == 0

with mock.patch.object(Connection, 'send', TestClient.patchedSend):
    ...
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,我必须为每个方法检查定义一个separete mocked函数,如果函数已被调用,我无法检查(没有额外的编码).

python mocking

3
推荐指数
1
解决办法
4443
查看次数

标签 统计

mocking ×1

python ×1