Home > OS >  What is the current, correct way to retrieve an SESBackend from Moto?
What is the current, correct way to retrieve an SESBackend from Moto?

Time:10-13

I need access to the SESBackend object behind Moto's mock_ses library, so that I can check sent messages have the right properties. The Moto documentation for SES currently only shows the basic decorator wrapping syntax.

I've got something working, but it feels very clunky, and I am thinking there must be a better way of doing this:

import pytest
import boto3    
from moto import mock_ses
from moto.core.utils import AccountSpecificBackend
from moto.ses.models import SESBackend

# **************************************
# *** Is this code really necessary? ***
# **************************************
def get_ses_backend(ses_object) -> SESBackend:
    for key, value in ses_object.backends.items():
        if isinstance(value, AccountSpecificBackend):
            return value['global']

def test_my_email_function():
    with mock_ses() as ses_object:
        ses_conn = boto3.client("ses", region_name='eu-west-2')

        backend = get_ses_backend(ses_object)

        # Do some stuff with boto3 ses

        assert (len(backend.sent_messages) == 1)

I'm quite new to mocking and moto, so it could just be I am not looking in the right place. Someone asked a related question back in June on the project GitHub, but I don't understand how to apply the given answer to my own case. I'm currently using Moto 4.0.1.

CodePudding user response:

You can use the lowercase ses_backend to access the instance of the SESBackend-class:

from moto.core import DEFAULT_ACCOUNT_ID
from moto.ses import ses_backends
def get_ses_backend() -> SESBackend:
    return ses_backends[DEFAULT_ACCOUNT_ID]["global"]

Note that the ses_object alias after mock_ses() is no longer necessary, so you could simplify the decorator:

with mock_ses():
    ses_conn = boto3.client("ses", region_name='eu-west-2')

    backend = get_ses_backend()

Documentation links:

The above example uses the default account. See the documentation if you want to change the account to something else: http://docs.getmoto.org/en/latest/docs/multi_account.html

The docs for the SNS-service show the pattern of accessing the backend, albeit for a different service: http://docs.getmoto.org/en/latest/docs/services/sns.html

  • Related