本文介绍了魔术模拟 assert_Called_once 与 assert_Called_once_with 奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 Python 中 assert_Called_onceassert_Called_once_with 的奇怪行为.这是我真正的简单测试:

I am noticing a weird behavior with assert_called_once and assert_called_once_with in python. This is my real simple test:

文件模块/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()

我在函数名称中提到的问题是:

My problem as stated in the name of the function is:

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

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

Am I doing something wrong? I am not sure but reading the documentation docs python:

assert_Called_once(*args, **kwargs)

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

Assert that the mock was called exactly once.

推荐答案

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

This is old, but for others landing here...

对于 python <3.6,assert_Called_once 不是一回事,所以你实际上是在进行一个不会出错的模拟函数调用

For python < 3.6, assert_called_once isn't a thing and so you're actually making a mocked function call which doesn't error

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

您可以改为查看调用次数.

You can check the call count instead.

这篇关于魔术模拟 assert_Called_once 与 assert_Called_once_with 奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:25
查看更多