Skip to content
Latchkey

Python "moto mock not patching boto3" in CI

moto patches boto3 only for clients created inside its mock context. If a boto3 client is built before the mock starts, or the mock decorator/context is not applied, real AWS calls leak and tests fail with credential or network errors.

What this error means

A test that should be fully mocked fails with "botocore.exceptions.NoCredentialsError: Unable to locate credentials" or makes a real network call despite using moto.

pytest
botocore.exceptions.NoCredentialsError: Unable to locate credentials

Common causes

The boto3 client was created outside the mock context

A module-level or fixture client built before mock_aws started is not patched.

Using a stale decorator name or wrong import

Older per-service decorators were removed in moto 5; the unified mock_aws context must wrap the client creation.

How to fix it

Create the client inside mock_aws

  1. Wrap the test (or fixture) in mock_aws() and create the boto3 client inside it.
  2. Set fake AWS credentials in the environment so botocore does not search for real ones.
  3. Avoid module-level clients; build them lazily inside the mocked scope.
Python
from moto import mock_aws
import boto3

@mock_aws
def test_s3():
    s3 = boto3.client("s3", region_name="us-east-1")
    s3.create_bucket(Bucket="test")

How to prevent it

  • Create AWS clients inside the moto-mocked scope.
  • Set dummy AWS_* credentials in the test environment.
  • Pin moto and use the unified mock_aws API.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →