如何使用python模拟来验证成员变量是否已设置和取消设置?

2024-04-27 00:51:18 发布

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

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

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是否被设置为某个值,然后又被设置回无。我该怎么做

我使用的是Ubuntu18.04,Python3.7,使用的是模拟软件包

谢谢


1条回答
网友
1楼 · 发布于 2024-04-27 00:51:18

根据讨论,这里是一个模拟我会做这样的情况

我已经修改了您的代码,假设使用了另一个函数来使用更改的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

相关问题 更多 >