python-gino / gino-starlette

An extension for GINO to support Starlette server.
https://python-gino.org
Other
78 stars 24 forks source link

Can I use Gino[starlette] with SQLite? #36

Open Plaoo opened 1 year ago

Plaoo commented 1 year ago

Tests using SQLite

Hi all, I'm trying to make the Gino mock, but I keep seeing the error gino.exceptions.UninitializedError: Gino engine is not initialized.

Code

My code is formed like this:

# __init__.py
@functools.lru_cache
def get_db_service():
    db = Gino(dsn=settings.get_settings().postgresql_conn_url)

    return db
# model 

_db = get_db_service()

class EdaTableInstance(_db.Model):
    __tablename__ = "eda_table_instance"
#...

   @classmethod
    async def get_all(cls) -> List['EdaTableInstance']:
        async with _db.acquire():
              return await EdaTableInstance.query.gino.all()

Now let's see how I'm writing the tests (various attempts)

# conftest.py
@pytest.fixture(autouse=True)
def mock_get_db_service(mocker):
    db = Gino(dsn="sqlite//:memory:")
    async_mock = AsyncMock(db)
    mocker.patch("gateway_api.services.get_db_service", return_value=async_mock)
    yield

or

# conftest.py

@pytest.fixture
async def db_initialize():
   await db.set_bind('sqlite:///:memory:')
   await db.gino.create_all()
   await EdaTableInstance.create_eda_table_instance(
       EdaTableInstanceInputOnCreate({"name":"table_server1", "host":"123.123.123.123"})
   )
   yield

or

# test_models.py
@pytest.fixture
def mock_gino_get_all(mocker):
    mocker.patch("gino.api.GinoExecutor.all", return_value=[])

@pytest.mark.asyncio
@pytest.mark.parametrize("id, expected", [(None, None)])
async def test_01_table_instance_get_all(id, expected):
    mock_cursor = MagicMock()
    mock_cursor.configure_mock(
        **{
            "get_one.return_value":[id]
        }
    )
    res = await EdaTableInstance().get_one(mock_cursor)
    assert res == expected

I would like to use SqLite in memory, so I don't have to connect from a database, if you know better methods to mock the database, it would help me so much. Thank you.

Specifications