forked from qbreader/python-module
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_async.py
More file actions
617 lines (555 loc) · 18.5 KB
/
test_async.py
File metadata and controls
617 lines (555 loc) · 18.5 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
"""Test the asynchronous API functions. This module specifically tests API interaction,
not the underlying data structures. See tests/test_types.py for that."""
import asyncio
from random import random
from typing import Any
import pytest
import pytest_asyncio
import qbreader as qb
from qbreader import Async
from tests import async_assert_exception, check_internet_connection
@pytest.fixture(scope="module")
def event_loop():
"""Rescope the event loop to the module."""
policy = asyncio.get_event_loop_policy()
loop = policy.new_event_loop()
yield loop
loop.close()
@pytest_asyncio.fixture(autouse=True)
async def async_code_is_too_fast_lol():
"""Sleep for up to 0.2 seconds during each test to avoid getting rate limited."""
await asyncio.sleep(random() / 5)
class TestAsync:
"""Test asynchronous API functions."""
@pytest_asyncio.fixture(scope="class")
async def qbr(self):
"""Create an Async instance shared by all tests."""
return await Async.create()
@pytest.fixture()
def mock_get(self, monkeypatch, qbr):
"""Mock aiohttp.ClientSession.get for Async.session"""
def _set_get(mock_status_code: int = 200, mock_json=None, *args, **kwargs):
class MockResponse:
def __init__(self):
self.status = mock_status_code
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass
async def json(self):
return mock_json
monkeypatch.setattr(
qbr.session, "get", lambda *args, **kwargs: MockResponse()
)
return _set_get
def test_internet(self):
"""Test that there is an internet connection."""
assert check_internet_connection(), "No internet connection"
@pytest.mark.asyncio
@pytest.mark.parametrize(
"params, expected_answer",
[
(
{
"questionType": "tossup",
"setName": "2023 PACE NSC",
"queryString": "hashes",
},
"password",
),
(
{
"questionType": qb.Tossup,
"setName": "2023 PACE NSC",
"queryString": "hashes",
},
"password",
),
(
{
"questionType": "bonus",
"setName": "2023 PACE NSC",
"queryString": "bell labs",
},
"C",
),
(
{
"questionType": qb.Bonus,
"setName": "2023 PACE NSC",
"queryString": "bell labs",
},
"C",
),
],
)
async def test_query(self, qbr, params: dict[str, Any], expected_answer: str):
query: qbr.QueryResponse = await qbr.query(**params)
judgement: qbr.AnswerJudgement
if params["questionType"] == "tossup":
judgement = await query.tossups[0].check_answer_async(
expected_answer, session=qbr.session
)
assert judgement.correct()
elif params["questionType"] == "bonus":
judgement = await query.bonuses[0].check_answer_async(
0, expected_answer, session=qbr.session
)
assert judgement.correct()
@pytest.mark.asyncio
async def test_query_min_max_year_range(self, qbr):
min_year = 2010
max_year = 2015
query = await qbr.query(
questionType="tossup",
searchType="question",
min_year=min_year,
max_year=max_year,
maxReturnLength=10,
)
for tossup in query.tossups:
assert min_year <= tossup.set.year <= max_year
@pytest.mark.asyncio
@pytest.mark.parametrize(
"params, exception",
[
(
{
"questionType": "no a valid question type",
},
ValueError,
),
(
{
"searchType": "not a valid search type",
},
ValueError,
),
(
{
"queryString": 1,
},
TypeError,
),
(
{
"regex": "str not bool",
},
TypeError,
),
(
{
"setName": 1,
},
TypeError,
),
(
{
"maxReturnLength": "str not int",
},
TypeError,
),
(
{
"maxReturnLength": -1,
},
ValueError,
),
],
)
async def test_query_exception(
self, qbr, params: dict[str, Any], exception: Exception
):
await async_assert_exception(qbr.query, exception, **params)
@pytest.mark.asyncio
async def test_query_bad_response(self, qbr, mock_get):
mock_get(mock_status_code=404)
await async_assert_exception(qbr.query, Exception)
@pytest.mark.asyncio
@pytest.mark.parametrize("number", [1, 20, 50, 100])
async def test_random_tossup(self, qbr, number: int):
assert len(await qbr.random_tossup(number=number)) == number
@pytest.mark.asyncio
@pytest.mark.parametrize(
"number, exception",
[(0, ValueError), (-1, ValueError), ("1", TypeError), (1.0, TypeError)],
)
async def test_random_tossup_exception(
self, qbr, number: int, exception: Exception
):
await async_assert_exception(qbr.random_tossup, exception, number=number)
@pytest.mark.asyncio
async def test_random_tossup_bad_response(self, qbr, mock_get):
mock_get(mock_status_code=404)
await async_assert_exception(qbr.random_tossup, Exception)
@pytest.mark.asyncio
@pytest.mark.parametrize("number", [1, 20, 50, 100])
async def test_random_bonus(self, qbr, number: int):
assert len(await qbr.random_bonus(number=number)) == number
@pytest.mark.asyncio
@pytest.mark.parametrize(
"number, three_part, exception",
[
(0, False, ValueError),
(-1, False, ValueError),
("1", False, TypeError),
(1.0, False, TypeError),
(1, "not a bool", TypeError),
],
)
async def test_random_bonus_exception(
self, qbr, number: int, three_part: bool, exception: Exception
):
await async_assert_exception(
qbr.random_bonus, exception, number=number, three_part_bonuses=three_part
)
@pytest.mark.asyncio
async def test_random_bonus_bad_response(self, qbr, mock_get):
mock_get(mock_status_code=404)
await async_assert_exception(qbr.random_bonus, Exception)
@pytest.mark.asyncio
async def test_random_name(self, qbr):
assert await qbr.random_name()
@pytest.mark.asyncio
async def test_random_name_bad_response(self, qbr, mock_get):
mock_get(mock_status_code=404)
await async_assert_exception(qbr.random_name, Exception)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"params, question, expected_answer",
[
(
{
"setName": "2023 PACE NSC",
"packetNumber": 1,
},
5,
"negative",
),
(
{
"setName": "2023 PACE NSC",
"packetNumber": 4,
},
16,
"spin",
),
],
)
async def test_packet(
self, qbr, params: dict[str, Any], question: int, expected_answer: str
):
packet: qbr.Packet = await qbr.packet(**params)
judgement: qbr.AnswerJudgement = await packet.tossups[
question - 1
].check_answer_async(expected_answer, session=qbr.session)
assert judgement.correct()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"params, exception",
[
(
{
"setName": 1,
"packetNumber": 1,
},
TypeError,
),
(
{
"setName": "2023 PACE NSC",
"packetNumber": "not an int",
},
TypeError,
),
(
{
"setName": "2023 PACE NSC",
"packetNumber": 0,
},
ValueError,
),
],
)
async def test_packet_exception(
self, qbr, params: dict[str, Any], exception: Exception
):
await async_assert_exception(qbr.packet, exception, **params)
@pytest.mark.asyncio
async def test_packet_bad_response(self, qbr, monkeypatch, mock_get):
mock_get(mock_status_code=404)
async def mock_num_packets(x):
return 21
monkeypatch.setattr(
qbr, "num_packets", mock_num_packets
) # mocking get requests breaks num_packets
await async_assert_exception(
qbr.packet, Exception, setName="2023 PACE NSC", packetNumber=1
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"params, question, expected_answer",
[
(
{
"setName": "2023 PACE NSC",
"packetNumber": 1,
},
5,
"negative",
),
(
{
"setName": "2023 PACE NSC",
"packetNumber": 4,
},
16,
"spin",
),
],
)
async def test_packet_tossups(
self, qbr, params: dict[str, Any], question: int, expected_answer: str
):
tus = await qbr.packet_tossups(**params)
judgement: qbr.AnswerJudgement = await tus[question - 1].check_answer_async(
expected_answer, session=qbr.session
)
assert judgement.correct()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"params, exception",
[
(
{
"setName": 1,
"packetNumber": 1,
},
TypeError,
),
(
{
"setName": "2023 PACE NSC",
"packetNumber": "not an int",
},
TypeError,
),
(
{
"setName": "2023 PACE NSC",
"packetNumber": 0,
},
ValueError,
),
],
)
async def test_packet_tossups_exception(
self, qbr, params: dict[str, Any], exception: Exception
):
await async_assert_exception(qbr.packet_tossups, exception, **params)
@pytest.mark.asyncio
async def test_packet_tossups_bad_response(self, qbr, monkeypatch, mock_get):
mock_get(mock_status_code=404)
async def mock_num_packets(x):
return 21
monkeypatch.setattr(
qbr, "num_packets", mock_num_packets
) # mocking get requests breaks num_packets
await async_assert_exception(
qbr.packet_tossups, Exception, setName="2023 PACE NSC", packetNumber=1
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"params, question, expected_answer",
[
(
{
"setName": "2023 PACE NSC",
"packetNumber": 1,
},
5,
"church",
),
(
{
"setName": "2023 PACE NSC",
"packetNumber": 4,
},
16,
"bananafish",
),
],
)
async def test_packet_bonuses(
self, qbr, params: dict[str, Any], question: int, expected_answer: str
):
bs = await qbr.packet_bonuses(**params)
judgement: qbr.AnswerJudgement = await bs[question - 1].check_answer_async(
0, expected_answer, session=qbr.session
)
assert judgement.correct()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"params, exception",
[
(
{
"setName": 1,
"packetNumber": 1,
},
TypeError,
),
(
{
"setName": "2023 PACE NSC",
"packetNumber": "not an int",
},
TypeError,
),
(
{
"setName": "2023 PACE NSC",
"packetNumber": 0,
},
ValueError,
),
],
)
async def test_packet_bonuses_exception(
self, qbr, params: dict[str, Any], exception: Exception
):
await async_assert_exception(qbr.packet_bonuses, exception, **params)
@pytest.mark.asyncio
async def test_packet_bonuses_bad_response(self, qbr, monkeypatch, mock_get):
mock_get(mock_status_code=404)
async def mock_num_packets(x):
return 21
monkeypatch.setattr(
qbr, "num_packets", mock_num_packets
) # mocking get requests breaks num_packets
await async_assert_exception(
qbr.packet_bonuses, Exception, setName="2023 PACE NSC", packetNumber=1
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"setName, expected",
[("2023 PACE NSC", 21), ("2022 SHOW-ME", 15)],
)
async def test_num_packets(self, qbr, setName: str, expected: int):
assert await qbr.num_packets(setName) == expected
@pytest.mark.asyncio
async def test_num_packets_bad_response(self, qbr, mock_get):
await async_assert_exception(
qbr.num_packets, ValueError, setName="not a set name"
)
mock_get(mock_status_code=400)
await async_assert_exception(
qbr.num_packets, Exception, setName="2023 PACE NSC"
)
@pytest.mark.asyncio
async def test_set_list(self, qbr):
assert await qbr.set_list()
@pytest.mark.asyncio
async def test_set_list_bad_response(self, qbr, mock_get):
mock_get(mock_status_code=404)
await async_assert_exception(qbr.set_list, Exception)
@pytest.mark.asyncio
async def test_room_list(self, qbr):
assert await qbr.room_list()
@pytest.mark.asyncio
async def test_room_list_bad_response(self, qbr, mock_get):
mock_get(mock_status_code=404)
await async_assert_exception(qbr.room_list, Exception)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"answerline, givenAnswer",
[("Rubik's cubes [prompt on cubes and speedcubing]", "Rubik's cubes")],
)
async def test_check_answer(self, qbr, answerline: str, givenAnswer: str):
judgement: qb.AnswerJudgement = await qbr.check_answer(
answerline=answerline, givenAnswer=givenAnswer
)
assert judgement.correct()
judgement = await qb.AnswerJudgement.check_answer_async(
answerline=answerline, givenAnswer=givenAnswer
) # testing no session provided
assert judgement.correct()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"answerline, givenAnswer, exception",
[
("Rubik's cubes [prompt on cubes and speedcubing]", 1, TypeError),
(1, "Rubik's cubes", TypeError),
],
)
async def test_check_answer_exception(
self, qbr, answerline: str, givenAnswer: str, exception: Exception
):
await async_assert_exception(
qbr.check_answer, exception, answerline, givenAnswer
)
await async_assert_exception(
qb.AnswerJudgement.check_answer_async, exception, answerline, givenAnswer
)
@pytest.mark.asyncio
async def test_check_answer_bad_response(self, qbr, mock_get):
mock_get(mock_status_code=404)
await async_assert_exception(
qbr.check_answer,
Exception,
answerline="Rubik's cubes",
givenAnswer="Rubik's cubes",
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"id, expected_answer",
[
("657fd7d7de6df0163bbe3b3d", "Sweden"),
("657fd7d8de6df0163bbe3b43", "jQuery"),
],
)
async def test_tossup_by_id(self, qbr, id: str, expected_answer: str):
tu: qb.Tossup = await qbr.tossup_by_id(id)
judgement: qb.AnswerJudgement = await tu.check_answer_async(
expected_answer, session=qbr.session
)
assert judgement.correct()
@pytest.mark.asyncio
async def test_tossup_by_id_bad_response(self, qbr, mock_get):
await async_assert_exception(qbr.tossup_by_id, ValueError, id="not a valid id")
mock_get(mock_status_code=404)
await async_assert_exception(
qbr.tossup_by_id, Exception, id="657fd7d7de6df0163bbe3b3d"
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"id, expected_answers",
[
("648938e130bd7ab56b095a42", ["volcano", "Magellan", "terra"]),
("648938e130bd7ab56b095a60", ["pH", "NADPH", "perforin"]),
],
)
async def test_bonus_by_id(self, qbr, id: str, expected_answers: list[str]):
b: qb.Bonus = await qbr.bonus_by_id(id)
for i, answer in enumerate(expected_answers):
judgement: qb.AnswerJudgement = await b.check_answer_async(
i, answer, session=qbr.session
)
assert judgement.correct()
@pytest.mark.asyncio
async def test_bonus_by_id_bad_response(self, qbr, mock_get):
await async_assert_exception(qbr.bonus_by_id, ValueError, id="not a valid id")
mock_get(mock_status_code=404)
await async_assert_exception(
qbr.bonus_by_id, Exception, id="648938e130bd7ab56b095a42"
)
@pytest.mark.asyncio
async def test_close(self, qbr):
await qbr.close()
assert qbr.session.closed
@pytest.mark.asyncio
async def test_async_with(self):
qbr = await Async.create()
async with qbr:
assert qbr.session
assert qbr.session.closed