摘自這個答案:
Python 模擬 AWS SSM
我現在有這個代碼:
測驗_2.py
from unittest import TestCase
import boto3
import pytest
from moto import mock_ssm
@pytest.yield_fixture
def s3ssm():
with mock_ssm():
ssm = boto3.client("ssm")
yield ssm
@mock_ssm
class MyTest(TestCase):
def setUp(self):
ssm = boto3.client("ssm")
ssm.put_parameter(
Name="/mypath/password",
Description="A test parameter",
Value="this is it!",
Type="SecureString",
)
def test_param_getting(self):
import real_code
resp = real_code.get_variable("/mypath/password")
assert resp["Parameter"]["Value"] == "this is it!"
這是我要測驗的代碼(或縮減示例):
real_code.py
import boto3
class ParamTest:
def __init__(self) -> None:
self.client = boto3.client("ssm")
pass
def get_parameters(self, param_name):
print(self.client.describe_parameters())
return self.client.get_parameters_by_path(Path=param_name)
def get_variable(param_name):
p = ParamTest()
param_details = p.get_parameters(param_name)
return param_details
我嘗試了許多解決方案,并在 pytest 和 unittest 之間切換了好幾次!
每次我運行代碼時,它都不會與 AWS 聯系,所以似乎有什么東西影響了 boto3 客戶端,但它不會回傳引數。如果我編輯 real_code.py 使其內部沒有類,則測驗通過。
是不是不能在real_code.py 檔案的類中修補客戶端?如果可能,我正在嘗試在不編輯 real_code.py 檔案的情況下執行此操作。
謝謝,
uj5u.com熱心網友回復:
在get_parameters_by_path回傳的前綴為所提供的路徑的所有引數。
提供時/mypath,它會回傳/mypath/password。
但是在提供時/mypath/password,如您的示例中所示,它只會回傳如下所示的引數:/mypath/password/..
如果您只想檢索單個引數,則get_parameter呼叫會更合適:
class ParamTest:
def __init__(self) -> None:
self.client = boto3.client("ssm")
pass
def get_parameters(self, param_name):
# Decrypt the value, as it is stored as a SecureString
return self.client.get_parameter(Name=param_name, WithDecryption=True)
編輯:請注意,Moto 在這方面的行為與 AWS 相同。從https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm.html#SSM.Client.get_parameters_by_path:
[路徑引數是引數的層次結構。[...] 層次結構是引數名稱,除了引數的最后一部分。對于成功的 API 呼叫,引數名稱的最后部分不能在路徑中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/391805.html
