python - 如何将参数从 mock.patch 传递给 new_callable?

标签 python python-3.x python-3.6 python-unittest python-mock

我有代码和测试文件:

代码.py

class Code:

    def do_something_inside(self, a, b, c):
        return a-b-c

    def do_something(self, b, c):
        self.do_something_inside(30, b, c)

测试.py

import unittest
import unittest.mock as mock
from code import Code

class TestStringMethods(unittest.TestCase):
    def setUp(self):
        self.code = Code()

    def do_something_inside_stub(self, a, b, c):
        return a+b+c

    @mock.patch('code.Code.do_something_inside', new_callable=do_something_inside_stub)
    def test_add(self):
        self.assertEquals(self.code.do_something(10, 5), 45)

if __name__ == '__main__':
    unittest.main()

我想使用 do_something_inside_stub 模拟 do_something_inside 方法,但执行失败:

E
======================================================================
ERROR: test_add (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python3.6/unittest/mock.py", line 1171, in patched
    arg = patching.__enter__()
  File "/usr/lib/python3.6/unittest/mock.py", line 1293, in __enter__
    new = Klass(**_kwargs)
TypeError: do_something_inside_stub() missing 4 required positional arguments: 'self', 'a', 'b', and 'c'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

我不知道如何将参数从 mock.patch 传递给 new_callable。

最佳答案

new_callable 需要一个继承自 Mock 的类,将为这个 mock 创建其对象。您正在寻找的功能是副作用。引用:https://docs.python.org/3/library/unittest.mock.html#the-mock-class

使用以下代码:

@mock.patch('code.Code.do_something_inside', side_effect=do_something_inside_stub)
def test_add(self, do_something_inside_mock):
    do_something_inside_mock.assert_called

关于python - 如何将参数从 mock.patch 传递给 new_callable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50749380/

相关文章:

ffmpeg - 使用FFMPEG gpu python从视频中读取帧

python - 是否可以使用 Nose 同时多次运行一个测试?

python套接字文件读取超时?

python-3.x - 有效使用多个 Asyncio 队列

python - 为什么有些 Python 异常是小写的?

Python 3 子进程 SIGABRT

python - 在python中为字符串添加双引号

Python-将全局变量分配给函数返回需要函数是全局的吗?

python - 是否可以针对具有脚本文件路径参数名称的脚本文件调用 Python?

python - CI 中的 datetime.strptime 失败