teamhide / fastapi-boilerplate

FastAPI boilerplate for real world production
987 stars 156 forks source link

Could you also add basic setup for pytest? #11

Closed Timothyyy closed 6 months ago

Timothyyy commented 1 year ago

It's great fastapi-boilerplate but it's hard to understand how to setup pytest with current implementation.. Could you please add it to repo?

teamhide commented 1 year ago

I added relevant libraries and test code templates. Please refer to https://github.com/teamhide/fastapi-boilerplate/blob/master/tests/app/user/services/test_user.py

Timothyyy commented 1 year ago

I added relevant libraries and test code templates. Please refer to https://github.com/teamhide/fastapi-boilerplate/blob/master/tests/app/user/services/test_user.py

I mean it's an easy partπŸ˜… I asked more for conftest.py setup and test DB creation and removal for tests

teamhide commented 1 year ago

Is it correct to talk about how to mock the database for testing?

Timothyyy commented 1 year ago

I'm taking more about creating test db, applying migrations using it for tests and destroying it after tests complete πŸ™

teamhide commented 1 year ago

I got it. I will add it soon :)

Timothyyy commented 1 year ago

@teamhide Hello! Any update on this request? πŸ™

zvadym commented 1 year ago

applying migrations using it for tests and destroying it after tests complete

@teamhide hi! any updates about? Can you please add basic tests - get users, create user, update user

zvadym commented 1 year ago

My solution - use fixture from https://www.core27.co/post/transactional-unit-tests-with-pytest-and-async-sqlalchemy

and then mock all imported sessions like this

# conftest.py

@pytest_asyncio.fixture(scope="function", autouse=True)
async def replace_testing_db(async_db_session, mocker):
    """
    Replace the testing db with the async session

    Can't replace the `session` object directly in `app.core.db.session`
    because it's already imported in modules and `mocker.patch` doesn't work in this case.

    So we need to replace the `session` object in the modules where it's used.
    """
    mocker.patch("app.core.db.transactional.session", async_db_session)
    mocker.patch("app.modules.xxx.services..session", async_db_session)
    mocker.patch("app.modules.yyy.services.session", async_db_session)

    yield async_db_session
teamhide commented 6 months ago

@Timothyyy @zvadym Sorry for the late reply. Added integration test and slice test code for each layer. Please check the latest code.