Python单元测试mock,获取mocked函数的输入参数

2024-04-23 07:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望单元测试断言函数中的变量action正在被设置为其预期值,唯一使用此变量的时间是在调用库时将其传递给库时。

Class Monolith(object):
    def foo(self, raw_event):
        action =  # ... Parse Event
        # Middle of function
        lib.event.Event(METADATA, action)
        # Continue on to use the build event.

我的想法是我可以模拟lib.event.Event,得到它的输入参数并断言它们具有特定的值。

>;这不是模拟的工作方式吗?模拟文档的不一致性、半个示例和大量与我想做的事情无关的示例使我感到沮丧。


Tags: 函数selfevent示例objectfoolibdef
3条回答

您可以使用patch decorator,然后对模拟对象调用assert_called_with,如下所示:

如果您有这种结构:

example.py
tests.py
lib/__init__.py
lib/event.py

example.py的内容是:

import lib

METADATA = 'metadata_example'

class Monolith(object):

    def foo(self, raw_event):
        action =  'action_example' # ... Parse Event
        # Middle of function
        lib.event.Event(METADATA, action)
        # Continue on to use the build event.

lib/event.py的内容是:

class Event(object):

    def __init__(self, metadata, action):
        pass

tests.py的代码应该如下:

import mock
import unittest

from lib.event import Event
from example import Monolith


class TestExample(unittest.TestCase):

    @mock.patch('lib.event.Event')
    def test_example1(self, event_mocked):
        # Setup
        m = Monolith()

        # Exercise
        m.foo('raw_event')

        # Verify
        event_mocked.assert_called_with('metadata_example', 'action_example')

如果你想直接访问参数,这个怎么样?不过有点多余。。。 见https://docs.python.org/3.6/library/unittest.mock.html#unittest.mock.call.call_list

import mock
import unittest

from lib.event import Event
from example import Monolith


class TestExample(unittest.TestCase):

    @mock.patch('lib.event.Event')
    def test_example1(self, event_mocked):
        # Setup
        m = Monolith()

        # Exercise
        m.foo('raw_event')

        # Verify
        name, args, kwargs = m.mock_calls[0]
        self.assertEquals(name, "foo")
        self.assertEquals(args, ['metadata_example', 'action_example'])
        self.assertEquals(kwargs, {})

也可以使用^{}^{}

一个简单的例子如下:

class TestExample(unittest.TestCase):

    @mock.patch('lib.event.Event')
    def test_example1(self, event_mocked):
        args, kwargs = event_mocked.call_args
        self.assertEqual(args, ['metadata_example', 'action_example'])


我只是很快为可能需要它的人写了这个例子-我没有实际测试过,所以可能有一些小错误。

相关问题 更多 >