/
test_quart.py
191 lines (146 loc) · 5.42 KB
/
test_quart.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import sys
import pytest
# Quart only supports Python 3.6 or later
if sys.version_info < (3, 6):
raise pytest.skip(allow_module_level=True)
import json
from async_generator import yield_, async_generator
from quart import Quart, jsonify, request, websocket
from quart.exceptions import NotFound
import gino
from gino.ext.quart import Gino
from .models import DB_ARGS, PG_URL
# noinspection PyShadowingNames
async def _app(config):
app = Quart(__name__)
app.config.update(config)
db = Gino(app)
class User(db.Model):
__tablename__ = 'gino_users'
id = db.Column(db.BigInteger(), primary_key=True)
nickname = db.Column(db.Unicode(), default='noname')
@app.route('/')
async def root():
return 'Hello, world!'
async def _get_user(ctx, uid: int, method: str) -> dict:
q = User.query.where(User.id == uid)
if method == '1':
return (await q.gino.first_or_404()).to_dict()
elif method == '2' and ctx:
return (await ctx.connection.first_or_404(q)).to_dict()
elif method == '3':
return (await db.bind.first_or_404(q)).to_dict()
elif method == '4':
return (await db.first_or_404(q)).to_dict()
else:
return (await User.get_or_404(uid)).to_dict()
@app.route('/users/<int:uid>')
async def get_user(uid):
method = request.args.get('method')
return jsonify(await _get_user(request, uid, method))
async def _add_user(ctx, nickname: str) -> dict:
u = await User.create(nickname=nickname)
await u.query.gino.first_or_404()
await db.first_or_404(u.query)
await db.bind.first_or_404(u.query)
if ctx:
await ctx.connection.first_or_404(u.query)
return u.to_dict()
@app.route('/users', methods=['POST'])
async def add_user():
return jsonify(await _add_user(
request, (await request.form).get('name')))
@app.websocket('/ws')
async def ws():
while True:
data = json.loads(await websocket.receive())
action = data.get('action')
if action == 'add':
new_user = await _add_user(None, data.get('name'))
await websocket.send(json.dumps(new_user))
elif action == 'get':
try:
user = await _get_user(
None, int(data.get('id')), data.get('method'))
except NotFound:
await websocket.send(json.dumps({'error': 'not found'}))
else:
await websocket.send(json.dumps(user))
else:
await websocket.send(json.dumps({'error': 'Invalid JSON'}))
e = await gino.create_engine(PG_URL)
try:
try:
await db.gino.create_all(e)
await yield_(app)
finally:
await db.gino.drop_all(e)
finally:
await e.close()
@pytest.fixture
@async_generator
async def app():
await _app({
'DB_HOST': DB_ARGS['host'],
'DB_PORT': DB_ARGS['port'],
'DB_USER': DB_ARGS['user'],
'DB_PASSWORD': DB_ARGS['password'],
'DB_DATABASE': DB_ARGS['database'],
})
@pytest.fixture
@async_generator
async def app_dsn():
await _app({'DB_DSN': PG_URL})
async def _test_index_returns_200(app):
response = await app.test_client().get('/')
assert response.status_code == 200
assert await response.get_data(raw=False) == 'Hello, world!'
@pytest.mark.asyncio
async def test_index_returns_200(app):
await _test_index_returns_200(app)
@pytest.mark.asyncio
async def test_index_returns_200_dsn(app_dsn):
await _test_index_returns_200(app_dsn)
async def _test(app):
test_client = app.test_client()
for method in '01234':
response = await test_client.get(
'/users/1', query_string={'method': method})
assert response.status_code == 404
response = await test_client.post('/users', form=dict(name='fantix'))
assert response.status_code == 200
assert await response.get_json() == dict(id=1, nickname='fantix')
for method in '01234':
response = await test_client.get(
'/users/1', query_string={'method': method})
assert response.status_code == 200
assert await response.get_json() == dict(id=1, nickname='fantix')
@pytest.mark.asyncio
async def test(app):
await _test(app)
@pytest.mark.asyncio
async def test_dsn(app_dsn):
await _test(app_dsn)
async def _websocket_request(ws, req: dict) -> dict:
await ws.send(json.dumps(req).encode('utf-8'))
return json.loads(await ws.receive())
async def _test_websocket(app):
test_client = app.test_client()
with test_client.websocket('/ws') as ws:
for method in '01234':
response = await _websocket_request(
ws, {'action': 'get', 'id': 1, 'method': method})
assert response.get('error') == 'not found'
response = await _websocket_request(
ws, {'action': 'add', 'name': 'fantix'})
assert response == dict(id=1, nickname='fantix')
for method in '01234':
response = await _websocket_request(
ws, {'action': 'get', 'id': 1, 'method': method})
assert response == dict(id=1, nickname='fantix')
@pytest.mark.asyncio
async def test_ws(app):
await _test_websocket(app)
@pytest.mark.asyncio
async def test_ws_dsn(app_dsn):
await _test_websocket(app_dsn)