0

What am I doing wrong here? This is my first time using moto and I'm really confused

conftest.py:

@pytest.fixture(scope='module')
def dynamodb(aws_credentials):
    with mock_dynamodb2():
        yield boto3.resource('dynamodb', region_name='us-east-1')


@pytest.fixture(scope='module')
def dynamodb_table(dynamodb):
    """Create a DynamoDB surveys table fixture."""
    table = dynamodb.create_table(
        TableName='MAIN_TABLE',
        KeySchema=[
           [..]
    table.meta.client.get_waiter('table_exists').wait(TableName='MAIN_TABLE')
    yield

testfile:

mport json
import boto3
from moto import mock_dynamodb2




@mock_dynamodb2
def test_lambda_handler(get_assets_event, dynamodb, dynamodb_table):
    from [...] import lambda_handler
    dynamodb = boto3.client('dynamodb')

    response = lambda_handler(get_assets_event, "")
    data = json.loads(response["body"])

    assert response["statusCode"] == 200
    assert "message" in response["body"]
    assert data["message"] == "hello world"
    # assert "location" in data.dict_keys()

But the issue is my lambda is using a helper, which has a dynamodb helper under the hood and that dbhelper starts like this:


dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ.get('MAIN_TABLE'))


def read_item(key: Dict):
    try:
        return table.get_item(Key=key)

    except ClientError as e:
        logging.exception(e)
        raise exceptions.DatabaseReadException(f"Error reading from db: {key}") from e

Is that even possible to mock like this? I feel like when I import the lambda handler it tries to overwrite my mocked db, but can't because obviously there's no os environ variable with the table name.

AciD
  • 113
  • 3
  • 8
  • If the table-name should be an environment variable, it makes sense to make this part of the test as well. You can use `mock.patch` to temporarily mock this env var for the duration of `test_lambda_handler`: `@mock.patch.dict(os.environ, {"MAIN_TABLE": "table_name"})` – Bert Blommers Dec 07 '21 at 19:39
  • Can you explain a bit more what's going wrong? What errors are you getting? – Bert Blommers Dec 07 '21 at 19:41
  • yep, I think I've got it to work with ` monkeypatch.setenv('MAIN_TABLE', 'MAIN_TABLE') ` inside of the test :) – AciD Dec 07 '21 at 19:46

0 Answers0