How does one test a Sanic Web API? The introduction and quick start parts are quite difficult for beginners. I tried the following (stolen from: https://sanic.readthedocs.io/en/latest/sanic/testing.html)
import pytest
from sanic import response, Sanic
from sanic.websocket import WebSocketProtocol
@pytest.yield_fixture
def app():
app = Sanic("test_sanic_app")
@app.route("/test_get", methods=['GET'])
async def test_get(request):
return response.json({"GET": True})
@app.route("/test_post", methods=['POST'])
async def test_post(request):
return response.json({"POST": True})
yield app
@pytest.fixture
def test_cli(loop, app, test_client):
return loop.run_until_complete(test_client(app, protocol=WebSocketProtocol))
#########
# Tests #
#########
async def test_fixture_test_client_get(test_cli):
"""
GET request
"""
resp = await test_cli.get('/test_get')
assert resp.status == 200
resp_json = await resp.json()
assert resp_json == {"GET": True}
async def test_fixture_test_client_post(test_cli):
"""
POST request
"""
resp = await test_cli.post('/test_post')
assert resp.status == 200
resp_json = await resp.json()
assert resp_json == {"POST": True}
This resulted in the following error:
@pytest.fixture
def test_cli(loop, app, test_client):
E fixture ‘loop’ not found
How I run the tests:
pytest test_example.py
My machine:
- Windows 10
- Python 3.6
- pipenv
- sanic 18.12.0
Questions
- What is this ‘loop’ not found error?
- How to test a Sanic web api, if the tests are seperated from the api (in another folder)?