返回 last30days-skill
test_reddit_keyless_backoff.py
根目录 / tests / test_reddit_keyless_backoff.py
1 """Tests for the shared keyless-Reddit throttle (U4) and 429 in-lane retry."""
2
3 import os
4 from unittest import mock
5
6 from lib import http, reddit_listing, render, schema
7
8
9 class TestRateLimiter:
10 def test_burst_does_not_sleep(self):
11 # A full bucket lets `burst` calls through immediately.
12 limiter = http.RateLimiter(rate_per_sec=5.0, burst=3)
13 with mock.patch.object(http.time, "monotonic", return_value=100.0), \
14 mock.patch.object(http.time, "sleep") as slept:
15 limiter.acquire()
16 limiter.acquire()
17 limiter.acquire()
18 slept.assert_not_called()
19
20 def test_sleeps_when_bucket_empty(self):
21 # burst=1: first call passes, second (same instant) must wait ~1/rate.
22 limiter = http.RateLimiter(rate_per_sec=2.0, burst=1)
23 times = iter([100.0, 100.0, 100.0, 100.5])
24 with mock.patch.object(http.time, "monotonic", side_effect=lambda: next(times)), \
25 mock.patch.object(http.time, "sleep") as slept:
26 limiter.acquire() # consumes the one token
27 limiter.acquire() # bucket empty -> sleep, then refilled token consumed
28 slept.assert_called()
29 waited = slept.call_args.args[0]
30 assert abs(waited - 0.5) < 1e-6 # (1 token deficit) / 2 per sec
31
32 def test_refill_over_time_avoids_sleep(self):
33 limiter = http.RateLimiter(rate_per_sec=2.0, burst=1)
34 # Second call 1s later: bucket refilled (2/s * 1s capped at burst=1) -> no sleep.
35 times = iter([100.0, 101.0])
36 with mock.patch.object(http.time, "monotonic", side_effect=lambda: next(times)), \
37 mock.patch.object(http.time, "sleep") as slept:
38 limiter.acquire()
39 limiter.acquire()
40 slept.assert_not_called()
41
42
43 class TestRedditKeylessGetText:
44 def test_acquires_limiter_then_delegates(self):
45 calls = mock.Mock()
46 with mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire") as acq, \
47 mock.patch.object(http, "get_text", return_value="body") as gt:
48 calls.attach_mock(acq, "acquire")
49 calls.attach_mock(gt, "get_text")
50 out = http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=x", accept="text/html")
51 assert out == "body"
52 assert calls.mock_calls == [
53 mock.call.acquire(),
54 mock.call.get_text(
55 "https://www.reddit.com/svc/shreddit/search/?q=x",
56 timeout=http.DEFAULT_TIMEOUT, retries=2, accept="text/html", headers=None,
57 ),
58 ]
59
60
61 class TestRedditKeylessRateKnob:
62 def test_default_rate_is_one_per_sec_small_burst(self):
63 limiter = http.make_reddit_keyless_limiter(environ={})
64 assert limiter.rate == 1.0
65 assert limiter.capacity == 2
66
67 def test_env_override(self):
68 limiter = http.make_reddit_keyless_limiter(
69 environ={http.REDDIT_KEYLESS_RATE_ENV: "0.25"}
70 )
71 assert limiter.rate == 0.25
72 assert limiter.capacity == 2
73
74 def test_invalid_and_nonpositive_fall_back_to_default(self):
75 for raw in ("fast", "", "-1", "0", "nan", "inf"):
76 limiter = http.make_reddit_keyless_limiter(
77 environ={http.REDDIT_KEYLESS_RATE_ENV: raw}
78 )
79 assert limiter.rate == http.DEFAULT_REDDIT_KEYLESS_RATE, raw
80
81 def test_process_env_syncs_onto_shared_limiter(self, monkeypatch):
82 monkeypatch.setattr(http.REDDIT_KEYLESS_LIMITER, "rate", 1.0)
83 monkeypatch.setenv(http.REDDIT_KEYLESS_RATE_ENV, "0.5")
84 with mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \
85 mock.patch.object(http, "get_text", return_value="ok"):
86 http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=x")
87 assert http.REDDIT_KEYLESS_LIMITER.rate == 0.5
88
89 def test_env_file_value_is_exported_for_limiter(self, tmp_path, monkeypatch):
90 from lib import env
91
92 config_file = tmp_path / ".env"
93 config_file.write_text(f"{http.REDDIT_KEYLESS_RATE_ENV}=0.25\n", encoding="utf-8")
94 config_file.chmod(0o600)
95 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
96 monkeypatch.setattr(env, "CONFIG_FILE", config_file)
97 monkeypatch.setenv("LAST30DAYS_CONFIG_DIR", str(tmp_path))
98 monkeypatch.delenv(http.REDDIT_KEYLESS_RATE_ENV, raising=False)
99 monkeypatch.chdir(tmp_path)
100 with mock.patch.object(env, "_load_keychain", return_value={}), \
101 mock.patch.object(env, "_load_pass", return_value={}):
102 config = env.get_config()
103 assert config[http.REDDIT_KEYLESS_RATE_ENV] == "0.25"
104 assert http.parse_reddit_keyless_rate(
105 config[http.REDDIT_KEYLESS_RATE_ENV]
106 ) == 0.25
107 assert os.environ.get(http.REDDIT_KEYLESS_RATE_ENV) == "0.25"
108
109
110 def _record_status(code: int, reason: str) -> None:
111 http._record_failure(http.HTTPError(f"HTTP {code}: {reason}", code))
112
113
114 class TestRedditKeyless429Retry:
115 def test_429_then_200_recovers_via_single_retry(self):
116 bodies = [None, "<html>ok</html>"]
117
118 def fake_get(*_args, **_kwargs):
119 val = bodies.pop(0)
120 if val is None:
121 _record_status(429, "Too Many Requests")
122 return val
123
124 with mock.patch.object(http, "get_text", side_effect=fake_get), \
125 mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire") as acq, \
126 mock.patch.object(http.time, "sleep") as slept, \
127 mock.patch.object(http.random, "uniform", return_value=0.0):
128 text, err = http.reddit_keyless_get_text_retry_429(
129 "https://www.reddit.com/svc/shreddit/search/?q=x"
130 )
131 assert text.startswith("<html")
132 assert err is None
133 assert acq.call_count == 2
134 slept.assert_called_once()
135 assert bodies == []
136
137 def test_429_then_429_records_failure_and_stops(self):
138 def fake_get(*_args, **_kwargs):
139 _record_status(429, "Too Many Requests")
140 return None
141
142 with mock.patch.object(http, "get_text", side_effect=fake_get) as gt, \
143 mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \
144 mock.patch.object(http.time, "sleep"), \
145 mock.patch.object(http.random, "uniform", return_value=0.0), \
146 http.capture_failures() as failures:
147 text, err = http.reddit_keyless_get_text_retry_429(
148 "https://www.reddit.com/svc/shreddit/search/?q=x"
149 )
150 assert text is None
151 assert err is not None and "429" in err
152 assert gt.call_count == 2
153 assert any(f.status_code == 429 for f in failures)
154
155 def test_non_429_miss_is_not_retried(self):
156 def fake_get(*_args, **_kwargs):
157 _record_status(403, "Forbidden")
158 return None
159
160 with mock.patch.object(http, "get_text", side_effect=fake_get) as gt, \
161 mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \
162 mock.patch.object(http.time, "sleep") as slept, \
163 http.capture_failures() as failures:
164 text, err = http.reddit_keyless_get_text_retry_429(
165 "https://www.reddit.com/svc/shreddit/search/?q=x"
166 )
167 assert text is None
168 assert "403" in (err or "")
169 assert gt.call_count == 1
170 slept.assert_not_called()
171 assert any(f.status_code == 403 for f in failures)
172
173 def test_listing_fetch_recovers_after_one_429(self):
174 from pathlib import Path
175
176 html = (
177 Path(__file__).resolve().parent.parent
178 / "fixtures"
179 / "reddit_listing_cards_sample.html"
180 ).read_text(encoding="utf-8")
181 bodies = [None, html]
182
183 def fake_get(*_args, **_kwargs):
184 val = bodies.pop(0)
185 if val is None:
186 _record_status(429, "Too Many Requests")
187 return val
188
189 with mock.patch.object(http, "get_text", side_effect=fake_get), \
190 mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \
191 mock.patch.object(http.time, "sleep"):
192 items, error = reddit_listing._fetch_one_with_status(
193 "technology", "hot", "netherlands"
194 )
195 assert error is None
196 assert items
197 assert bodies == []
198
199 def test_listing_fetch_records_double_429(self):
200 def fake_get(*_args, **_kwargs):
201 _record_status(429, "Too Many Requests")
202 return None
203
204 with mock.patch.object(http, "get_text", side_effect=fake_get) as gt, \
205 mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \
206 mock.patch.object(http.time, "sleep"), \
207 http.capture_failures() as failures:
208 items, error = reddit_listing._fetch_one_with_status(
209 "technology", "hot", "x"
210 )
211 assert items == []
212 assert error is not None and "429" in error
213 assert gt.call_count == 2
214 assert any(f.status_code == 429 for f in failures)
215
216
217 class TestPartialOutcomeWording:
218 def test_rate_limited_partial_does_not_read_as_cutoff(self):
219 outcome = schema.SourceOutcome(
220 source="reddit",
221 state=schema.PARTIAL,
222 items_returned=8,
223 detail="HTTP 429: Too Many Requests",
224 )
225 text = render._format_outcome(outcome)
226 assert "partial after" not in text
227 assert "8 items returned" in text
228 assert "some requests rate-limited" in text
229 assert "HTTP 429" in text
230
231 def test_non_rate_limit_partial_keeps_count_without_429_claim(self):
232 outcome = schema.SourceOutcome(
233 source="instagram",
234 state=schema.PARTIAL,
235 items_returned=1,
236 detail="HTTP 400: Bad Request",
237 )
238 text = render._format_outcome(outcome)
239 assert "partial after" not in text
240 assert "1 item returned" in text
241 assert "rate-limited" not in text
242 assert "HTTP 400" in text
243
243 lines PYTHON