简体   繁体   中英

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'. I confimed that the function was indeed called once and with argument '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 )

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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