我有一个简单的协程register
,它接受登录名和密码作为后置参数,然后它进入数据库等等。我的问题是我不知道如何测试协程。
我遵循了 https://aiohttp.readthedocs.io/en/latest/testing.html中的示例。
在我开始自己编写测试之前,一切似乎都很容易。
代码 test_register.py
from main import make_app
pytest_plugins = 'aiohttp.pytest_plugin'
@pytest.fixture
def cli(loop, test_client):
return loop.run_until_complete(test_client(make_app))
async def test_register(cli):
resp = await cli.post('/register', data={'login': 'emil', 'password': 'qwerty'})
assert resp.status == 200
text = await resp.text()
和register.py
from settings import db
async def register(request):
post_data = await request.post()
print('Gotta: ', post_data)
login, password = post_data['login'], post_data['password']
matches = await db.users.find({'login': login}).count()
...
main.py
from aiohttp import web
from routes import routes
def make_app(loop=None):
app = web.Application(loop=loop)
for route in routes:
app.router.add_route(route.method, route.url, route.handler)
return app
def main():
web.run_app(make_app())
if __name__ == "__main__":
main()
settings.py
from motor.motor_asyncio import AsyncIOMotorClient
DBNAME = 'testdb'
db = AsyncIOMotorClient()[DBNAME]
然后我跑了py.test test_register.py
,它卡在数据库操作上
matches = await db.users.find({'login': login}).count()