Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a stepfunction

I have a AWS Lambda function where I am starting the execution of the step function. Now I want to write a test case for the same using Pytest. I am not sure how to mock a stepfunction using Moto.

Following is the code snippet of my stepfunction in abc.py

 client = boto3.client('stepfunctions')
                        client.start_execution(
                            stateMachineArn=os.environ['SFN_ARN'],
                            name='Test-SFN",
                            input=json.dumps(details)
                        )

Now to mock this I have created a function in Conftest.py

sfn_definition = {//some definition}    
@mock_stepfunctions
    def mock_sfn():
        client = boto3.client('stepfunctions')
        response = client.create_state_machine(name="Test-SFN", definition=json.dumps(sfn_definition), roleArn="arn:aws:iam::someARN" )

This is the first time I am mocking a StepFunction so I am not sure what has to be done exactly. As this is trying to connect to actual stepfunction than creating a mock.

The error I am facing is

botocore.errorfactory.StateMachineDoesNotExist: An error occurred (StateMachineDoesNotExist) when calling the StartExecution operation:

Any help would be appreciated, Thank you

State Machine Does Not Exist:

like image 906
user18148705 Avatar asked Oct 15 '25 15:10

user18148705


1 Answers

To create the mocked StepFunction you can add something like this to conftest.py

import boto3
from moto import mock_stepfunctions
import pytest

STEP_FUNCTION_NAME = 'dummy-sfn'
STEP_FUNCTION_ARN = (
    f'arn:aws:states:us-east-1:123456789012:stateMachine:{STEP_FUNCTION_NAME}')


@pytest.fixture(autouse=True)
def env_setup(monkeypatch):
    monkeypatch.setenv('SFN_ARN', STEP_FUNCTION_ARN)


@pytest.fixture
def aws_credentials(monkeypatch):
    """Mocked AWS Credentials for moto."""
    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')


@pytest.fixture
def stepfunctions_client_fixt(aws_credentials):
    with mock_stepfunctions():
        conn = boto3.client('stepfunctions')
        yield conn


@pytest.fixture(autouse=True)
def step_function_fixt(stepfunctions_client_fixt):
    stepfunctions_client_fixt.create_state_machine(
        name=STEP_FUNCTION_NAME,
        definition='fake',
        roleArn='arn:aws:iam::123456789012:role/role-name',
    )
    yield

And then include something like this in test_abc.py

from unittest.mock import patch

from abc import my_method_that_calls_start_execution


def test_my_method_that_calls_start_execution(stepfunctions_client_fixt):
    with patch('abc.client', stepfunctions_client_fixt):
        my_method_that_calls_start_execution()
like image 93
Miguel Sousa Avatar answered Oct 17 '25 04:10

Miguel Sousa