zhanymkanov / fastapi_production_template

FastAPI Template with Docker, Postgres
The Unlicense
1.02k stars 141 forks source link

A basic service and a test case for it would be a big help. #33

Closed ckpinguin closed 4 months ago

ckpinguin commented 4 months ago

I just couldn't figure out how to test any service that involves db-action, because you do not use dependency for the db-session. So I thought I'd kindly ask you to add a small example of yours. I like your solution more than adding a db-dependency on the route-level as suggested in the fastApi docs. Anyway, thanks a ton, you already helped me a lot on my FastAPI journey!

zhanymkanov commented 4 months ago

Actually, I had such examples.

You can check them at this version of the repo (it's your commit btw)

zhanymkanov commented 4 months ago

The only thing is they aren't as great as I'd want them to be, but it's enough to grasp an idea.

ckpinguin commented 4 months ago

I was using them already as templates. But as for the actual structure, the tests for services which call db-inserts etc. are working on the live database. That's more of a convenience issue than a problem. I'll try to figure out a way to run tests with a memory-db somehow.

zhanymkanov commented 4 months ago

3 years ago I was doing something like this

from src.database import database

@pytest.fixture
async def sqlalchemy() -> Generator[Database, None, None]:
    await database.connect()
    yield database
    await database.disconnect()

@mark.asyncio

async def test_service(
    sqlalchemy: Database,
):
   service_result = await service.get_object("id")
   ...

Here, the sqlalchemy fixture is used to manage the connection to db, which is not used in the test, but run in the fixture by pytest. Then, service calls will work

ckpinguin commented 4 months ago

Interesting, I'll give that a shot, thanks!