DynamoDBのORMのPynamoDBで作ったモデルを、motoを使ってテストするためのコード例です。

> pip install moto pynamodb pytest
/
├─models
│   └─user.py
└─tests
    ├─__init__.py
    └─test_user.py

models/user.py

from pynamodb.models import Model
from pynamodb.attributes import (
    UnicodeAttribute,
    NumberAttribute,
    ListAttribute,
)


class UserModel(Model):
    class Meta:
        table_name = 'user'
        region = 'ap-northeast-1'

    id = UnicodeAttribute(hash_key=True)
    name = UnicodeAttribute(null=False)
    age = NumberAttribute(null=False)
    hobbies = ListAttribute(null=True)

tests/test_user.py

from models.user import UserModel
from moto import mock_dynamodb
import uuid


@mock_dynamodb
def test_user_model():
    UserModel.create_table(
        read_capacity_units=5, write_capacity_units=5, wait=True)

    id = str(uuid.uuid4())

    user = UserModel(id)
    user.name = "foo"
    user.age = 20
    user.hobbies = ["chess", "singing"]
    user.save()

    print("count:{count}".format(count=UserModel.count()))

    bar = UserModel.get(id)
    print("name:{name}".format(name=bar.name))

    bar.delete()
    assert UserModel.count() == 0
> pytest -vvs
=================================================================================================== test session starts ====================================================================================================
platform win32 -- Python 3.8.10, pytest-7.1.1, pluggy-1.0.0 -- c:\users\danishi\pynamodb-test\venv\scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\danishi\pynamodb-test
collected 1 item

tests/test_user.py::test_user_model count:1
name:foo
PASSED

==================================================================================================== 1 passed in 1.40s =====================================================================================================

元記事はこちら

https://qiita.com/danishi/items/a940f9c7b52bdae24765
著者:
@danishi