gino icon indicating copy to clipboard operation
gino copied to clipboard

pytest throw Gino engine is not initialized

Open teamhide opened this issue 6 years ago • 3 comments

  • GINO version: 0.8.2
  • Python version: 3.7.2
  • asyncpg version: 0.18.3
  • aiocontextvars version: 0.2.2
  • PostgreSQL version: 11.3

Description

I'm using sanic and gino.

Also used pytest-sanic for test code.

/tests/__init__.py

import pytest
from apps import create_app


@pytest.yield_fixture
def app():
    app = create_app()
    yield app

/apps/__init__.py

from sanic import Sanic
from core.config import get_connection
from core.databases import db


def create_app():
    app = Sanic(__name__)
    config = get_connection()
    app.config.from_object(config)
    db.init_app(app)
    return app

/tests/test_user.py

from apps.users.entities import UserEntity
from apps.users.tests import app
from apps.users.models import User


class TestUserRepository:
    async def test_save_user(self, app):
        await User.query.gino.all()
        assert 1 == 1

What I Did

When I run via pytest, it throw

self = <gino.api._PlaceHolder object at 0x10f9c4e28>, item = 'all'

    def __getattribute__(self, item):
        if item == '_exception':
            return super().__getattribute__(item)
>       raise self._exception
E       gino.exceptions.UninitializedError: Gino engine is not initialized.

../.local/share/virtualenvs/sanic_boilerplate-xbIlMJcw/lib/python3.7/site-packages/gino/api.py:501: UninitializedError

But In my /tests/__init__.py, I already import create_app() and it start sanic server with initialize gino.

Is there any problem in my code?

teamhide avatar May 27 '19 13:05 teamhide

I fixed this issue like this

/tests/__init__.py

import pytest
from core.databases import db


@pytest.fixture
async def app():
    return await db.set_bind('postgresql://localhost/sanic')

I wonder that, why db.init_app() doesn't work with pytest?

teamhide avatar May 28 '19 15:05 teamhide

Right, #36 also mentioned (in zh) that the init hooks are not called. I'll try to make an easier setup for testing with Sanic.

fantix avatar May 28 '19 15:05 fantix

The Gino isn't initialized, because app in't running at the moment. Gino will be initialized after before_server_start event.

mikekeda avatar Jul 16 '19 21:07 mikekeda