python - 如何使用 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,使用模拟包。
谢谢。
解决方案
根据讨论,这是我对这种情况所做的模拟。
我已经修改了您的代码,假设使用另一个函数来利用更改的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
推荐阅读
- automation - 插件录音机和录音有什么区别?
- powershell - 自动登录到 msonline 和 azuread 模块 - 可能吗?
- c - 无法覆盖返回地址(eip)
- php - 我如何在php中相应地交织2个变量?
- azure-api-management - Azure API 管理 - Application Insight 中的自定义跟踪
- azure - 当我在 Azure 中运行 Windows 服务时,响应时间非常差
- c++ - 我的程序不适用于 strcat - 我似乎不明白为什么?
- wordpress - wp_remote_request 不允许编辑帖子
- powershell - 使用 IFTTT 与 Google Assistance 和 Dropbox 一起使用 Powershell 打开 Spotify
- c# - C# Entity Framework - 如何在 Where 子句中动态传递值