Moto Documentation

repository·master·Indexed 27 days ago

https://github.com/getmoto/moto

Moto is a library for mocking AWS Services in tests, providing a virtual AWS environment to intercept and simulate AWS API calls made via libraries like boto3. It includes features such as the @mock_aws decorator, experimental AWS Config support for S3 and IAM, an ASL parser for Step Functions, and a structured four-phase lifecycle for DynamoDB expression parsing.

Tokens
75.6K
Snippets
67
Records
366
Agent score
93%

What's inside Moto

  1. Overview of Moto

    master
    Moto is a library that allows your tests to easily mock out AWS Services. It intercepts boto3 calls and maintains a virtual state of buckets, keys, and other AWS resources, allowing for local testing without hitting actual AWS endpoints.
  2. Use Moto to mock Amazon Bedrock Runtime

    master
    Moto provides support for the Amazon Bedrock Runtime service. Currently, the primary implemented feature is invoke_model. Other features such as apply_guardrail, converse, converse_stream, count_tokens, get_async_invoke, invoke_model_with_bidirectional_stream, invoke_model_with_response_stream, list_async_invokes, and start_async_invoke are listed as planned or partially implemented and may not be fully functional.
  3. Mock AWS EventBridge Pipes with Moto

    master

    Moto provides support for AWS EventBridge Pipes via the moto.pipes.models.EventBridgePipesBackend class. This allows you to mock the lifecycle and management of pipes in your tests.

    Currently implemented features include:

    • create_pipe
    • delete_pipe
    • describe_pipe
    • list_pipes (supports optional filtering and pagination)
    • list_tags_for_resource
    • start_pipe
    • stop_pipe
    • tag_resource
    • untag_resource

    Note: update_pipe is not yet implemented.

  4. Understand the vendored `boto` dependency in Moto

    master
    Moto no longer maintains a direct dependency on the deprecated boto package. Instead, it uses a vendored subset of boto code located in moto/packages/boto/. This subset contains only the specific files and stripped-down models required for Moto to function, minimizing the footprint and removing superfluous methods/attributes.
  5. Understand how Moto mocks botocore requests

    master

    Moto mocks requests originating from botocore using the BotocoreStubber class. This class performs two primary functions:

    1. Inspection: It inspects incoming requests to determine the appropriate handler method.
    2. Execution: It executes the method and processes the result.

    Moto automatically registers the BotocoreStubber as an event handler for the before_send event in botocore. Because this event fires just before the actual HTTP request is made, botocore still performs client-side validation before Moto intercepts the call.

  6. Understand how Moto mocks requests from the requests module

    master

    When users manually invoke the AWS API using the Python requests module, Moto intercepts these requests and determines the result on the fly.

    To maintain consistency, Moto re-uses the logic from BotocoreStubber (which is designed to parse incoming HTTP requests to AWS) to handle requests intercepted via the responses module.

    Moto identifies supported requests by maintaining a list of URLs for each AWS service (defined in moto/backend_index.py).

    • For botocore requests: Moto checks the URL against the supported list. If unsupported, it returns a 404 NotYetImplemented response.
    • For requests module calls: Moto uses specific callbacks for supported URLs and a NotYetImplemented callback for any unhandled requests to *.amazonaws.com.
  7. Mock RDS Data `execute_statement` results

    master

    By default, Moto does not execute SQL statements for the rds-data service; calls to execute_statement will always return 0 records. To test specific database responses, you can override this behavior by configuring a queue of expected results via a dedicated Moto API endpoint.

    When you configure this queue, a request to execute_statement will consume the first result from the queue and associate it with the provided SQL query. Subsequent requests using the same SQL query will return that same result. Requests with different SQL queries will consume the next result in the queue, or return an empty result if the queue is exhausted.

    import boto3
    import requests
    
    # 1. Define the expected results queue
    expected_results = {
        "account_id": "123456789012",  # Default - can be omitted
        "region": "us-east-1",         # Default - can be omitted
        "results": [
            {
                "records": [...],
                "columnMetadata": [...],
                "numberOfRecordsUpdated": 42,
                "generatedFields": [...],
                "formattedRecords": "some json"
            },
            # Add more result objects as required
        ],
    }
    
    # 2. Configure the Moto API with the expected results
    # Note: Replace the URL with your local Moto server address if not using the default
    resp = requests.post(
        "http://motoapi.amazonaws.com/moto-api/static/rds-data/statement-results",
        json=expected_results,
    )
    assert resp.status_code == 201
    
    # 3. Use boto3 to call execute_statement and receive the mocked result
    rdsdata = boto3.client("rds-data", region_name="us-east-1")
    resp = rdsdata.execute_statement(
        resourceArn="not applicable", 
        secretArn="not applicable", 
        sql="SELECT some FROM thing"
    )
  8. Control Boto3 Session Resetting

    master

    Moto can reset the boto3-Session to ensure that subsequent tests use the correct credentials (fake vs. real). This prevents leaked mocked credentials from affecting tests that need to reach real AWS.

    If all your tests use Moto and you never need to reach real AWS, you can set "reset_boto3_session": False to improve performance by reusing the cached session.

    @mock_aws(config={
        "core": {
            "reset_boto3_session": False
        }
    })