Fábio Dias
Fábio Dias

Reputation: 686

How to mock Moto's AccountId

I need to change the default AccountId 123456789012 to a different value.

I tried this fixture:

@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

But that assert fails, the AccountId is still the default...

Upvotes: 1

Views: 3312

Answers (2)

Pierre D
Pierre D

Reputation: 26201

Based on @FábioDias's excellent hint about the environment variable 'MOTO_ACCOUNT_ID', we can combine this with moto getting started as follow:

@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')
    # see note 2022-06-03
    # since moto deals with ACCOUNT_ID in a "set-once" manner, we need
    # to reload moto and all of its sub-modules
    importlib.reload(sys.modules['moto'])
    to_reload = [m for m in sys.modules if m.startswith('moto.')]
    for m in to_reload:
        importlib.reload(sys.modules[m])

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

This seems to work in all cases I've tested so far.

Note 2022-06-03

As of now (moto.__version__ == '3.1.12dev'), moto still sets ACCOUNT_ID once and for all, and then copies it in various sub-modules. The only way I found to force-change the account ID everywhere is by reloading moto first (so that it assigns the new ACCOUNT_ID in moto.core.models) and then all sub-modules already loaded.

Upvotes: 0

Fábio Dias
Fábio Dias

Reputation: 686

The code included hardcoded account ids in a bunch of places. The code currently on git lets that be overwritten by setting the environment variable MOTO_ACCOUNT_ID, no need to monkey patch.

Upvotes: 3

Related Questions