【问题标题】:Magic mock assert_called_once vs assert_called_once_with weird behaviour魔术模拟 assert_called_once 与 assert_called_once_with 奇怪的行为
【发布时间】:2017-02-17 12:05:19
【问题描述】:

我注意到 python 中 assert_called_onceassert_called_once_with 的奇怪行为。这是我真正的简单测试:

文件模块/a.py

from .b import B

class A(object):
    def __init__(self):
        self.b = B("hi")

    def call_b_hello(self):
        print(self.b.hello())

文件模块/b.py

class B(object):
    def __init__(self, string):
        print("created B")
        self.string = string;

    def hello(self):
        return self.string

这些是我的测试:

import unittest
from mock import patch
from module.a import A    

class MCVETests(unittest.TestCase):
    @patch('module.a.B')   
    def testAcallBwithMockPassCorrect(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.call_b_hello()
        a.b.hello.assert_called_once()

    @patch('module.a.B')
    def testAcallBwithMockPassCorrectWith(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.call_b_hello()
        a.b.hello.assert_called_once_with()

    @patch('module.a.B')
    def testAcallBwithMockFailCorrectWith(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.b.hello.assert_called_once_with()

    @patch('module.a.B')
    def testAcallBwithMockPassWrong(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.b.hello.assert_called_once()

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

函数名称中所述我的问题是:

  • 测试 1 正确通过
  • 测试 2 正确通过
  • 测试 3 正确失败(我已删除对 b 的调用)
  • 测试 4 通过我不知道为什么。

我做错了吗?我不确定但阅读文档docs python:

assert_call_once(*args, **kwargs)

断言模拟只被调用了一次。

【问题讨论】:

  • 我实际上无法重现这个。就我而言,3 和 4 都失败了。你使用什么版本的 Python 和什么版本的 mock 库?我使用 Python 3.6 进行了测试(并使用了 stdlib unittest.mock)。
  • 我使用的是python2.7,我将更改代码并使用python3.5进行检查,谢谢:)
  • 在 3.5 中该函数不存在,所以我将使用这种方式解决问题:assert a.b.hello.call_count == 1 engineeringblog.yelp.com/2015/02/…
  • 我无法在 Python 2.7 either 中重现这一点,使用 mock 版本 2.0.0。
  • 我不知道该说什么。我遇到了这个问题,我正在重写所有测试来解决这个问题。在 3.5 版中,我得到: raise AttributeError(name) AttributeError: assert_called_once 在 2.7 版中,我通过了。我无权访问 3.6 版。如果问题不合适,请关闭/删除问题,我的解决方法是在这一点上使用解决方法:)

标签: python unit-testing magicmock


【解决方案1】:

这是旧的,但对于其他登陆这里的人......

对于 python assert_called_once 不是一个东西,所以你实际上是在进行一个不会出错的模拟函数调用

请看:http://engineroom.trackmaven.com/blog/mocking-mistakes/

您可以改为查看通话次数。

【讨论】:

  • 这是旧的,但 assert_call_once() 从 python 版本 3.6 开始就已经存在了。
  • 所以在此之前我们有assert mock.call_count == 1
猜你喜欢
  • 2013-12-27
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 2014-10-07
  • 2021-03-04
相关资源
最近更新 更多