【问题标题】:Python mocking using MOTO for SSM使用 MOTO 进行 SSM 的 Python 模拟
【发布时间】:2022-01-23 20:25:42
【问题描述】:

取自这个答案:

Python mock AWS SSM

我现在有这个代码:

test_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 文件的情况下做到这一点。

谢谢,

【问题讨论】:

    标签: python-3.x unit-testing boto3 moto


    【解决方案1】:

    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调用成功,参数名称的最后一部分不能在路径中。

    【讨论】:

    • 非常感谢。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 2022-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多