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

2
  • are you using aiohttp? Commented Aug 29, 2017 at 16:44
  • @Juggernaut : yes, I am using aiohttp. Commented Aug 29, 2017 at 16:45

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I am a beginner to pytest. can you give me more information about configuring the app and test fixtures?
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.
got it. Thank you so much :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.