神奇的模拟assert_used_once与assert_used_once_的奇怪行为

问题描述 投票:0回答:1

我注意到 python 中

assert_called_once
assert_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_used_once(*args, **kwargs)

断言模拟仅被调用一次。

python unit-testing magicmock
1个回答
10
投票

这已经很旧了,但对于其他登陆这里的人来说......

对于 python < 3.6,

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

请参阅:嘲笑错误

您可以查看通话次数。

© www.soinside.com 2019 - 2024. All rights reserved.