【问题标题】:python mock assert_called_withpython 模拟 assert_call_with
【发布时间】:2017-11-30 14:56:12
【问题描述】:

我试图理解模拟中的assert_called_with,但我编写的代码引发了一些错误。

import os
import twitter

URL = "http://test.com"

def tweet(api, message):
    if len(message) > 40:
        message = message.strip("?.,.,.")

    status = api.PostUpdate(message)
    return status

def main():
    api = twitter.Api(consumer_key=''
                    ,consumer_secret='')
    msg = 'This is test message'
    tweet(api, msg)

if __name__ == '__main__':
    main()

单元测试

import unittest
from mock import Mock
import test

class TweetTest(unittest.TestCase):
    def test_example(self):
        mock_twitter = Mock()        
        test.tweet(mock_twitter,'msg')        
        mock_twitter.PostUpdate.assert_called_with('message')        

if __name__ == '__main__':
    unittest.main()

我想了解assert_called_with 在这里做了什么?

【问题讨论】:

  • 那个测试对你没有价值。当没有使用“消息”调用 api.PostUpdate 时,它​​所做的只是失败。根据代码,它每次都会失败。更好的测试是查找 twitter api 测试凭据并实际命中外部 api。
  • @Dan 我同意这个特定代码 sn-p 的用途有限,但我不同意查找 API 测试凭据并点击外部 API。在这里引入模拟的全部意义不在于这样您就可以断言代码将如何与外部系统交互,而无需实际调用/改变该外部系统?否则我们正在冒险进入 E2E / 集成测试领域?

标签: python python-unittest python-mock python-unittest.mock


【解决方案1】:

根据python文档https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_called_with

'这个方法是断言调用是在一个 特殊的方式'

因此它会测试参数是否以正确的方式使用。

关于您收到的错误,我认为您传递的参数是错误的。它必须是这样的:

mock_twitter.PostUpdate.assert_called_with(message='msg')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2012-08-08
    • 2018-11-10
    相关资源
    最近更新 更多