4

我想测试我写的一个电子邮件发送方法。在文件 format_email.py 中,我导入 send_email。

 from cars.lib.email import send_email

 class CarEmails(object):

    def __init__(self, email_client, config):
        self.email_client = email_client
        self.config = config

    def send_cars_email(self, recipients, input_payload):

在 send_cars_email() 中格式化电子邮件内容后,我使用之前导入的方法发送电子邮件。

 response_code = send_email(data, self.email_client)

在我的测试文件 test_car_emails.py

@pytest.mark.parametrize("test_input,expected_output", test_data)
def test_email_payload_formatting(test_input, expected_output):
    emails = CarsEmails(email_client=MagicMock(), config=config())
    emails.send_email = MagicMock()
    emails.send_cars_email(*test_input)
    emails.send_email.assert_called_with(*expected_output)

当我运行测试时,它会因未调用断言而失败。我相信问题是我在嘲笑 send_email 功能。

我应该在哪里模拟这个功能?

4

3 回答 3

8

你用这条线嘲笑的emails.send_email = MagicMock()是功能

class CarsEmails:

    def send_email(self):
        ...

你没有的。因此,此行只会向您的对象添加一个新功能。emails但是,不会从您的代码中调用此函数,并且分配将完全没有效果。相反,您应该模拟模块中的send_email函数cars.lib.email

模拟使用它的函数

一旦你在你的模块send_email中导入了这个函数,它就可以在 name 下使用。由于您知道该函数在那里被调用,您可以使用它的新名称来模拟它:from cars.lib.email import send_emailformat_email.pyformat_email.send_email

from unittest.mock import patch

from format_email import CarsEmails

@pytest.mark.parametrize("test_input,expected_output", test_data)
def test_email_payload_formatting(config, test_input, expected_output):
    emails = CarsEmails(email_client=MagicMock(), config=config)
    with patch('format_email.send_email') as mocked_send:
        emails.send_cars_email(*test_input)
        mocked_send.assert_called_with(*expected_output)

模拟定义它的函数

更新

阅读文档中的修补位置部分确实很有帮助(另请参阅Martijn Pieters评论):unittest

基本原则是您在查找对象的位置进行修补,该位置不一定与定义对象的位置相同。

所以坚持在使用位置模拟函数,不要从刷新导入或以正确的顺序对齐它们开始。即使当源代码format_email由于某种原因而无法访问时(例如当它是 cythonized/编译的 C/C++ 扩展模块时)应该有一些晦涩的用例,您仍然只有两种可能的导入方式,所以请尝试如在哪里修补和使用成功的那个中所述的两种模拟可能性。

原始答案

您还可以send_email在其原始模块中模拟函数:

with patch('cars.lib.email.send_email') as mocked_send:
    ...

但请注意,如果您在修补之前调用了send_emailin的导入format_email.py,则修补cars.lib.email不会对代码中的代码产生任何影响,format_email因为该函数已经导入,因此mocked_send不会调用以下示例中的:

from format_email import CarsEmails

...

emails = CarsEmails(email_client=MagicMock(), config=config)
with patch('cars.lib.email.send_email') as mocked_send:
    emails.send_cars_email(*test_input)
    mocked_send.assert_called_with(*expected_output)

要解决此问题,您应该format_email在以下补丁后首次导入cars.lib.email

with patch('cars.lib.email.send_email') as mocked_send:
    from format_email import CarsEmails
    emails = CarsEmails(email_client=MagicMock(), config=config)
    emails.send_cars_email(*test_input)
    mocked_send.assert_called_with(*expected_output)

或重新加载模块,例如importlib.reload()

import importlib

import format_email

with patch('cars.lib.email.send_email') as mocked_send:
    importlib.reload(format_email)
    emails = format_email.CarsEmails(email_client=MagicMock(), config=config)
    emails.send_cars_email(*test_input)
    mocked_send.assert_called_with(*expected_output)

如果你问我,这两种方式都不漂亮。我会坚持在调用它的模块中模拟该函数。

于 2018-02-17T23:57:23.150 回答
8

