【发布时间】:2021-09-02 02:39:19
【问题描述】:
我对 Python 和单元测试真的很陌生,我现在正在尝试为处理程序编写单元测试。
处理程序的简化版本如下所示:
some_handler.py
def handleEvent(event):
user = event....
action = event...
response = getIsAuthorized(user, action)
return convertToHttpResponse(response)
getIsAuthorized(user, action):
...
authorizer = SomeAuthorizer()
return authorizer.isAuthorized(user, action)
SomeAuthorizer 是一个简单的类:
some_authorizer.py
class SomeAuthorizer(object):
__init__(self):
# some instantiation of stuff needed for the 3P client
...
# creation of some 3P auth client
self.client = Some3PClient(...)
is_authorized(user, action):
return self.client.is_authorized(user, action)
代码本身按预期工作,但我的测试让我很痛苦。 我让它在某些情况下工作:
@patch.object(SomeAuthorizer, 'is_authorized')
def test_authorization_request_not_authorized(self, mock_is_authorized):
mock_is_authorized.return_value = False
response = handle_request(test_event("test_user", "testing"))
assert response == status_code(200, False)
但是当另一个开发人员在他们的机器上运行测试时,它失败了,原因似乎是因为他们没有在本地设置 Authorizer 的构造函数所需的一些环境内容(他们在本地得到的错误是在测试运行时创建 SomeAuthorizer 实例的问题)。但我的理解是,构造函数甚至不应该被调用,因为它被嘲笑了?不是这样吗?
关于如何解决这个问题的任何提示?我一直在拼命想了解模拟是如何工作的,以及补丁/模拟的组合会起作用,但它不会走得太远。
【问题讨论】:
-
你想模拟整个
SomeAuthorizer类还是只模拟SomeAuthorizer.is_authorized()方法? -
会不会有代码在类定义中运行?某处可能存在该类的全局实例吗?你可以创建一个minimal reproducible example 来显示构造函数在不应该被调用的时候被调用吗?其他开发人员能否验证(使用调试器、打印跟踪或其他方式)构造函数被调用?
-
@NielGodfreyPonciano 理想情况下是整个班级,但我找不到让它工作的方法,让我按照我想要的方式模拟 is_authorized 方法
-
@KarlKnechtel 我将尝试找出一个在测试中调用它的可共享示例。开发人员能够验证在运行测试时是否调用了构造函数,因为测试产生的跟踪是关于它如何无法创建“Some3PClient”,因为它们没有一些必需的 env 值。跨度>
-
你能通过显式模拟
Some3PClient类来解决这个问题吗?
标签: python pytest python-mock