简体   繁体   English

来自unittest.mock.patch的意外行为

[英]Unexpected behavior from unittest.mock.patch

What is wrong with my code below? 我下面的代码有什么问题?

I'm expecting assert call_func_once_with("b") to throw an error as call_func was passed 'a'. 我期望assert call_func_once_with("b")会在call_func被传递'a'时引发错误。 I confimed that the function was indeed called once and with argument 'a'. 我确信该函数确实被调用过一次并带有参数“ a”。

from unittest.mock import Mock, patch
def call_func(x):
    pass

@patch("__main__.call_func")
def test_call_func(call_func):
    call_func("a")
    assert call_func.called_once_with("b")
    assert call_func.called == 1
    print(call_func.call_args)

test_call_func()

Output: 输出:

call('a')

You're not the first person to notice strange things with these types of assertions (see Magic mock assert_called_once vs assert_called_once_with weird behaviour ) 您不是第一个注意到这类断言的奇怪事物的人(请参阅魔术嘲笑assert_call_once与assert_Called_once_with奇怪的行为

For what it's worth, I can only advise that you try to create a test class which inherits from unittest.TestCase and then use the assertEqual method to get more consistent test behaviour: 对于它的价值,我只能建议您尝试创建一个从unittest.TestCase继承的测试类,然后使用assertEqual方法获取更一致的测试行为:

import unittest
from unittest.mock import patch, call


def call_func(x):
    pass


class MyTests(unittest.TestCase):
    @patch("__main__.call_func")
    def test_call_func(self, call_func_mock):
        call_func_mock("a")
        # assert call_func_mock.called == 1
        # assert call_func_mock.called_once_with("b")
        self.assertEqual(call_func_mock.call_count, 1)
        self.assertEqual(call_func_mock.call_args_list[0], call("b"))
        print(call_func_mock.call_args)


unittest.main()

This gives the following (expected) results: 这给出了以下(预期)结果:

F
======================================================================
FAIL: test_call_func (__main__.MyTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Python36\lib\unittest\mock.py", line 1179, in patched
    return func(*args, **keywargs)
  File "C:/scratch.py", line 16, in test_call_func
    self.assertEquals(call_func_mock.call_args_list[0], call("b"))
AssertionError: call('a') != call('b')

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (failures=1)

Process finished with exit code 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM