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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With