python - 魔术模拟 assert_called_once 与 assert_called_once_with 奇怪的行为

标签 python unit-testing magicmock

我注意到 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_called_once(*args, **kwargs)

Assert that the mock was called exactly once.

最佳答案

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

对于 python < 3.6,assert_called_once 不是问题,因此您实际上是在进行一个不会出错的模拟函数调用

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

您可以改为检查调用次数。

关于python - 魔术模拟 assert_called_once 与 assert_called_once_with 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297549/

相关文章:

python - 使用 python-markdown-math 渲染 markdown 时出现问题

python - 当我从批处理文件运行 .py 文件时 PyCharm 打开

python - 制作经过训练的数据集python的图形

Python:如何使用 f 字符串进行数学运算

python - 用pytest模拟一个导入的函数

c++ - Iceberg 类和 Google 单元测试

unit-testing - 如何在 salesforce 中进行单元测试?

Phpunit 找不到抽象类

python - Unresolved reference MagicMock

类的python模拟默认初始化参数