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
The mock is only active for the duration of
create_test_table, that's why the table is no longer there whentest_get_item_from_tableis executed.The recommended way is to use a context decorator and
yieldthe data instead: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.