Async fixtures with pytest

前端 未结 2 594
陌清茗
陌清茗 2021-01-17 09:39

How do I define async fixtures and use them in async tests?

The following code, all in the same file, fails miserably. Is the fixture called plainly by the test runn

2条回答
  •  不要未来只要你来
    2021-01-17 10:03

    Coroutine functions are not natively supported by PyTest, so you need to install additional framework for it

    • pytest-aiohttp
    • pytest-asyncio
    • pytest-trio
    • pytest-tornasync

    If you use pytest-aiohttp, your problem solves in this way

    import asyncio
    import pytest
    
    from app import db
    
    
    url = 'postgresql://postgres:postgres@localhost:5432'
    
    
    @pytest.fixture(scope='session')
    def loop():
        return asyncio.get_event_loop()
    
    
    @pytest.fixture(scope='session', autouse=True)
    async def prepare_db(loop):
        async with db.with_bind(f'{url}/postgres') as engine:
            await engine.status(db.text('CREATE DATABASE test_db'))
    
        await db.set_bind(f'{url}/test_db')
        await db.gino.create_all()
    
        yield
        await db.bind.close()
    
        async with db.with_bind(f'{url}/postgres') as engine:
            await engine.status(db.text('DROP DATABASE test_db'))
    

    Main idea is using synchronous loop-fixture which will be used by async fixtures

提交回复
热议问题