python-ballchasing 0.5.3__py3-none-any.whl → 0.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ballchasing/__init__.py +1 -0
- ballchasing/api.py +214 -33
- ballchasing/constants.py +12 -9
- ballchasing/exceptions.py +37 -0
- ballchasing/rate_limit.py +13 -1
- ballchasing/stats_info.tsv +29 -1
- ballchasing/typed/__init__.py +2 -5
- ballchasing/typed/_base.py +106 -0
- ballchasing/typed/deep_group.py +26 -440
- ballchasing/typed/deep_replay.py +23 -286
- ballchasing/typed/methods.py +145 -0
- ballchasing/typed/models.py +954 -0
- ballchasing/typed/shallow_group.py +3 -18
- ballchasing/typed/shallow_replay.py +5 -66
- ballchasing/typed/shared.py +6 -243
- ballchasing/util/iterators.py +1 -1
- ballchasing/util/stats.py +3 -3
- {python_ballchasing-0.5.3.dist-info → python_ballchasing-0.6.0.dist-info}/METADATA +18 -2
- python_ballchasing-0.6.0.dist-info/RECORD +25 -0
- {python_ballchasing-0.5.3.dist-info → python_ballchasing-0.6.0.dist-info}/WHEEL +1 -1
- python_ballchasing-0.6.0.dist-info/top_level.txt +1 -0
- python_ballchasing-0.5.3.dist-info/RECORD +0 -26
- python_ballchasing-0.5.3.dist-info/top_level.txt +0 -3
- scripts/get_maps.py +0 -147
- scripts/make_types.py +0 -194
- scripts/test.py +0 -52
- scripts/test_typed.py +0 -88
- tests/test_fixes.py +0 -430
- {python_ballchasing-0.5.3.dist-info → python_ballchasing-0.6.0.dist-info}/licenses/LICENSE +0 -0
tests/test_fixes.py
DELETED
|
@@ -1,430 +0,0 @@
|
|
|
1
|
-
import io
|
|
2
|
-
import logging
|
|
3
|
-
import time
|
|
4
|
-
from pathlib import Path
|
|
5
|
-
from unittest.mock import patch, MagicMock
|
|
6
|
-
import pytest
|
|
7
|
-
from requests import Response
|
|
8
|
-
from requests.exceptions import ConnectionError as RequestsConnectionError, HTTPError, Timeout
|
|
9
|
-
|
|
10
|
-
from ballchasing.api import BallchasingApi, PATRON_RATE_LIMIT_SLEEP_TIMES
|
|
11
|
-
from ballchasing.constants import Map
|
|
12
|
-
from ballchasing.rate_limit import RateLimiter, RateLimitCategory, resolve_category, rate_limited
|
|
13
|
-
from ballchasing.typed.shared import PlayerID, BasePlayer, BaseReplay
|
|
14
|
-
from ballchasing.typed.deep_replay import DeepReplay, TeamCoreStatsDR, PlayerCoreStatsDR
|
|
15
|
-
from ballchasing.util.replays import is_standard_replay
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def make_mock_response(status_code=200, json_data=None, headers=None, content=None):
|
|
19
|
-
resp = Response()
|
|
20
|
-
resp.status_code = status_code
|
|
21
|
-
if content is not None:
|
|
22
|
-
resp._content = content
|
|
23
|
-
resp.raw = io.BytesIO(content)
|
|
24
|
-
elif json_data is not None:
|
|
25
|
-
raw_bytes = bytes(__import__("json").dumps(json_data), "utf-8")
|
|
26
|
-
resp._content = raw_bytes
|
|
27
|
-
resp.raw = io.BytesIO(raw_bytes)
|
|
28
|
-
else:
|
|
29
|
-
resp._content = b"{}"
|
|
30
|
-
resp.raw = io.BytesIO(b"{}")
|
|
31
|
-
if headers:
|
|
32
|
-
resp.headers.update(headers)
|
|
33
|
-
return resp
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
class TestInitialPingBypass:
|
|
37
|
-
def test_do_initial_ping_false_makes_no_requests(self):
|
|
38
|
-
with patch.object(BallchasingApi, "_request") as mock_request:
|
|
39
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
40
|
-
mock_request.assert_not_called()
|
|
41
|
-
assert api._ping_result is None
|
|
42
|
-
|
|
43
|
-
def test_sleep_time_on_rate_limit_defaults_to_regular_when_not_pinged(self):
|
|
44
|
-
with patch.object(BallchasingApi, "_request") as mock_request:
|
|
45
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
46
|
-
assert api.sleep_time_on_rate_limit == PATRON_RATE_LIMIT_SLEEP_TIMES["regular"]
|
|
47
|
-
mock_request.assert_not_called()
|
|
48
|
-
|
|
49
|
-
def test_sleep_time_on_rate_limit_explicit(self):
|
|
50
|
-
api = BallchasingApi("dummy_key", sleep_time_on_rate_limit=1.5, do_initial_ping=False)
|
|
51
|
-
assert api.sleep_time_on_rate_limit == 1.5
|
|
52
|
-
|
|
53
|
-
def test_sleep_time_updates_after_ping(self):
|
|
54
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
55
|
-
assert api.sleep_time_on_rate_limit == PATRON_RATE_LIMIT_SLEEP_TIMES["regular"]
|
|
56
|
-
|
|
57
|
-
# Simulate ping result later
|
|
58
|
-
api._ping_result = {"type": "gold", "name": "TestUser"}
|
|
59
|
-
assert api.sleep_time_on_rate_limit == PATRON_RATE_LIMIT_SLEEP_TIMES["gold"]
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
class TestHttpRetryAndLogging:
|
|
63
|
-
@pytest.mark.parametrize("status_code", [502, 503, 504])
|
|
64
|
-
def test_retry_transient_gateway_errors(self, status_code):
|
|
65
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
66
|
-
err_resp = make_mock_response(status_code=status_code)
|
|
67
|
-
ok_resp = make_mock_response(status_code=200, json_data={"success": True})
|
|
68
|
-
|
|
69
|
-
with patch.object(api._session, "request", side_effect=[err_resp, ok_resp]) as mock_req, \
|
|
70
|
-
patch("time.sleep") as mock_sleep:
|
|
71
|
-
res = api._request("/test", "GET")
|
|
72
|
-
assert res.status_code == 200
|
|
73
|
-
assert mock_req.call_count == 2
|
|
74
|
-
mock_sleep.assert_called_once_with(1) # 2 ** 0
|
|
75
|
-
|
|
76
|
-
def test_retry_timeout(self):
|
|
77
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
78
|
-
ok_resp = make_mock_response(status_code=200, json_data={"success": True})
|
|
79
|
-
|
|
80
|
-
with patch.object(api._session, "request", side_effect=[Timeout("timed out"), ok_resp]) as mock_req, \
|
|
81
|
-
patch("time.sleep") as mock_sleep:
|
|
82
|
-
res = api._request("/test", "GET")
|
|
83
|
-
assert res.status_code == 200
|
|
84
|
-
assert mock_req.call_count == 2
|
|
85
|
-
mock_sleep.assert_called_once_with(1)
|
|
86
|
-
|
|
87
|
-
def test_retry_exhaustion_raises(self):
|
|
88
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
89
|
-
err_resp = make_mock_response(status_code=502)
|
|
90
|
-
|
|
91
|
-
with patch.object(api._session, "request", return_value=err_resp), \
|
|
92
|
-
patch("time.sleep"):
|
|
93
|
-
with pytest.raises(RequestsConnectionError):
|
|
94
|
-
api._request("/test", "GET")
|
|
95
|
-
|
|
96
|
-
def test_rate_limit_backoff_retry_after(self):
|
|
97
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
98
|
-
rl_resp = make_mock_response(status_code=429, headers={"Retry-After": "3"})
|
|
99
|
-
ok_resp = make_mock_response(status_code=200, json_data={"ok": True})
|
|
100
|
-
|
|
101
|
-
with patch.object(api._session, "request", side_effect=[rl_resp, ok_resp]), \
|
|
102
|
-
patch("time.sleep") as mock_sleep:
|
|
103
|
-
res = api._request("/test", "GET")
|
|
104
|
-
assert res.status_code == 200
|
|
105
|
-
mock_sleep.assert_called_once_with(3.0)
|
|
106
|
-
|
|
107
|
-
def test_rate_limit_backoff_default_when_unset(self):
|
|
108
|
-
api = BallchasingApi("dummy_key", sleep_time_on_rate_limit=0, do_initial_ping=False)
|
|
109
|
-
rl_resp = make_mock_response(status_code=429)
|
|
110
|
-
ok_resp = make_mock_response(status_code=200, json_data={"ok": True})
|
|
111
|
-
|
|
112
|
-
with patch.object(api._session, "request", side_effect=[rl_resp, ok_resp]), \
|
|
113
|
-
patch("time.sleep") as mock_sleep:
|
|
114
|
-
res = api._request("/test", "GET")
|
|
115
|
-
assert res.status_code == 200
|
|
116
|
-
assert mock_sleep.call_count == 1
|
|
117
|
-
assert mock_sleep.call_args[0][0] >= 1.0
|
|
118
|
-
|
|
119
|
-
def test_rate_limit_retries_indefinitely(self):
|
|
120
|
-
api = BallchasingApi("dummy_key", sleep_time_on_rate_limit=0.125, do_initial_ping=False)
|
|
121
|
-
# Simulate 10 consecutive 429s followed by a 200 OK
|
|
122
|
-
rl_resps = [make_mock_response(status_code=429) for _ in range(10)]
|
|
123
|
-
ok_resp = make_mock_response(status_code=200, json_data={"ok": True})
|
|
124
|
-
|
|
125
|
-
with patch.object(api._session, "request", side_effect=rl_resps + [ok_resp]), \
|
|
126
|
-
patch("time.sleep") as mock_sleep:
|
|
127
|
-
res = api._request("/test", "GET")
|
|
128
|
-
assert res.status_code == 200
|
|
129
|
-
assert mock_sleep.call_count == 10
|
|
130
|
-
|
|
131
|
-
def test_logging_used_on_retry(self, caplog):
|
|
132
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False, print_on_rate_limit=True)
|
|
133
|
-
rl_resp = make_mock_response(status_code=429)
|
|
134
|
-
ok_resp = make_mock_response(status_code=200, json_data={"ok": True})
|
|
135
|
-
|
|
136
|
-
with caplog.at_level(logging.WARNING, logger="ballchasing"), \
|
|
137
|
-
patch.object(api._session, "request", side_effect=[rl_resp, ok_resp]), \
|
|
138
|
-
patch("time.sleep"):
|
|
139
|
-
api._request("/test", "GET")
|
|
140
|
-
assert any("Rate limited" in record.message for record in caplog.records)
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
class TestDeduplicationBeforeDeepFetch:
|
|
144
|
-
def test_get_replays_deduplicates_before_deep_call(self):
|
|
145
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
146
|
-
replays_batch = [
|
|
147
|
-
{"id": "rep1", "rocket_league_id": "rl1"},
|
|
148
|
-
{"id": "rep1", "rocket_league_id": "rl1"}, # duplicate id
|
|
149
|
-
{"id": "rep2", "rocket_league_id": "rl2"},
|
|
150
|
-
]
|
|
151
|
-
|
|
152
|
-
def fake_iterable(*args, **kwargs):
|
|
153
|
-
yield from replays_batch
|
|
154
|
-
|
|
155
|
-
with patch.object(api, "_iterable_from_request", side_effect=fake_iterable), \
|
|
156
|
-
patch.object(api, "get_replay", side_effect=lambda rid: {"id": rid, "deep": True}) as mock_get_replay:
|
|
157
|
-
results = list(api.get_replays(deep=True, deduplicate=True))
|
|
158
|
-
assert len(results) == 2
|
|
159
|
-
assert [r["id"] for r in results] == ["rep1", "rep2"]
|
|
160
|
-
# get_replay should only have been called twice (for rep1 and rep2), NOT 3 times
|
|
161
|
-
assert mock_get_replay.call_count == 2
|
|
162
|
-
mock_get_replay.assert_any_call("rep1")
|
|
163
|
-
mock_get_replay.assert_any_call("rep2")
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
class TestCountZeroIterable:
|
|
167
|
-
def test_count_zero_makes_no_requests(self):
|
|
168
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
169
|
-
with patch.object(api, "_request") as mock_req:
|
|
170
|
-
replays = list(api.get_replays(count=0))
|
|
171
|
-
assert replays == []
|
|
172
|
-
mock_req.assert_not_called()
|
|
173
|
-
|
|
174
|
-
groups = list(api.get_groups(count=0))
|
|
175
|
-
assert groups == []
|
|
176
|
-
mock_req.assert_not_called()
|
|
177
|
-
|
|
178
|
-
def test_next_url_missing_after_param_handled_defensively(self):
|
|
179
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
180
|
-
# First page has 'next' without 'after' query param
|
|
181
|
-
page1 = {"list": [{"id": "r1"}], "next": "https://ballchasing.com/api/replays?other=val"}
|
|
182
|
-
|
|
183
|
-
with patch.object(api, "_request") as mock_req:
|
|
184
|
-
mock_req.return_value = make_mock_response(200, json_data=page1)
|
|
185
|
-
replays = list(api.get_replays(count=10, disable_prefetch=True))
|
|
186
|
-
assert len(replays) == 1
|
|
187
|
-
assert replays[0]["id"] == "r1"
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
class TestToDictPreservesFalsyValues:
|
|
191
|
-
def test_preserves_zero_and_false(self):
|
|
192
|
-
pid = PlayerID(platform="steam", id="12345", player_number=0)
|
|
193
|
-
d = pid.to_dict()
|
|
194
|
-
assert d["player_number"] == 0
|
|
195
|
-
assert d["id"] == "12345"
|
|
196
|
-
assert d["platform"] == "steam"
|
|
197
|
-
|
|
198
|
-
player = BasePlayer(name="Test", id=pid, pro=False, mvp=False)
|
|
199
|
-
pd = player.to_dict()
|
|
200
|
-
assert pd["pro"] is False
|
|
201
|
-
assert pd["mvp"] is False
|
|
202
|
-
|
|
203
|
-
core = PlayerCoreStatsDR(goals=0, assists=0, saves=0, score=0, mvp=False)
|
|
204
|
-
cd = core.to_dict()
|
|
205
|
-
assert cd["goals"] == 0
|
|
206
|
-
assert cd["assists"] == 0
|
|
207
|
-
assert cd["saves"] == 0
|
|
208
|
-
assert cd["score"] == 0
|
|
209
|
-
assert cd["mvp"] is False
|
|
210
|
-
|
|
211
|
-
replay = BaseReplay(duration=300, overtime=False, overtime_seconds=0)
|
|
212
|
-
rd = replay.to_dict()
|
|
213
|
-
assert rd["overtime"] is False
|
|
214
|
-
assert rd["overtime_seconds"] == 0
|
|
215
|
-
assert rd["duration"] == 300
|
|
216
|
-
|
|
217
|
-
def test_drops_none(self):
|
|
218
|
-
player = BasePlayer(name="Test", rank=None)
|
|
219
|
-
pd = player.to_dict()
|
|
220
|
-
assert "rank" not in pd
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
class TestNonePlayerIdFixes:
|
|
224
|
-
def test_base_player_is_bot_with_none_id(self):
|
|
225
|
-
player = BasePlayer(name="BotPlayer", id=None)
|
|
226
|
-
assert player.is_bot() is True
|
|
227
|
-
|
|
228
|
-
def test_base_player_is_bot_with_empty_id(self):
|
|
229
|
-
player = BasePlayer(name="BotPlayer", id=PlayerID(platform="", id=""))
|
|
230
|
-
assert player.is_bot() is True
|
|
231
|
-
|
|
232
|
-
def test_base_player_is_not_bot(self):
|
|
233
|
-
player = BasePlayer(name="Human", id=PlayerID(platform="steam", id="123"))
|
|
234
|
-
assert player.is_bot() is False
|
|
235
|
-
|
|
236
|
-
def test_is_standard_replay_with_none_player_id(self):
|
|
237
|
-
# Construct a replay where a player has id: None
|
|
238
|
-
replay = {
|
|
239
|
-
"id": "rep123",
|
|
240
|
-
"playlist_id": "ranked-doubles",
|
|
241
|
-
"map_code": Map.STADIUM_P,
|
|
242
|
-
"duration": 300,
|
|
243
|
-
"blue": {
|
|
244
|
-
"goals": 2,
|
|
245
|
-
"players": [
|
|
246
|
-
{"name": "P1", "start_time": 0, "end_time": 300, "id": {"platform": "steam", "id": "1", "player_number": 0}},
|
|
247
|
-
{"name": "Bot1", "start_time": 0, "end_time": 300, "id": None},
|
|
248
|
-
]
|
|
249
|
-
},
|
|
250
|
-
"orange": {
|
|
251
|
-
"goals": 1,
|
|
252
|
-
"players": [
|
|
253
|
-
{"name": "P2", "start_time": 0, "end_time": 300, "id": {"platform": "steam", "id": "2", "player_number": 0}},
|
|
254
|
-
{"name": "P3", "start_time": 0, "end_time": 300, "id": {"platform": "steam", "id": "3", "player_number": 0}},
|
|
255
|
-
]
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
# With allow_bots=True, should not crash with AttributeError and should be valid
|
|
259
|
-
valid, reason = is_standard_replay(replay, allow_bots=True)
|
|
260
|
-
assert valid is True
|
|
261
|
-
assert reason == "No issues found"
|
|
262
|
-
|
|
263
|
-
# With allow_bots=False, should return False because Bot1 has no ID, without crashing
|
|
264
|
-
valid_nobots, reason_nobots = is_standard_replay(replay, allow_bots=False)
|
|
265
|
-
assert valid_nobots is False
|
|
266
|
-
assert "Bot1 has no ID" in reason_nobots
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
class TestApiDocReflections:
|
|
270
|
-
def test_upload_replay_returns_id_on_duplicate_409_when_not_raising(self):
|
|
271
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
272
|
-
resp_409 = make_mock_response(409, json_data={"id": "existing-replay-id", "error": "duplicate replay"})
|
|
273
|
-
|
|
274
|
-
with patch.object(api._session, "request", return_value=resp_409):
|
|
275
|
-
result = api.upload_replay(io.BytesIO(b"dummy_replay_data"), raise_on_duplicate=False)
|
|
276
|
-
assert result["id"] == "existing-replay-id"
|
|
277
|
-
|
|
278
|
-
def test_upload_replay_raises_on_duplicate_409_when_configured(self):
|
|
279
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
280
|
-
resp_409 = make_mock_response(409, json_data={"id": "existing-replay-id", "error": "duplicate replay"})
|
|
281
|
-
|
|
282
|
-
with patch.object(api._session, "request", return_value=resp_409):
|
|
283
|
-
with pytest.raises(HTTPError):
|
|
284
|
-
api.upload_replay(io.BytesIO(b"dummy_replay_data"), raise_on_duplicate=True)
|
|
285
|
-
|
|
286
|
-
def test_create_group_omits_parent_when_none(self):
|
|
287
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
288
|
-
ok_resp = make_mock_response(201, json_data={"id": "grp1", "name": "Top Level"})
|
|
289
|
-
|
|
290
|
-
with patch.object(api._session, "request", return_value=ok_resp) as mock_req:
|
|
291
|
-
res = api.create_group(name="Top Level", player_identification="by-id", team_identification="by-distinct-players")
|
|
292
|
-
assert res["id"] == "grp1"
|
|
293
|
-
assert mock_req.call_count == 1
|
|
294
|
-
payload = mock_req.call_args[1]["json"]
|
|
295
|
-
assert "parent" not in payload
|
|
296
|
-
assert payload == {
|
|
297
|
-
"name": "Top Level",
|
|
298
|
-
"player_identification": "by-id",
|
|
299
|
-
"team_identification": "by-distinct-players"
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
def test_create_group_includes_parent_when_provided(self):
|
|
303
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
304
|
-
ok_resp = make_mock_response(201, json_data={"id": "grp2", "name": "Child Group"})
|
|
305
|
-
|
|
306
|
-
with patch.object(api._session, "request", return_value=ok_resp) as mock_req:
|
|
307
|
-
api.create_group(name="Child Group", player_identification="by-id", team_identification="by-distinct-players", parent="parent-grp")
|
|
308
|
-
payload = mock_req.call_args[1]["json"]
|
|
309
|
-
assert payload["parent"] == "parent-grp"
|
|
310
|
-
|
|
311
|
-
def test_patch_replay_explicit_kwargs(self):
|
|
312
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
313
|
-
ok_resp = make_mock_response(204)
|
|
314
|
-
|
|
315
|
-
with patch.object(api._session, "request", return_value=ok_resp) as mock_req:
|
|
316
|
-
api.patch_replay("rep-123", title="New Title", visibility="private", group="")
|
|
317
|
-
payload = mock_req.call_args[1]["json"]
|
|
318
|
-
assert payload == {"title": "New Title", "visibility": "private", "group": ""}
|
|
319
|
-
|
|
320
|
-
def test_patch_group_explicit_kwargs(self):
|
|
321
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
322
|
-
ok_resp = make_mock_response(204)
|
|
323
|
-
|
|
324
|
-
with patch.object(api._session, "request", return_value=ok_resp) as mock_req:
|
|
325
|
-
api.patch_group("grp-123", player_identification="by-name", team_identification="by-player-clusters", parent="new-parent", shared=True)
|
|
326
|
-
payload = mock_req.call_args[1]["json"]
|
|
327
|
-
assert payload == {
|
|
328
|
-
"player_identification": "by-name",
|
|
329
|
-
"team_identification": "by-player-clusters",
|
|
330
|
-
"parent": "new-parent",
|
|
331
|
-
"shared": True
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
def test_get_groups_url_no_trailing_slash(self):
|
|
335
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
336
|
-
ok_resp = make_mock_response(200, json_data={"list": []})
|
|
337
|
-
|
|
338
|
-
with patch.object(api._session, "request", return_value=ok_resp) as mock_req:
|
|
339
|
-
list(api.get_groups(count=10, disable_prefetch=True))
|
|
340
|
-
called_url = mock_req.call_args[1]["url"]
|
|
341
|
-
assert called_url == f"{api.base_url}/groups"
|
|
342
|
-
|
|
343
|
-
def test_download_replay_supports_pathlib(self, tmp_path):
|
|
344
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
345
|
-
ok_resp = make_mock_response(200, content=b"PK\x03\x04fake_replay_binary")
|
|
346
|
-
|
|
347
|
-
with patch.object(api._session, "request", return_value=ok_resp):
|
|
348
|
-
dest = api.download_replay("rep-123", tmp_path)
|
|
349
|
-
assert dest == tmp_path / "rep-123.replay"
|
|
350
|
-
assert dest.read_bytes() == b"PK\x03\x04fake_replay_binary"
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
class TestRateLimitingAndTracker:
|
|
354
|
-
def test_initial_state_not_rate_limited(self):
|
|
355
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
356
|
-
assert api.is_rate_limited is False
|
|
357
|
-
assert api.last_rate_limited_at is None
|
|
358
|
-
stats = api.rate_limit_stats
|
|
359
|
-
assert stats["is_rate_limited"] is False
|
|
360
|
-
assert stats["last_rate_limited_at"] is None
|
|
361
|
-
assert stats["category_counts"] == {}
|
|
362
|
-
|
|
363
|
-
def test_category_resolution(self):
|
|
364
|
-
assert resolve_category("/replays") == RateLimitCategory.LIST
|
|
365
|
-
assert resolve_category("https://ballchasing.com/api/groups") == RateLimitCategory.LIST
|
|
366
|
-
assert resolve_category("/replays/123/file") == RateLimitCategory.DOWNLOAD
|
|
367
|
-
assert resolve_category("/replays/abc-123") == RateLimitCategory.CORE
|
|
368
|
-
assert resolve_category("/groups/grp-456") == RateLimitCategory.CORE
|
|
369
|
-
assert resolve_category("/v2/upload") == RateLimitCategory.CORE
|
|
370
|
-
assert resolve_category("/maps") == RateLimitCategory.CORE
|
|
371
|
-
assert resolve_category("/") == RateLimitCategory.PING
|
|
372
|
-
|
|
373
|
-
def test_record_429_updates_tracker_and_stats(self):
|
|
374
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
375
|
-
rl_resp = make_mock_response(status_code=429, headers={"Retry-After": "5"})
|
|
376
|
-
ok_resp = make_mock_response(status_code=200, json_data={"list": []})
|
|
377
|
-
|
|
378
|
-
with patch.object(api._session, "request", side_effect=[rl_resp, ok_resp]), \
|
|
379
|
-
patch("time.sleep"):
|
|
380
|
-
api._request("/replays", "GET")
|
|
381
|
-
|
|
382
|
-
assert api.last_rate_limited_at is not None
|
|
383
|
-
assert time.time() - api.last_rate_limited_at < 5.0
|
|
384
|
-
stats = api.rate_limit_stats
|
|
385
|
-
assert stats["category_counts"].get("list") == 1
|
|
386
|
-
assert "list" in stats["last_per_category"]
|
|
387
|
-
|
|
388
|
-
def test_category_sleep_times(self):
|
|
389
|
-
limiter = RateLimiter(patron_type_getter=lambda: "regular")
|
|
390
|
-
assert limiter.get_category_sleep_time(RateLimitCategory.LIST) == 3600 / 500 # 7.2s
|
|
391
|
-
assert limiter.get_category_sleep_time(RateLimitCategory.CORE) == 3600 / 1000 # 3.6s
|
|
392
|
-
assert limiter.get_category_sleep_time(RateLimitCategory.DOWNLOAD) == 3600 / 200 # 18.0s
|
|
393
|
-
|
|
394
|
-
gold_limiter = RateLimiter(patron_type_getter=lambda: "gold")
|
|
395
|
-
assert gold_limiter.get_category_sleep_time(RateLimitCategory.LIST) == 3600 / 1000 # 3.6s
|
|
396
|
-
assert gold_limiter.get_category_sleep_time(RateLimitCategory.CORE) == 3600 / 2000 # 1.8s
|
|
397
|
-
assert gold_limiter.get_category_sleep_time(RateLimitCategory.DOWNLOAD) == 3600 / 400 # 9.0s
|
|
398
|
-
|
|
399
|
-
def test_global_tracker_blocks_concurrent_requests(self):
|
|
400
|
-
# Simulate instance being put into cooldown
|
|
401
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
402
|
-
api.rate_limiter.record_429(RateLimitCategory.CORE, retry_after=5.0)
|
|
403
|
-
|
|
404
|
-
assert api.is_rate_limited is True
|
|
405
|
-
# A subsequent call to before_request should sleep for the remaining cooldown
|
|
406
|
-
with patch("time.sleep") as mock_sleep:
|
|
407
|
-
api.rate_limiter.before_request(RateLimitCategory.LIST)
|
|
408
|
-
assert mock_sleep.call_count == 1
|
|
409
|
-
slept = mock_sleep.call_args[0][0]
|
|
410
|
-
assert 0.0 < slept <= 5.0
|
|
411
|
-
|
|
412
|
-
def test_proactive_mode_enforces_burst_rate(self):
|
|
413
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False, proactive_rate_limit=True)
|
|
414
|
-
# On proactive mode, 2 calls in immediate succession will sleep for min_interval
|
|
415
|
-
with patch("time.sleep") as mock_sleep:
|
|
416
|
-
api.rate_limiter.before_request(RateLimitCategory.LIST)
|
|
417
|
-
# First call has no elapsed constraint
|
|
418
|
-
assert mock_sleep.call_count == 0
|
|
419
|
-
# Immediate second call should sleep
|
|
420
|
-
api.rate_limiter.before_request(RateLimitCategory.LIST)
|
|
421
|
-
assert mock_sleep.call_count == 1
|
|
422
|
-
slept = mock_sleep.call_args[0][0]
|
|
423
|
-
assert 0.4 <= slept <= 0.6 # 1 / 2.0s = 0.5s interval
|
|
424
|
-
|
|
425
|
-
def test_rate_limited_decorator_attaches_to_api_methods(self):
|
|
426
|
-
api = BallchasingApi("dummy_key", do_initial_ping=False)
|
|
427
|
-
assert getattr(api.get_replay, "rate_limit_category", None) == RateLimitCategory.CORE
|
|
428
|
-
assert getattr(api.get_replays, "rate_limit_category", None) == RateLimitCategory.LIST
|
|
429
|
-
assert getattr(api.download_replay, "rate_limit_category", None) == RateLimitCategory.DOWNLOAD
|
|
430
|
-
assert getattr(api.ping, "rate_limit_category", None) == RateLimitCategory.PING
|
|
File without changes
|