1

我需要将默认 AccountId 123456789012 更改为不同的值。

我试过这个夹具:

@pytest.fixture(autouse=True):
def sts(monkeypatch):
    import moto.iam.models as models
    monkeypatch.setattr(models,'ACCOUNT_ID','111111111111')
    from moto import mock_sts
    with mock_sts():
        sts=boto3.client('sts',region_name='us-east-1')
        assert(sts.get_caller_identity().get('Account')=='111111111111')
        yield sts

但是该断言失败,AccountId 仍然是默认值...

4

2 回答 2

1

该代码在很多地方都包含硬编码的帐户 ID。当前在 git 上的代码可以通过设置环境变量 MOTO_ACCOUNT_ID 来覆盖,无需猴子补丁。

于 2019-12-24T13:10:23.397 回答
0

基于@FábioDias 对环境变量的出色提示'MOTO_ACCOUNT_ID',我们可以将其与moto 入门结合起来,如下所示:

@pytest.fixture(autouse=True)
def aws_credentials(monkeypatch):
    """Mocked AWS credentials to prevent production accidents"""
    monkeypatch.setenv("AWS_ACCESS_KEY_ID", "testing")
    monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "testing")
    monkeypatch.setenv("AWS_SECURITY_TOKEN", "testing")
    monkeypatch.setenv("AWS_SESSION_TOKEN", "testing")
    monkeypatch.setenv("AWS_DEFAULT_REGION", "us-east-1")
    monkeypatch.setenv('MOTO_ACCOUNT_ID', '111111111111')


@pytest.fixture(scope='function')
def s3(aws_credentials):
    with mock_s3():
        yield boto3.client('s3', region_name='us-east-1')

到目前为止,这似乎适用于我测试过的所有情况。

于 2022-03-04T00:49:54.140 回答