8

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

Amin Etesamian
  • 3,363
  • 5
  • 27
  • 50
lanchana gupta
  • 330
  • 1
  • 3
  • 11

1 Answers1

8

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

Amin Etesamian
  • 3,363
  • 5
  • 27
  • 50
  • I am a beginner to pytest. can you give me more information about configuring the app and test fixtures? – lanchana gupta Aug 29 '17 at 19:09
  • 1
    configuration is optional. it consist of adding middle-wares like session management or db configuration management. Simply create your test cases and use `test_fixture` as an argument for you testcase. like the one I put in the answer. and run `py.test test_module.py` in your terminal. – Amin Etesamian Aug 29 '17 at 20:38
  • 1
    got it. Thank you so much :) – lanchana gupta Aug 29 '17 at 21:25