[英]Python patched Class - method return_value returns MagicMock
I have a function that determines if a token can be pulled from environment variables, or from Google Cloud Secret Manager (via a custom class).我有一个函数可以确定是否可以从环境变量或 Google Cloud Secret Manager(通过自定义类)中提取令牌。
I am mocking the secret manager connection class so it doesn't actually connect to GCP, however the pull_secret()
method I have from it is returning another MagicMock object.我正在模拟秘密管理器连接类,因此它实际上并没有连接到 GCP,但是我从中获得的
pull_secret()
方法正在返回另一个 MagicMock 对象。
Here's the function code ( utility_functions.py
):这是函数代码(
utility_functions.py
):
def fetch_token(secret_name: str):
try:
token = os.environ['TOKEN']
except KeyError:
print("TOKEN environment variable not set. Pulling Secret from Google Cloud Secret Manager...")
token = None
if token is None or token == '':
gcp_sm = SecretManagerConnection()
token = gcp_sm.pull_secret(project_id=os.environ['GCP_PROJECT_ID'], secret_name=secret_name)
return token
The test code I am using is as follows:我正在使用的测试代码如下:
@patch("app.utilities.utility_functions.SecretManagerConnection")
def test_fetch_token_google_secret(mock_sm):
os.environ["GCP_PROJECT_ID"] = "test"
mock_sm.pull_secret().return_value = "1234567890.abcdefghijklmnopqrstuvwxyz"
del os.environ["TOKEN"]
assert fetch_token("test") == "1234567890.abcdefghijklmnopqrstuvwxyz"
The Error I get is AssertionError: assert <MagicMock name='SecretManagerConnection().pull_secret()' id='2533589158400'> == '1234567890.abcdefghijklmnopqrstuvwxyz'
我得到的错误是
AssertionError: assert <MagicMock name='SecretManagerConnection().pull_secret()' id='2533589158400'> == '1234567890.abcdefghijklmnopqrstuvwxyz'
Is there something I am doing wrong in trying to assign the pull_secret()
return value?在尝试分配
pull_secret()
返回值时我做错了什么吗?
Patching SecretManagerConnection
class will replace it with a magic mock instance.修补
SecretManagerConnection
类将用一个魔术模拟实例替换它。 When this class is instantiated in the fetch_token
function, the instantiated class will return the return_value
of mock instance which in your case is not properly configured/set.当在
fetch_token
函数中实例化此类时,实例化的类将返回模拟实例的return_value
,在您的情况下,该实例未正确配置/设置。
Configure/set the return_value
for pull_secret
method on the return_value
of mocked class rather than setting on the mocked class itself.在模拟类的
return_value
上配置/设置pull_secret
方法的return_value
,而不是在模拟类本身上设置。
@patch("app.utilities.utility_functions.SecretManagerConnection")
def test_fetch_token_google_secret(mock_sm):
os.environ["GCP_PROJECT_ID"] = "test"
instance = mock_sm.return_value
instance.pull_secret.return_value = "1234567890.abcdefghijklmnopqrstuvwxyz"
del os.environ["TOKEN"]
assert fetch_token("test") == "1234567890.abcdefghijklmnopqrstuvwxyz"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.