Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pytest cases for async and await method

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

like image 499
lanchana gupta Avatar asked Aug 29 '17 16:08

lanchana gupta


People also ask

How do I use async await in Python?

An async function uses the await keyword to denote a coroutine. When using the await keyword, coroutines release the flow of control back to the event loop. To run a coroutine, we need to schedule it on the event loop. After scheduling, coroutines are wrapped in Tasks as a Future object.

Is pytest third party?

A number of third-party testing frameworks attempt to address some of the issues with unittest , and pytest has proven to be one of the most popular.

Is FastAPI asynchronous?

Anyway, in any of the cases above, FastAPI will still work asynchronously and be extremely fast. But by following the steps above, it will be able to do some performance optimizations.

How do you wait for async to finish?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.


1 Answers

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

like image 115
Juggernaut Avatar answered Sep 24 '22 23:09

Juggernaut