Python pytest cases for async and await method

3.4k views Asked by At

I am trying to write pytest for the following async, await methods but I am getting nowhere.

   class UserDb(object):
    async def add_user_info(self,userInfo):
      return await self.post_route(route='users',json=userInfo)

    async def post_route(self,route=None,json=None,params=None):
      uri = self.uri + route if route else self.uri      
      async with self.client.post(uri,json=json,params=params) as resp:            
      assert resp.status == 200
      return await resp.json()

Can someone help me with this? TIA

1

There are 1 answers

3
Amin Etesamian On BEST ANSWER

pip install pytest-aiohttp, then create a fixture like this

from pytest import fixture

def make_app():
    app = Application()
    # Config your app here
    return app

@fixture
def test_fixture(loop, test_client):
    """Test fixture to be used in test cases"""
    app = make_app()
    return loop.run_until_complete(test_client(app))

Now write your tests

f = test_fixture

async def test_add_user_info(f):
    resp = await f.get('/')
    assert resp.status == 200
    assert await resp.json() == {'some_key': 'some_value'}

Also I noticed your add_user_info coroutine isn't returning anything. More info is here