由于您使用的是 pytest,我建议使用 pytest 的内置“monkeypatch”夹具。

考虑这个简单的设置:

我们定义要模拟的函数。

"""`my_library.py` defining 'foo'."""


def foo(*args, **kwargs):
    """Some function that we're going to mock."""
    return args, kwargs

并在一个单独的文件中调用该函数的类。

"""`my_module` defining MyClass."""
from my_library import foo


class MyClass:
    """Some class used to demonstrate mocking imported functions."""
    def should_call_foo(self, *args, **kwargs):
        return foo(*args, **kwargs)

我们使用“monkeypatch”夹具 模拟使用它的功能

"""`test_my_module.py` testing MyClass from 'my_module.py'"""
from unittest.mock import Mock

import pytest

from my_module import MyClass


def test_mocking_foo(monkeypatch):
    """Mock 'my_module.foo' and test that it was called by the instance of
    MyClass.
    """
    my_mock = Mock()
    monkeypatch.setattr('my_module.foo', my_mock)

    MyClass().should_call_foo(1, 2, a=3, b=4)

    my_mock.assert_called_once_with(1, 2, a=3, b=4)

如果您想重用它,我们也可以将模拟分解到它自己的固定装置中。

@pytest.fixture
def mocked_foo(monkeypatch):
    """Fixture that will mock 'my_module.foo' and return the mock."""
    my_mock = Mock()
    monkeypatch.setattr('my_module.foo', my_mock)
    return my_mock


def test_mocking_foo_in_fixture(mocked_foo):
    """Using the 'mocked_foo' fixture to test that 'my_module.foo' was called
    by the instance of MyClass."""
    MyClass().should_call_foo(1, 2, a=3, b=4)

    mocked_foo.assert_called_once_with(1, 2, a=3, b=4)
于 2018-02-18T16:46:15.020 回答
-1

最简单的解决方法如下

@pytest.mark.parametrize("test_input,expected_output", test_data)
def test_email_payload_formatting(test_input, expected_output):
    emails = CarsEmails(email_client=MagicMock(), config=config())
    import format_email
    format_email.send_email = MagicMock()
    emails.send_cars_email(*test_input)
    format_email.send_email.assert_called_with(*expected_output)

基本上你有一个已经导入的模块,send_emailformat_email现在必须更新加载的模块。

但这不是最推荐的方法,因为您失去了原始send_email功能。所以你应该使用带有上下文的补丁。有不同的方法可以做到这一点

方式一

from format_email import CarsEmails

@pytest.mark.parametrize("test_input,expected_output", test_data)
def test_email_payload_formatting(test_input, expected_output):
    emails = CarsEmails(email_client=MagicMock(), config=config())
    with patch('cars.lib.email.send_email') as mocked_send:
        import format_email
        reload(format_email)
        emails.send_cars_email(*test_input)
        mocked_send.assert_called_with(*expected_output)

在此我们模拟导入的实际函数

方式二

with patch('cars.lib.email.send_email') as mocked_send:
    from format_email import CarsEmails

    @pytest.mark.parametrize("test_input,expected_output", test_data)
    def test_email_payload_formatting(test_input, expected_output):
        emails = CarsEmails(email_client=MagicMock(), config=config())
        emails.send_cars_email(*test_input)
        mocked_send.assert_called_with(*expected_output)

这样,您文件中的任何测试也将使用修补功能进行其他测试

方式3

from format_email import CarsEmails

@pytest.mark.parametrize("test_input,expected_output", test_data)
def test_email_payload_formatting(test_input, expected_output):
    with patch('format_email.send_email') as mocked_send:
        emails = CarsEmails(email_client=MagicMock(), config=config())
        emails.send_cars_email(*test_input)
        mocked_send.assert_called_with(*expected_output)

在这种方法中,我们修补导入本身,而不是调用的实际函数。在这种情况下,不需要重新加载

所以你可以看到有不同的模拟方式,有些方法是好的做法,有些是个人选择

于 2018-02-18T09:46:33.640 回答