0

I'm trying to create a dynamoDB in a pytest fixture and use it in other tests to reduce code redundancy, but having some issues.

@pytest.fixture
@mock_dynamodb
def create_test_table(self, mocker):
    table_name = "table"
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.create_table(
        TableName=table_name,
        KeySchema=[
            {"AttributeName": "name"},
        ],
        AttributeDefinitions=[
            {"AttributeName": "name", "AttributeType": "S"},
       ]
    )

    return table
def test_get_item_from_table_found(self, mocker, create_test_table):
    table = create_test_table
    item = dict()
    item["name"] = "name"
    table.put_item(Item=item)
    ...

I keep running into a An error occurred (ResourceNotFoundException) when calling the PutItem operation: Requested resource not found. I've debugged the code and it looks like the context for the table is correctly passed through

SafeDev
  • 641
  • 4
  • 12

1 Answers1

0

The mock is only active for the duration of create_test_table, that's why the table is no longer there when test_get_item_from_table is executed.

The recommended way is to use a context decorator and yield the data instead:

@pytest.fixture
def create_test_table(self, mocker):
    table_name = "table"
    with mock_dynamodb():
        dynamodb = boto3.resource("dynamodb")
        table = dynamodb.create_table(
            TableName=table_name,
        KeySchema=[
            {"AttributeName": "name", "KeyType": "HASH"},
        ],
        AttributeDefinitions=[
            {"AttributeName": "name", "AttributeType": "S"},
       ],
        ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
    )

        yield table

That ensures that the mock is still active, and the table still exists, when the actual test is executed.


On a general note, if you use this as part of a TestClass, (and you use Moto >= 3.x), you could also use a class-decorator: see http://docs.getmoto.org/en/latest/docs/getting_started.html#class-decorator

It depends on your setup whether it makes sense, but I find that personally easier to work with than passing fixtures around.

Bert Blommers
  • 1,788
  • 2
  • 13
  • 19