【问题标题】:Python mock failing call assertionPython模拟失败调用断言
【发布时间】:2018-12-19 13:14:56
【问题描述】:

我一直在阅读 python 模拟,但无法理解以下代码失败的原因。

我有两个类,一个Potato 和一个PotatoBag,如下所示。 Figure 存储在 food.py 中,Report 存储在 bag.py 中。

class Potato:
    def create_potato(self):
        pass

    def output_potato(self):
        pass


class PotatoBag:
    def __init__(self, potatoes):
        self.potatoes = potatoes

    def output_to_file(self):
        for fig in self.potatoes:
            fig.create_potato()
            fig.output_potato()

目前我正在尝试对输出方法进行单元测试,以便 Report 使用模拟从 Figure 正确调用 create_figureoutput_figure。这是我的测试代码:

from unittest.mock import MagicMock, patch
from bag import PotatoBag
from food import Potato
import pytest

@pytest.fixture(scope='module')
def potatoes():
    x = Potato()
    y = Potato()
    return [x, y]

@patch('food.Potato')
def test_output_to_file(mock_potato, potatoes):

    test_potato_bag = PotatoBag(potatoes)
    test_potato_bag.output_to_file()

    mock_potato.return_value.create_potato.assert_called()
    mock_potato.return_value.output_potato.assert_called()

pytest 立即生成一个AssertionError,说明从未调用过 create_figure。

_mock_self = <MagicMock name='Potato().create_potato' id='140480853451272'>

    def assert_called(_mock_self):
        """assert that the mock was called at least once
            """
        self = _mock_self
        if self.call_count == 0:
            msg = ("Expected '%s' to have been called." %
                   self._mock_name or 'mock')
>           raise AssertionError(msg)
E           AssertionError: Expected 'create_potato' to have been called.

/home/anaconda3/lib/python3.7/unittest/mock.py:792: AssertionError

我的代码有什么问题?

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

    您正在向Report 传递来自您的夹具而不是模拟的Figures 列表。

    将您的测试更改为...

    @patch('figure.Figure')
    def test_output_to_file(mock_figure, figures):
    
        test_report = Report([mock_figure])
        test_report.output_to_file()
    
        mock_figure.create_figure.assert_called_once()
        mock_figure.output_figure.assert_called_once()
    

    这解决了 output_to_file 正确调用 Figure 上的函数的测试,而无需真正担心设置图形和处理调用这些函数可能带来的任何副作用或其他复杂性。可以为Figure 的单元测试省去这种担心;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多