返回 last30days-skill
test_brightdata.py
根目录 / tests / test_brightdata.py
1 """Tests for the Bright Data CLI adapter (U1).
2
3 Covers the activation gate (PATH + presence-only credential probe), the
4 never-raise error envelope across every failure mode, and the verbatim
5 passthrough of the CLI's own auth/credit warnings.
6
7 No test in this file spawns a real subprocess or touches the network.
8 """
9
10 from __future__ import annotations
11
12 import json
13 import sys
14 from pathlib import Path
15
16 import pytest
17
18 sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts"))
19
20 from lib import brightdata, subproc # noqa: E402
21
22
23 class _Result:
24 """Stand-in for subproc.SubprocResult."""
25
26 def __init__(self, returncode=0, stdout="", stderr=""):
27 self.returncode = returncode
28 self.stdout = stdout
29 self.stderr = stderr
30
31
32 # One real search record, trimmed. Field names verified against a live
33 # amazon_product_search payload on 2026-08-13.
34 SEARCH_RECORD = {
35 "asin": "B0DWD47BW7",
36 "url": "https://www.amazon.com/dp/B0DWD47BW7",
37 "name": "Chill Max Leak-Proof XL Bento-Style Lunch Box | Ice Pack Included",
38 "brand": "Bentgo",
39 "sponsored": "false",
40 "rating": 4.4,
41 "num_ratings": 459,
42 "final_price": 39.99,
43 "currency": "USD",
44 }
45
46
47 # ---------------------------------------------------------------- gate
48
49
50 def test_gate_false_when_binary_missing(monkeypatch):
51 monkeypatch.setattr(brightdata.shutil, "which", lambda _: None)
52 assert brightdata.is_installed() is False
53 assert brightdata.is_available({}) is False
54
55
56 def test_gate_reports_unauthenticated_when_no_credential_signal(monkeypatch, tmp_path):
57 monkeypatch.delenv("BRIGHTDATA_API_KEY", raising=False)
58 monkeypatch.setattr(brightdata.shutil, "which", lambda _: "/usr/local/bin/brightdata")
59 monkeypatch.setattr(brightdata, "_config_dir", lambda: tmp_path / "absent")
60 status = brightdata.gate_status({})
61 assert status["brightdata_installed"] is True
62 assert status["brightdata_authenticated"] is False
63 assert brightdata.is_available({}) is False
64
65
66 def test_api_key_alone_satisfies_the_credential_probe(monkeypatch, tmp_path):
67 monkeypatch.setattr(brightdata.shutil, "which", lambda _: "/usr/local/bin/brightdata")
68 monkeypatch.setattr(brightdata, "_config_dir", lambda: tmp_path / "absent")
69 assert brightdata.is_available({"BRIGHTDATA_API_KEY": "dummy-key-not-real"}) is True
70
71
72 def test_credentials_file_satisfies_the_probe_without_being_read(monkeypatch, tmp_path):
73 cfg = tmp_path / "brightdata-cli"
74 cfg.mkdir()
75 creds = cfg / "credentials.json"
76 creds.write_text('{"token": "dummy-not-real"}')
77 creds.chmod(0o600)
78 monkeypatch.setattr(brightdata.shutil, "which", lambda _: "/usr/local/bin/brightdata")
79 monkeypatch.setattr(brightdata, "_config_dir", lambda: cfg)
80
81 def _explode(*a, **k): # pragma: no cover - must never run
82 raise AssertionError("credential contents must never be read")
83
84 monkeypatch.setattr(Path, "read_text", _explode)
85 assert brightdata.has_credentials({}) is True
86
87
88 def test_gate_does_not_spawn_a_subprocess(monkeypatch, tmp_path):
89 monkeypatch.setattr(brightdata.shutil, "which", lambda _: None)
90
91 def _explode(*a, **k): # pragma: no cover - must never run
92 raise AssertionError("gate must stay offline")
93
94 monkeypatch.setattr(subproc, "run_with_timeout", _explode)
95 brightdata.gate_status({})
96 assert brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30)["records"] == []
97
98
99 # ------------------------------------------------------------ envelope
100
101
102 def _installed(monkeypatch):
103 monkeypatch.setattr(brightdata.shutil, "which", lambda _: "/usr/local/bin/brightdata")
104
105
106 def test_happy_path_parses_a_bare_json_array(monkeypatch):
107 """Live payloads are a top-level list, not a {"results": ...} envelope."""
108 _installed(monkeypatch)
109 monkeypatch.setattr(
110 subproc, "run_with_timeout",
111 lambda *a, **k: _Result(stdout=json.dumps([SEARCH_RECORD, SEARCH_RECORD])),
112 )
113 out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=60)
114 assert "error" not in out
115 assert len(out["records"]) == 2
116 assert out["records"][0]["asin"] == "B0DWD47BW7"
117
118
119 @pytest.mark.parametrize("wrapper", ["records", "results", "data"])
120 def test_dict_envelopes_are_tolerated_for_cli_churn(monkeypatch, wrapper):
121 _installed(monkeypatch)
122 monkeypatch.setattr(
123 subproc, "run_with_timeout",
124 lambda *a, **k: _Result(stdout=json.dumps({wrapper: [SEARCH_RECORD]})),
125 )
126 assert len(brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30)["records"]) == 1
127
128
129 def test_auth_401_surfaces_the_cli_error_without_raising(monkeypatch):
130 _installed(monkeypatch)
131 stderr = "Triggering pipeline collection...\nError: 401 Unauthorized - run `brightdata login`"
132 monkeypatch.setattr(
133 subproc, "run_with_timeout", lambda *a, **k: _Result(returncode=1, stderr=stderr)
134 )
135 out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30)
136 assert out["records"] == []
137 assert "401" in out["error"]
138
139
140 def test_error_uses_the_last_stderr_line_not_the_polling_narration(monkeypatch):
141 """The CLI narrates polling on stderr; the failure is the final line."""
142 _installed(monkeypatch)
143 stderr = (
144 "Snapshot sd_x started. If you stop waiting, get the data later with: "
145 "brightdata pipelines results sd_x\n"
146 "Waiting for snapshot sd_x: running, 30s\n"
147 "✗ results failed. Error: snapshot failed"
148 )
149 monkeypatch.setattr(
150 subproc, "run_with_timeout", lambda *a, **k: _Result(returncode=1, stderr=stderr)
151 )
152 assert brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30)["error"] == "✗ results failed. Error: snapshot failed"
153
154
155 def test_subprocess_timeout_returns_empty_records_and_error(monkeypatch):
156 _installed(monkeypatch)
157
158 def _timeout(*a, **k):
159 raise subproc.SubprocTimeout("Command brightdata timed out after 180s")
160
161 monkeypatch.setattr(subproc, "run_with_timeout", _timeout)
162 out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=180)
163 assert out["records"] == []
164 assert "timed out" in out["error"]
165
166
167 def test_malformed_json_returns_empty_records_and_error(monkeypatch):
168 _installed(monkeypatch)
169 monkeypatch.setattr(subproc, "run_with_timeout", lambda *a, **k: _Result(stdout="not json{"))
170 out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30)
171 assert out["records"] == []
172 assert "json decode" in out["error"]
173
174
175 def test_empty_stdout_is_not_an_error(monkeypatch):
176 _installed(monkeypatch)
177 monkeypatch.setattr(subproc, "run_with_timeout", lambda *a, **k: _Result(stdout=" \n"))
178 out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30)
179 assert out["records"] == []
180 assert "error" not in out
181
182
183 def test_spawn_failures_never_raise(monkeypatch):
184 _installed(monkeypatch)
185 for exc in (FileNotFoundError("no binary"), OSError("spawn failed")):
186 def _raise(*a, __e=exc, **k):
187 raise __e
188
189 monkeypatch.setattr(subproc, "run_with_timeout", _raise)
190 out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30)
191 assert out["records"] == [] and out["error"]
192
193
194 # ------------------------------------------------------------ arguments
195
196
197 def test_cli_timeout_sits_below_the_subprocess_timeout(monkeypatch):
198 """The CLI must fail cleanly on its own before we SIGTERM it."""
199 _installed(monkeypatch)
200 seen = {}
201 monkeypatch.setattr(
202 subproc, "run_with_timeout",
203 lambda cmd, **k: seen.update(cmd=cmd, timeout=k["timeout"]) or _Result(stdout="[]"),
204 )
205 brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=180)
206 cli_timeout = int(seen["cmd"][seen["cmd"].index("--timeout") + 1])
207 assert cli_timeout < seen["timeout"] == 180
208
209
210 def test_record_is_sent_as_typed_input_json(monkeypatch):
211 """Numbers must stay JSON numbers: the API rejects "50" for a number field."""
212 _installed(monkeypatch)
213 seen = {}
214 monkeypatch.setattr(
215 subproc, "run_with_timeout",
216 lambda cmd, **k: seen.update(cmd=cmd) or _Result(stdout="[]"),
217 )
218 brightdata.run_pipeline("gd_x", {"url": "https://a/dp/X", "max_reviews": 50}, timeout=60)
219 cmd = seen["cmd"]
220 assert cmd[:5] == ["/usr/local/bin/brightdata", "pipelines", "run", "gd_x", "collect_by_url"]
221 assert json.loads(cmd[cmd.index("--input") + 1]) == [{"url": "https://a/dp/X", "max_reviews": 50}]
222 assert "--json" in cmd
223
224
225 def test_api_key_travels_in_the_environment_never_in_argv(monkeypatch):
226 """argv is not a secret channel: /proc/<pid>/cmdline is world-readable."""
227 _installed(monkeypatch)
228 seen = {}
229 monkeypatch.setattr(
230 subproc, "run_with_timeout",
231 lambda cmd, **k: seen.update(cmd=cmd, env=k.get("env")) or _Result(stdout="[]"),
232 )
233 monkeypatch.delenv("BRIGHTDATA_API_KEY", raising=False)
234 brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30, config={"BRIGHTDATA_API_KEY": "dummy-key"})
235 assert "-k" not in seen["cmd"]
236 assert "dummy-key" not in " ".join(seen["cmd"])
237 assert seen["env"]["BRIGHTDATA_API_KEY"] == "dummy-key"
238
239
240 def test_no_explicit_key_still_filters_the_parent_env(monkeypatch):
241 _installed(monkeypatch)
242 monkeypatch.setenv("OPENAI_API_KEY", "dummy-unrelated-secret")
243 monkeypatch.setenv("BRIGHTDATA_API_KEY", "dummy-brightdata-key")
244 seen = {}
245 monkeypatch.setattr(
246 subproc, "run_with_timeout",
247 lambda cmd, **k: seen.update(env=k.get("env")) or _Result(stdout="[]"),
248 )
249 brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30, config={})
250 assert isinstance(seen["env"], dict)
251 assert "OPENAI_API_KEY" not in seen["env"]
252 assert seen["env"]["BRIGHTDATA_API_KEY"] == "dummy-brightdata-key"
253
254
255 def test_option_shaped_values_stay_inside_the_input_json(monkeypatch):
256 """A keyword beginning with '-' must not reach argv as an option."""
257 _installed(monkeypatch)
258 seen = {}
259 monkeypatch.setattr(
260 subproc, "run_with_timeout",
261 lambda cmd, **k: seen.update(cmd=cmd) or _Result(stdout="[]"),
262 )
263 brightdata.run_pipeline("gd_x", {"keyword": "--help"}, timeout=30)
264 assert "--help" not in seen["cmd"]
265
266
267 @pytest.mark.parametrize("stderr", [
268 "error: unknown option '--input'\n(Did you mean --output?)",
269 'Error: Unknown pipeline type "run".',
270 ])
271 def test_pre_0_4_cli_error_says_to_upgrade(monkeypatch, stderr):
272 _installed(monkeypatch)
273 monkeypatch.setattr(
274 subproc, "run_with_timeout", lambda *a, **k: _Result(returncode=1, stderr=stderr)
275 )
276 out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30)
277 assert "0.4.0" in out["error"] and "@brightdata/cli@latest" in out["error"]
278
279
280 def test_the_key_is_scrubbed_out_of_surfaced_stderr(monkeypatch):
281 """Auth failures are exactly where a CLI echoes the rejected key back."""
282 _installed(monkeypatch)
283 logged = []
284 monkeypatch.setattr(brightdata.log, "source_log", lambda n, m, **k: logged.append(m))
285 monkeypatch.setattr(
286 subproc, "run_with_timeout",
287 lambda *a, **k: _Result(returncode=1, stderr="Error: 401 for key dummy-key"),
288 )
289 out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30, config={"BRIGHTDATA_API_KEY": "dummy-key"})
290 assert "dummy-key" not in out["error"]
291 assert not any("dummy-key" in m for m in logged)
292
293
294 # ------------------------------------------------------------- warnings
295
296
297 def test_credit_and_auth_warnings_pass_through_verbatim(monkeypatch):
298 _installed(monkeypatch)
299 warned = []
300 monkeypatch.setattr(brightdata.log, "source_log", lambda name, msg, **k: warned.append(msg))
301 stderr = (
302 "Snapshot sd_x started. If you stop waiting, get the data later with: "
303 "brightdata pipelines results sd_x\n"
304 "Waiting for snapshot sd_x: running, 30s\n"
305 "Warning: only 12 credits remaining on your free tier\n"
306 )
307 monkeypatch.setattr(
308 subproc, "run_with_timeout", lambda *a, **k: _Result(stdout="[]", stderr=stderr)
309 )
310 brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30)
311 assert "Warning: only 12 credits remaining on your free tier" in warned
312 # Routine polling narration stays out of the log.
313 assert not any("Waiting for snapshot" in m for m in warned)
314
315
316 def test_source_log_is_called_with_tty_only_false(monkeypatch):
317 """Repo rule: tty_only=True silently drops output in non-TTY hosts."""
318 _installed(monkeypatch)
319 kwargs = {}
320 monkeypatch.setattr(
321 brightdata.log, "source_log", lambda name, msg, **k: kwargs.update(k)
322 )
323 monkeypatch.setattr(
324 subproc, "run_with_timeout", lambda *a, **k: _Result(returncode=1, stderr="Error: 401")
325 )
326 brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30)
327 assert kwargs.get("tty_only") is False
328
328 lines PYTHON