首页 > 解决方案 > 如何使用 python Mock 来验证成员变量是否已设置和未设置?

问题描述

这是我想做的一个非常简化的版本。假设我有一堂课:

class Paint():
    def __init__(self):
        # None, or a string.
        self.color = None

    def brush(self):
        self.color = 'blue'
        self.color = None

然后在我的单元测试中,我想做以下事情:

p = Paint()
p.brush()

# Hypothetical verification
assert tuples = p.color.mock_assignments
assert tuples[0] == 'blue'
assert tuples[1] == None

我想做一个真正的 Paint() 对象,但模拟出成员变量color。我想验证在调用brush()时color是否设置为某个值,然后设置回无。我该怎么做呢?

我在 ubuntu 18.04,python 3.7,使用模拟包。

谢谢。

标签: pythonunit-testingmocking

解决方案


根据讨论,这是我对这种情况所做的模拟。

我已经修改了您的代码,假设使用另一个函数来利用更改的self.color值。

import unittest
from unittest.mock import patch

def some_function(arg):
    # emulates another function that does something
    print(arg)

class Paint():
    def __init__(self):
        # None, or a string.
        self.color = None

    def brush(self):
        self.color = 'blue'
        # assumed function that is called with the changed attribute
        some_function(self.color)
        self.color = None

# unittest way
class TestPaint(unittest.TestCase):
    @patch(f'{__name__}.some_function')
    def test_brush(self, mock_fun):
        p = Paint()
        p.brush()
        mock_fun.assert_called_with('blue')
        self.assertEqual(p.color, None)

# pytest way
@patch(f'{__name__}.some_function')
def test_pain(mock_fun):
    p = Paint()
    p.brush()
    mock_fun.assert_called_with('blue')
    assert p.color is None

推荐阅读