add an example
This commit is contained in:
parent
e7c8035ed7
commit
fd5faeb5dd
|
@ -65,16 +65,63 @@ the available arguments to aiohttp can be found
|
||||||
Just write tests like,
|
Just write tests like,
|
||||||
|
|
||||||
```python
|
```python
|
||||||
async def test_sanic_db_find_by_id(app):
|
async def test_sanic_db_find_by_id(app):
|
||||||
"""
|
"""
|
||||||
Let's assume that, in db we have,
|
Let's assume that, in db we have,
|
||||||
{
|
{
|
||||||
"id": "123",
|
"id": "123",
|
||||||
"name": "Kobe Bryant",
|
"name": "Kobe Bryant",
|
||||||
"team": "Lakers",
|
"team": "Lakers",
|
||||||
}
|
}
|
||||||
"""
|
"""
|
||||||
doc = await app.db["players"].find_by_id("123")
|
doc = await app.db["players"].find_by_id("123")
|
||||||
assert doc.name == "Kobe Bryant"
|
assert doc.name == "Kobe Bryant"
|
||||||
assert doc.team == "Lakers"
|
assert doc.team == "Lakers"
|
||||||
|
```
|
||||||
|
|
||||||
|
[pytest-sanic](https://github.com/yunstanford/pytest-sanic) also provides some useful fixtures, like loop, unused_port,
|
||||||
|
test_server, test_client.
|
||||||
|
|
||||||
|
```python
|
||||||
|
@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}
|
||||||
```
|
```
|
||||||
|
|
Loading…
Reference in New Issue
Block a user