模拟对象的构造函数仍然被调用?
Constructor for mocked object is still getting called?
我对 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 是一个简单的 class:
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)
但是当另一个开发者 运行 在他们的盒子上进行测试时,它失败了,原因似乎是因为他们没有在本地设置授权者构造函数所需的一些环境(他们在本地遇到的错误是在测试 运行 时创建 SomeAuthorizer 实例的问题。但我的理解是构造函数甚至不应该被调用,因为它被嘲笑了?不是这样吗?
关于如何解决这个问题的任何提示?我一直在用头撞墙试图了解模拟是如何工作的,以及补丁/模拟的什么样的组合会起作用,但它不会走得太远。
这是您可能想用作参考的有效解决方案。这将模拟整个 SomeAuthorizer
class 因此它的 __init__()
将不会被执行,它的任何方法如 is_authorized()
.
文件树
$ tree
.
├── some_authorizer.py
├── some_handler.py
└── test_auth.py
some_authorizer.py
class Some3PClient:
def is_authorized(self, user, action):
return True # Real implementation returns True
class SomeAuthorizer(object):
def __init__(self):
print("Real class __init__ called")
self.client = Some3PClient()
def is_authorized(self, user, action):
print("Real class is_authorized called")
return self.client.is_authorized(user, action)
some_handler.py
from some_authorizer import SomeAuthorizer # The module we want to mock. To emphasize, the version we need to mock is "some_handler.SomeAuthorizer" and not "some_authorizer.SomeAuthorizer".
def handleEvent(event):
user = "event...."
action = "event..."
response = getIsAuthorized(user, action)
return convertToHttpResponse(response)
def getIsAuthorized(user, action):
authorizer = SomeAuthorizer()
return authorizer.is_authorized(user, action)
def convertToHttpResponse(response):
return (200, response)
test_auth.py
from unittest.mock import patch
from some_handler import handleEvent
def test_real_class():
response = handleEvent("test_event")
assert response == (200, True)
print(response)
@patch("some_handler.SomeAuthorizer") # As commented in some_handler.py, patch the full path "some_handler.SomeAuthorizer" and not "SomeAuthorizer" nor "some_authorizer.SomeAuthorizer". If you want to patch the latter for all that uses it, you have to reload the modules that imports it.
def test_mock_class(mock_some_authorizer):
mock_some_authorizer.return_value.is_authorized.return_value = False # Mock implementation returns False
response = handleEvent("test_event")
assert response == (200, False)
print(response)
输出
$ pytest -q -rP
============================================================================================ PASSES ============================================================================================
_______________________________________________________________________________________ test_real_class ________________________________________________________________________________________
------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------
Real class __init__ called
Real class is_authorized called
(200, True)
_______________________________________________________________________________________ test_mock_class ________________________________________________________________________________________
------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------
(200, False)
2 passed in 0.05s
我对 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 是一个简单的 class:
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)
但是当另一个开发者 运行 在他们的盒子上进行测试时,它失败了,原因似乎是因为他们没有在本地设置授权者构造函数所需的一些环境(他们在本地遇到的错误是在测试 运行 时创建 SomeAuthorizer 实例的问题。但我的理解是构造函数甚至不应该被调用,因为它被嘲笑了?不是这样吗?
关于如何解决这个问题的任何提示?我一直在用头撞墙试图了解模拟是如何工作的,以及补丁/模拟的什么样的组合会起作用,但它不会走得太远。
这是您可能想用作参考的有效解决方案。这将模拟整个 SomeAuthorizer
class 因此它的 __init__()
将不会被执行,它的任何方法如 is_authorized()
.
文件树
$ tree
.
├── some_authorizer.py
├── some_handler.py
└── test_auth.py
some_authorizer.py
class Some3PClient:
def is_authorized(self, user, action):
return True # Real implementation returns True
class SomeAuthorizer(object):
def __init__(self):
print("Real class __init__ called")
self.client = Some3PClient()
def is_authorized(self, user, action):
print("Real class is_authorized called")
return self.client.is_authorized(user, action)
some_handler.py
from some_authorizer import SomeAuthorizer # The module we want to mock. To emphasize, the version we need to mock is "some_handler.SomeAuthorizer" and not "some_authorizer.SomeAuthorizer".
def handleEvent(event):
user = "event...."
action = "event..."
response = getIsAuthorized(user, action)
return convertToHttpResponse(response)
def getIsAuthorized(user, action):
authorizer = SomeAuthorizer()
return authorizer.is_authorized(user, action)
def convertToHttpResponse(response):
return (200, response)
test_auth.py
from unittest.mock import patch
from some_handler import handleEvent
def test_real_class():
response = handleEvent("test_event")
assert response == (200, True)
print(response)
@patch("some_handler.SomeAuthorizer") # As commented in some_handler.py, patch the full path "some_handler.SomeAuthorizer" and not "SomeAuthorizer" nor "some_authorizer.SomeAuthorizer". If you want to patch the latter for all that uses it, you have to reload the modules that imports it.
def test_mock_class(mock_some_authorizer):
mock_some_authorizer.return_value.is_authorized.return_value = False # Mock implementation returns False
response = handleEvent("test_event")
assert response == (200, False)
print(response)
输出
$ pytest -q -rP
============================================================================================ PASSES ============================================================================================
_______________________________________________________________________________________ test_real_class ________________________________________________________________________________________
------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------
Real class __init__ called
Real class is_authorized called
(200, True)
_______________________________________________________________________________________ test_mock_class ________________________________________________________________________________________
------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------
(200, False)
2 passed in 0.05s