0

Im mocking dynamo db client using @mock_dynamodb2 provided by moto.

In my tests Im creating tables and test some input - straight forward.

When I run the code to create the table more than once (even when turning off the computer) I see that the table already exist.

I dont want this behavior and I dont want to depend on deletion of this table as well, as sometimes thrown exceptions might miss the deletion code for some reason and the table will still exist.

The code im using to create the mock is:

@mock.patch.dict(os.environ, {"REGION_NAME": "us-east-1"})
@mock_dynamodb2  # type: ignore
@pytest.mark.asyncio
async def mock_dynamo_db_call_method(
    param: Any, self_copy: _AutoRefreshingAioObject, name: str, *args: Any, **kwargs: Any
) -> Any:
    dynamodb_client_mock = client("dynamodb", region_name=os.environ.get("REGION_NAME"))
    if name == "create_table":
        dynamodb_client_mock.create_table(
            TableName=kwargs["TableName"],
            KeySchema=kwargs["KeySchema"],
            AttributeDefinitions=kwargs["AttributeDefinitions"],
            ProvisionedThroughput=kwargs["ProvisionedThroughput"],
        )
        return None
    elif name == "delete_table":
        dynamodb_client_mock.delete_table(TableName=kwargs["TableName"])
    else:
        raise Exception("Method is not mocked")
  • 2
    Are you sure that the mock is active, and that it's not hitting AWS itself? As Moto will automatically delete resources in between tests - it will definitely not keep a table in between computer restarts – Bert Blommers Apr 02 '23 at 14:47
  • @BertBlommers well, it seems like you were right. I thought that using the decorator `@mock_dynamodb2` inits the mock. but it seems like it doesnt. How do you init the mock using the decorator? i saw there is another version by calling `mock_dynamodb2().start(reset=False)` – MC LinkTimeError Apr 02 '23 at 15:12
  • It should be a matter of just adding the decorator, with two caveats. One: async support is not guaranteed, so this may give unexpected results. Two: the mock has to be started before any boto3-client is created - see http://docs.getmoto.org/en/latest/docs/getting_started.html#what-about-those-pesky-imports – Bert Blommers Apr 02 '23 at 18:21

0 Answers0