fastapi-boilerplate icon indicating copy to clipboard operation
fastapi-boilerplate copied to clipboard

Could you also add basic setup for pytest?

Open Timothyyy opened this issue 3 years ago β€’ 6 comments

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?

Timothyyy avatar Aug 30 '22 12:08 Timothyyy

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

teamhide avatar Aug 30 '22 13:08 teamhide

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

Timothyyy avatar Aug 30 '22 13:08 Timothyyy

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

teamhide avatar Aug 30 '22 13:08 teamhide

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

Timothyyy avatar Aug 30 '22 14:08 Timothyyy

I got it. I will add it soon :)

teamhide avatar Aug 30 '22 14:08 teamhide

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

Timothyyy avatar Sep 01 '22 09:09 Timothyyy

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 avatar Jan 29 '23 22:01 zvadym

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

zvadym avatar Feb 14 '23 19:02 zvadym

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

teamhide avatar Jan 15 '24 15:01 teamhide