python-ballchasing 0.5.4__py3-none-any.whl → 0.6.1__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.
tests/test_fixes.py DELETED
@@ -1,439 +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_initial_ping_with_rate_limiter(self):
120
- # Ensure that do_initial_ping=True does not raise AttributeError: no attribute rate_limiter
121
- mock_resp = make_mock_response(status_code=200, json_data={"name": "TestUser", "type": "champion"})
122
- with patch("requests.sessions.Session.request", return_value=mock_resp):
123
- api = BallchasingApi("dummy_key", do_initial_ping=True, proactive_rate_limit=True)
124
- assert api.steam_name == "TestUser"
125
- assert api.patron_type == "champion"
126
- assert hasattr(api, "rate_limiter")
127
-
128
- def test_rate_limit_retries_indefinitely(self):
129
- api = BallchasingApi("dummy_key", sleep_time_on_rate_limit=0.125, do_initial_ping=False)
130
- # Simulate 10 consecutive 429s followed by a 200 OK
131
- rl_resps = [make_mock_response(status_code=429) for _ in range(10)]
132
- ok_resp = make_mock_response(status_code=200, json_data={"ok": True})
133
-
134
- with patch.object(api._session, "request", side_effect=rl_resps + [ok_resp]), \
135
- patch("time.sleep") as mock_sleep:
136
- res = api._request("/test", "GET")
137
- assert res.status_code == 200
138
- assert mock_sleep.call_count == 10
139
-
140
- def test_logging_used_on_retry(self, caplog):
141
- api = BallchasingApi("dummy_key", do_initial_ping=False, print_on_rate_limit=True)
142
- rl_resp = make_mock_response(status_code=429)
143
- ok_resp = make_mock_response(status_code=200, json_data={"ok": True})
144
-
145
- with caplog.at_level(logging.WARNING, logger="ballchasing"), \
146
- patch.object(api._session, "request", side_effect=[rl_resp, ok_resp]), \
147
- patch("time.sleep"):
148
- api._request("/test", "GET")
149
- assert any("Rate limited" in record.message for record in caplog.records)
150
-
151
-
152
- class TestDeduplicationBeforeDeepFetch:
153
- def test_get_replays_deduplicates_before_deep_call(self):
154
- api = BallchasingApi("dummy_key", do_initial_ping=False)
155
- replays_batch = [
156
- {"id": "rep1", "rocket_league_id": "rl1"},
157
- {"id": "rep1", "rocket_league_id": "rl1"}, # duplicate id
158
- {"id": "rep2", "rocket_league_id": "rl2"},
159
- ]
160
-
161
- def fake_iterable(*args, **kwargs):
162
- yield from replays_batch
163
-
164
- with patch.object(api, "_iterable_from_request", side_effect=fake_iterable), \
165
- patch.object(api, "get_replay", side_effect=lambda rid: {"id": rid, "deep": True}) as mock_get_replay:
166
- results = list(api.get_replays(deep=True, deduplicate=True))
167
- assert len(results) == 2
168
- assert [r["id"] for r in results] == ["rep1", "rep2"]
169
- # get_replay should only have been called twice (for rep1 and rep2), NOT 3 times
170
- assert mock_get_replay.call_count == 2
171
- mock_get_replay.assert_any_call("rep1")
172
- mock_get_replay.assert_any_call("rep2")
173
-
174
-
175
- class TestCountZeroIterable:
176
- def test_count_zero_makes_no_requests(self):
177
- api = BallchasingApi("dummy_key", do_initial_ping=False)
178
- with patch.object(api, "_request") as mock_req:
179
- replays = list(api.get_replays(count=0))
180
- assert replays == []
181
- mock_req.assert_not_called()
182
-
183
- groups = list(api.get_groups(count=0))
184
- assert groups == []
185
- mock_req.assert_not_called()
186
-
187
- def test_next_url_missing_after_param_handled_defensively(self):
188
- api = BallchasingApi("dummy_key", do_initial_ping=False)
189
- # First page has 'next' without 'after' query param
190
- page1 = {"list": [{"id": "r1"}], "next": "https://ballchasing.com/api/replays?other=val"}
191
-
192
- with patch.object(api, "_request") as mock_req:
193
- mock_req.return_value = make_mock_response(200, json_data=page1)
194
- replays = list(api.get_replays(count=10, disable_prefetch=True))
195
- assert len(replays) == 1
196
- assert replays[0]["id"] == "r1"
197
-
198
-
199
- class TestToDictPreservesFalsyValues:
200
- def test_preserves_zero_and_false(self):
201
- pid = PlayerID(platform="steam", id="12345", player_number=0)
202
- d = pid.to_dict()
203
- assert d["player_number"] == 0
204
- assert d["id"] == "12345"
205
- assert d["platform"] == "steam"
206
-
207
- player = BasePlayer(name="Test", id=pid, pro=False, mvp=False)
208
- pd = player.to_dict()
209
- assert pd["pro"] is False
210
- assert pd["mvp"] is False
211
-
212
- core = PlayerCoreStatsDR(goals=0, assists=0, saves=0, score=0, mvp=False)
213
- cd = core.to_dict()
214
- assert cd["goals"] == 0
215
- assert cd["assists"] == 0
216
- assert cd["saves"] == 0
217
- assert cd["score"] == 0
218
- assert cd["mvp"] is False
219
-
220
- replay = BaseReplay(duration=300, overtime=False, overtime_seconds=0)
221
- rd = replay.to_dict()
222
- assert rd["overtime"] is False
223
- assert rd["overtime_seconds"] == 0
224
- assert rd["duration"] == 300
225
-
226
- def test_drops_none(self):
227
- player = BasePlayer(name="Test", rank=None)
228
- pd = player.to_dict()
229
- assert "rank" not in pd
230
-
231
-
232
- class TestNonePlayerIdFixes:
233
- def test_base_player_is_bot_with_none_id(self):
234
- player = BasePlayer(name="BotPlayer", id=None)
235
- assert player.is_bot() is True
236
-
237
- def test_base_player_is_bot_with_empty_id(self):
238
- player = BasePlayer(name="BotPlayer", id=PlayerID(platform="", id=""))
239
- assert player.is_bot() is True
240
-
241
- def test_base_player_is_not_bot(self):
242
- player = BasePlayer(name="Human", id=PlayerID(platform="steam", id="123"))
243
- assert player.is_bot() is False
244
-
245
- def test_is_standard_replay_with_none_player_id(self):
246
- # Construct a replay where a player has id: None
247
- replay = {
248
- "id": "rep123",
249
- "playlist_id": "ranked-doubles",
250
- "map_code": Map.STADIUM_P,
251
- "duration": 300,
252
- "blue": {
253
- "goals": 2,
254
- "players": [
255
- {"name": "P1", "start_time": 0, "end_time": 300, "id": {"platform": "steam", "id": "1", "player_number": 0}},
256
- {"name": "Bot1", "start_time": 0, "end_time": 300, "id": None},
257
- ]
258
- },
259
- "orange": {
260
- "goals": 1,
261
- "players": [
262
- {"name": "P2", "start_time": 0, "end_time": 300, "id": {"platform": "steam", "id": "2", "player_number": 0}},
263
- {"name": "P3", "start_time": 0, "end_time": 300, "id": {"platform": "steam", "id": "3", "player_number": 0}},
264
- ]
265
- }
266
- }
267
- # With allow_bots=True, should not crash with AttributeError and should be valid
268
- valid, reason = is_standard_replay(replay, allow_bots=True)
269
- assert valid is True
270
- assert reason == "No issues found"
271
-
272
- # With allow_bots=False, should return False because Bot1 has no ID, without crashing
273
- valid_nobots, reason_nobots = is_standard_replay(replay, allow_bots=False)
274
- assert valid_nobots is False
275
- assert "Bot1 has no ID" in reason_nobots
276
-
277
-
278
- class TestApiDocReflections:
279
- def test_upload_replay_returns_id_on_duplicate_409_when_not_raising(self):
280
- api = BallchasingApi("dummy_key", do_initial_ping=False)
281
- resp_409 = make_mock_response(409, json_data={"id": "existing-replay-id", "error": "duplicate replay"})
282
-
283
- with patch.object(api._session, "request", return_value=resp_409):
284
- result = api.upload_replay(io.BytesIO(b"dummy_replay_data"), raise_on_duplicate=False)
285
- assert result["id"] == "existing-replay-id"
286
-
287
- def test_upload_replay_raises_on_duplicate_409_when_configured(self):
288
- api = BallchasingApi("dummy_key", do_initial_ping=False)
289
- resp_409 = make_mock_response(409, json_data={"id": "existing-replay-id", "error": "duplicate replay"})
290
-
291
- with patch.object(api._session, "request", return_value=resp_409):
292
- with pytest.raises(HTTPError):
293
- api.upload_replay(io.BytesIO(b"dummy_replay_data"), raise_on_duplicate=True)
294
-
295
- def test_create_group_omits_parent_when_none(self):
296
- api = BallchasingApi("dummy_key", do_initial_ping=False)
297
- ok_resp = make_mock_response(201, json_data={"id": "grp1", "name": "Top Level"})
298
-
299
- with patch.object(api._session, "request", return_value=ok_resp) as mock_req:
300
- res = api.create_group(name="Top Level", player_identification="by-id", team_identification="by-distinct-players")
301
- assert res["id"] == "grp1"
302
- assert mock_req.call_count == 1
303
- payload = mock_req.call_args[1]["json"]
304
- assert "parent" not in payload
305
- assert payload == {
306
- "name": "Top Level",
307
- "player_identification": "by-id",
308
- "team_identification": "by-distinct-players"
309
- }
310
-
311
- def test_create_group_includes_parent_when_provided(self):
312
- api = BallchasingApi("dummy_key", do_initial_ping=False)
313
- ok_resp = make_mock_response(201, json_data={"id": "grp2", "name": "Child Group"})
314
-
315
- with patch.object(api._session, "request", return_value=ok_resp) as mock_req:
316
- api.create_group(name="Child Group", player_identification="by-id", team_identification="by-distinct-players", parent="parent-grp")
317
- payload = mock_req.call_args[1]["json"]
318
- assert payload["parent"] == "parent-grp"
319
-
320
- def test_patch_replay_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_replay("rep-123", title="New Title", visibility="private", group="")
326
- payload = mock_req.call_args[1]["json"]
327
- assert payload == {"title": "New Title", "visibility": "private", "group": ""}
328
-
329
- def test_patch_group_explicit_kwargs(self):
330
- api = BallchasingApi("dummy_key", do_initial_ping=False)
331
- ok_resp = make_mock_response(204)
332
-
333
- with patch.object(api._session, "request", return_value=ok_resp) as mock_req:
334
- api.patch_group("grp-123", player_identification="by-name", team_identification="by-player-clusters", parent="new-parent", shared=True)
335
- payload = mock_req.call_args[1]["json"]
336
- assert payload == {
337
- "player_identification": "by-name",
338
- "team_identification": "by-player-clusters",
339
- "parent": "new-parent",
340
- "shared": True
341
- }
342
-
343
- def test_get_groups_url_no_trailing_slash(self):
344
- api = BallchasingApi("dummy_key", do_initial_ping=False)
345
- ok_resp = make_mock_response(200, json_data={"list": []})
346
-
347
- with patch.object(api._session, "request", return_value=ok_resp) as mock_req:
348
- list(api.get_groups(count=10, disable_prefetch=True))
349
- called_url = mock_req.call_args[1]["url"]
350
- assert called_url == f"{api.base_url}/groups"
351
-
352
- def test_download_replay_supports_pathlib(self, tmp_path):
353
- api = BallchasingApi("dummy_key", do_initial_ping=False)
354
- ok_resp = make_mock_response(200, content=b"PK\x03\x04fake_replay_binary")
355
-
356
- with patch.object(api._session, "request", return_value=ok_resp):
357
- dest = api.download_replay("rep-123", tmp_path)
358
- assert dest == tmp_path / "rep-123.replay"
359
- assert dest.read_bytes() == b"PK\x03\x04fake_replay_binary"
360
-
361
-
362
- class TestRateLimitingAndTracker:
363
- def test_initial_state_not_rate_limited(self):
364
- api = BallchasingApi("dummy_key", do_initial_ping=False)
365
- assert api.is_rate_limited is False
366
- assert api.last_rate_limited_at is None
367
- stats = api.rate_limit_stats
368
- assert stats["is_rate_limited"] is False
369
- assert stats["last_rate_limited_at"] is None
370
- assert stats["category_counts"] == {}
371
-
372
- def test_category_resolution(self):
373
- assert resolve_category("/replays") == RateLimitCategory.LIST
374
- assert resolve_category("https://ballchasing.com/api/groups") == RateLimitCategory.LIST
375
- assert resolve_category("/replays/123/file") == RateLimitCategory.DOWNLOAD
376
- assert resolve_category("/replays/abc-123") == RateLimitCategory.CORE
377
- assert resolve_category("/groups/grp-456") == RateLimitCategory.CORE
378
- assert resolve_category("/v2/upload") == RateLimitCategory.CORE
379
- assert resolve_category("/maps") == RateLimitCategory.CORE
380
- assert resolve_category("/") == RateLimitCategory.PING
381
-
382
- def test_record_429_updates_tracker_and_stats(self):
383
- api = BallchasingApi("dummy_key", do_initial_ping=False)
384
- rl_resp = make_mock_response(status_code=429, headers={"Retry-After": "5"})
385
- ok_resp = make_mock_response(status_code=200, json_data={"list": []})
386
-
387
- with patch.object(api._session, "request", side_effect=[rl_resp, ok_resp]), \
388
- patch("time.sleep"):
389
- api._request("/replays", "GET")
390
-
391
- assert api.last_rate_limited_at is not None
392
- assert time.time() - api.last_rate_limited_at < 5.0
393
- stats = api.rate_limit_stats
394
- assert stats["category_counts"].get("list") == 1
395
- assert "list" in stats["last_per_category"]
396
-
397
- def test_category_sleep_times(self):
398
- limiter = RateLimiter(patron_type_getter=lambda: "regular")
399
- assert limiter.get_category_sleep_time(RateLimitCategory.LIST) == 3600 / 500 # 7.2s
400
- assert limiter.get_category_sleep_time(RateLimitCategory.CORE) == 3600 / 1000 # 3.6s
401
- assert limiter.get_category_sleep_time(RateLimitCategory.DOWNLOAD) == 3600 / 200 # 18.0s
402
-
403
- gold_limiter = RateLimiter(patron_type_getter=lambda: "gold")
404
- assert gold_limiter.get_category_sleep_time(RateLimitCategory.LIST) == 3600 / 1000 # 3.6s
405
- assert gold_limiter.get_category_sleep_time(RateLimitCategory.CORE) == 3600 / 2000 # 1.8s
406
- assert gold_limiter.get_category_sleep_time(RateLimitCategory.DOWNLOAD) == 3600 / 400 # 9.0s
407
-
408
- def test_global_tracker_blocks_concurrent_requests(self):
409
- # Simulate instance being put into cooldown
410
- api = BallchasingApi("dummy_key", do_initial_ping=False)
411
- api.rate_limiter.record_429(RateLimitCategory.CORE, retry_after=5.0)
412
-
413
- assert api.is_rate_limited is True
414
- # A subsequent call to before_request should sleep for the remaining cooldown
415
- with patch("time.sleep") as mock_sleep:
416
- api.rate_limiter.before_request(RateLimitCategory.LIST)
417
- assert mock_sleep.call_count == 1
418
- slept = mock_sleep.call_args[0][0]
419
- assert 0.0 < slept <= 5.0
420
-
421
- def test_proactive_mode_enforces_burst_rate(self):
422
- api = BallchasingApi("dummy_key", do_initial_ping=False, proactive_rate_limit=True)
423
- # On proactive mode, 2 calls in immediate succession will sleep for min_interval
424
- with patch("time.sleep") as mock_sleep:
425
- api.rate_limiter.before_request(RateLimitCategory.LIST)
426
- # First call has no elapsed constraint
427
- assert mock_sleep.call_count == 0
428
- # Immediate second call should sleep
429
- api.rate_limiter.before_request(RateLimitCategory.LIST)
430
- assert mock_sleep.call_count == 1
431
- slept = mock_sleep.call_args[0][0]
432
- assert 0.4 <= slept <= 0.6 # 1 / 2.0s = 0.5s interval
433
-
434
- def test_rate_limited_decorator_attaches_to_api_methods(self):
435
- api = BallchasingApi("dummy_key", do_initial_ping=False)
436
- assert getattr(api.get_replay, "rate_limit_category", None) == RateLimitCategory.CORE
437
- assert getattr(api.get_replays, "rate_limit_category", None) == RateLimitCategory.LIST
438
- assert getattr(api.download_replay, "rate_limit_category", None) == RateLimitCategory.DOWNLOAD
439
- assert getattr(api.ping, "rate_limit_category", None) == RateLimitCategory.PING