| 1 | """Share-price window from yahoo-finance-pp-cli: ticker choice, numbers, footer. |
| 2 | |
| 3 | No test shells out. ``FakeCli`` stands in for ``subproc.run_with_timeout`` and |
| 4 | answers ``chart`` and ``autocomplete`` in the shapes the real binary returned |
| 5 | for NVDA, 7203.T, ^GSPC, Tesla and Stripe. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import json |
| 11 | import threading |
| 12 | from datetime import datetime, timezone |
| 13 | from types import SimpleNamespace |
| 14 | from unittest.mock import ANY |
| 15 | |
| 16 | import pytest |
| 17 | |
| 18 | import last30days as cli |
| 19 | from lib import company_resolve, health, http, render, schema, yahoo_finance |
| 20 | from tests.test_company_resolve import FakeWikidata |
| 21 | from tests.test_render_v3 import sample_report |
| 22 | |
| 23 | NVDA_CLOSES = [ |
| 24 | ("2026-10-12", 226.32), ("2026-10-13", 222.00), ("2026-10-20", 210.00), |
| 25 | ("2026-10-27", 200.00), ("2026-11-04", 190.00), ("2026-11-05", 172.33), |
| 26 | ("2026-11-06", 175.00), ("2026-11-09", 170.00), ("2026-11-10", 167.68), |
| 27 | ] |
| 28 | SP500_CLOSES = [("2026-10-12", 7807.24), ("2026-10-26", 7650.00), ("2026-11-10", 7500.91)] |
| 29 | RISING_CLOSES = [("2026-10-12", 100.0), ("2026-10-13", 104.0), ("2026-11-10", 110.0)] |
| 30 | TOYOTA_CLOSES = [("2026-10-12", 2480.0), ("2026-10-13", 2500.0), ("2026-11-10", 2610.0)] |
| 31 | AMD_CLOSES = [("2026-10-12", 200.0), ("2026-10-30", 190.0), ("2026-11-10", 183.8)] |
| 32 | |
| 33 | NVDA_LINE = ( |
| 34 | "📈 Yahoo Finance: NVDA -25.9% in the L30 │ $226.32 → $167.68 │ " |
| 35 | "S&P 500 -3.9% │ worst day Nov 5 -9.3%" |
| 36 | ) |
| 37 | NVIDIA = {"company": "Nvidia", "ticker": "NVDA", "exchange": "Nasdaq"} |
| 38 | TESLA = {"company": "Tesla", "ticker_candidates": ["TSLA", "TL0", "0R0X"]} |
| 39 | |
| 40 | |
| 41 | def _chart(symbol, closes, *, currency="USD", gmtoffset=-18000, hour=14, name=None, instrument="EQUITY"): |
| 42 | """A chart response; each bar is stamped at the exchange's opening hour.""" |
| 43 | stamps = [ |
| 44 | int(datetime.fromisoformat(f"{day}T{hour:02d}:30:00+00:00").timestamp()) |
| 45 | for day, _close in closes |
| 46 | ] |
| 47 | names = {"longName": name, "shortName": name} if name else {} |
| 48 | return { |
| 49 | "meta": {"source": "live"}, |
| 50 | "results": {"chart": {"result": [{ |
| 51 | "meta": { |
| 52 | "currency": currency, "symbol": symbol, "gmtoffset": gmtoffset, |
| 53 | "instrumentType": instrument, "fullExchangeName": "NasdaqGS", **names, |
| 54 | }, |
| 55 | "timestamp": stamps, |
| 56 | "indicators": {"quote": [{"close": [close for _day, close in closes]}]}, |
| 57 | }]}}, |
| 58 | } |
| 59 | |
| 60 | |
| 61 | def _matches(*rows): |
| 62 | return {"meta": {"source": "live"}, "results": {"ResultSet": {"Result": [ |
| 63 | {"symbol": symbol, "name": symbol, "typeDisp": kind, "exchDisp": "-"} |
| 64 | for symbol, kind in rows |
| 65 | ]}}} |
| 66 | |
| 67 | |
| 68 | def _ok(data) -> SimpleNamespace: |
| 69 | return SimpleNamespace(returncode=0, stdout=json.dumps(data), stderr="") |
| 70 | |
| 71 | |
| 72 | def _failed(message: str, code: int = 3) -> SimpleNamespace: |
| 73 | return SimpleNamespace(returncode=code, stdout="", stderr=f"Error: {message}\n") |
| 74 | |
| 75 | |
| 76 | class FakeCli: |
| 77 | """Answers by symbol for ``chart`` and by query for ``autocomplete``.""" |
| 78 | |
| 79 | def __init__(self, charts=None, matches=None): |
| 80 | self.charts = charts or {} |
| 81 | self.matches = matches or {} |
| 82 | self.calls: list[list[str]] = [] |
| 83 | |
| 84 | def __call__(self, cmd, timeout): |
| 85 | self.calls.append(list(cmd)) |
| 86 | assert cmd[0] == yahoo_finance.CLI_BIN |
| 87 | assert "--json" in cmd and "--agent" not in cmd |
| 88 | if cmd[1] == "chart": |
| 89 | answer = self.charts[cmd[2]] |
| 90 | else: |
| 91 | assert cmd[1:3] == ["autocomplete", "--query"] |
| 92 | answer = self.matches[cmd[3]] |
| 93 | return answer if isinstance(answer, SimpleNamespace) else _ok(answer) |
| 94 | |
| 95 | def charted(self) -> list[str]: |
| 96 | return [cmd[2] for cmd in self.calls if cmd[1] == "chart"] |
| 97 | |
| 98 | |
| 99 | @pytest.fixture(autouse=True) |
| 100 | def _fresh_fetches(): |
| 101 | yahoo_finance.forget_fetches() |
| 102 | |
| 103 | |
| 104 | def _install(monkeypatch, *, available=True, **fake_kwargs) -> FakeCli: |
| 105 | fake = FakeCli(**fake_kwargs) |
| 106 | monkeypatch.setattr(yahoo_finance, "_is_available", lambda: available) |
| 107 | monkeypatch.setattr(yahoo_finance.subproc, "run_with_timeout", fake) |
| 108 | return fake |
| 109 | |
| 110 | |
| 111 | def _report(range_from="2026-10-11", range_to="2026-11-10") -> schema.Report: |
| 112 | report = sample_report() |
| 113 | report.range_from = range_from |
| 114 | report.range_to = range_to |
| 115 | return report |
| 116 | |
| 117 | |
| 118 | def _attach(monkeypatch, company, *, report=None, **install_kwargs): |
| 119 | fake = _install(monkeypatch, **install_kwargs) |
| 120 | report = report or _report() |
| 121 | yahoo_finance.attach_market_data(report, company) |
| 122 | return report, fake |
| 123 | |
| 124 | |
| 125 | def _footer(report: schema.Report) -> list[str]: |
| 126 | return [line for line in render._build_source_footer_lines(report) if "Yahoo Finance" in line] |
| 127 | |
| 128 | |
| 129 | NVDA_CHARTS = {"NVDA": _chart("NVDA", NVDA_CLOSES), "^GSPC": _chart("^GSPC", SP500_CLOSES)} |
| 130 | |
| 131 | |
| 132 | def test_falling_window_reads_as_one_footer_line(monkeypatch): |
| 133 | report, fake = _attach(monkeypatch, NVIDIA, charts=NVDA_CHARTS) |
| 134 | |
| 135 | assert _footer(report) == [NVDA_LINE] |
| 136 | assert fake.charted() == ["NVDA", "^GSPC"] |
| 137 | # The window is asked for by its edges, a day wide on each side. |
| 138 | nvda = fake.calls[0] |
| 139 | assert nvda[nvda.index("--interval") + 1] == "1d" |
| 140 | period1 = int(nvda[nvda.index("--period1") + 1]) |
| 141 | period2 = int(nvda[nvda.index("--period2") + 1]) |
| 142 | assert datetime.fromtimestamp(period1, timezone.utc).date().isoformat() == "2026-10-10" |
| 143 | assert datetime.fromtimestamp(period2, timezone.utc).date().isoformat() == "2026-11-12" |
| 144 | |
| 145 | |
| 146 | def test_footer_line_sits_directly_after_polymarket(monkeypatch): |
| 147 | report, _fake = _attach(monkeypatch, NVIDIA, charts=NVDA_CHARTS) |
| 148 | report.items_by_source["polymarket"] = [schema.SourceItem( |
| 149 | item_id="pm1", source="polymarket", title="Will Nvidia close above $200?", |
| 150 | body="", url="https://polymarket.com/event/nvda", |
| 151 | )] |
| 152 | |
| 153 | lines = render._build_source_footer_lines(report) |
| 154 | |
| 155 | polymarket = next(i for i, line in enumerate(lines) if line.startswith("📊 Polymarket")) |
| 156 | assert lines[polymarket + 1] == NVDA_LINE |
| 157 | |
| 158 | |
| 159 | def test_rising_window_names_the_best_day(monkeypatch): |
| 160 | report, _fake = _attach( |
| 161 | monkeypatch, {"company": "Riser", "ticker": "RISE", "exchange": "Nasdaq"}, |
| 162 | charts={"RISE": _chart("RISE", RISING_CLOSES), "^GSPC": _chart("^GSPC", SP500_CLOSES)}, |
| 163 | ) |
| 164 | |
| 165 | assert _footer(report) == [ |
| 166 | "📈 Yahoo Finance: RISE +10.0% in the L30 │ $100.00 → $110.00 │ " |
| 167 | "S&P 500 -3.9% │ best day Nov 10 +5.8%" |
| 168 | ] |
| 169 | |
| 170 | |
| 171 | def test_listing_outside_the_us_uses_its_currency_and_no_sp500(monkeypatch): |
| 172 | report, fake = _attach( |
| 173 | monkeypatch, |
| 174 | {"company": "Toyota", "ticker": "7203", "exchange": "Tokyo Stock Exchange"}, |
| 175 | matches={"Toyota": _matches(("TM", "Equity"), ("7203.T", "Equity"))}, |
| 176 | charts={"7203.T": _chart("7203.T", TOYOTA_CLOSES, currency="JPY", gmtoffset=32400, hour=0)}, |
| 177 | ) |
| 178 | |
| 179 | assert _footer(report) == [ |
| 180 | "📈 Yahoo Finance: 7203.T +5.2% in the L30 │ JPY 2,480 → JPY 2,610 │ best day Nov 10 +4.4%" |
| 181 | ] |
| 182 | assert fake.charted() == ["7203.T"] |
| 183 | |
| 184 | |
| 185 | def test_foreign_ticker_yahoo_cannot_confirm_gives_no_line(monkeypatch): |
| 186 | report, fake = _attach( |
| 187 | monkeypatch, |
| 188 | {"company": "Toyota", "ticker": "7203", "exchange": "Tokyo Stock Exchange"}, |
| 189 | matches={"Toyota": _matches(("TM", "Equity"), ("72035.T", "Equity"))}, |
| 190 | ) |
| 191 | |
| 192 | assert _footer(report) == [] |
| 193 | assert "yahoo_finance" not in report.artifacts |
| 194 | assert "yahoo_finance" not in report.source_status |
| 195 | assert fake.charted() == [] |
| 196 | |
| 197 | |
| 198 | def test_window_opening_on_a_weekend_starts_at_the_first_close(monkeypatch): |
| 199 | report, _fake = _attach( |
| 200 | monkeypatch, NVIDIA, report=_report(range_from="2026-10-10"), charts=NVDA_CHARTS, |
| 201 | ) |
| 202 | |
| 203 | window = report.artifacts["yahoo_finance"] |
| 204 | assert (window["start_date"], window["start_close"]) == ("2026-10-12", 226.32) |
| 205 | assert (window["end_date"], window["end_close"]) == ("2026-11-10", 167.68) |
| 206 | assert _footer(report) == [NVDA_LINE] |
| 207 | |
| 208 | |
| 209 | def test_bars_outside_the_window_are_left_out(monkeypatch): |
| 210 | wide = [("2026-10-09", 229.28), *NVDA_CLOSES, ("2026-11-11", 180.00)] |
| 211 | report, _fake = _attach( |
| 212 | monkeypatch, NVIDIA, |
| 213 | charts={"NVDA": _chart("NVDA", wide), "^GSPC": _chart("^GSPC", SP500_CLOSES)}, |
| 214 | ) |
| 215 | |
| 216 | assert _footer(report) == [NVDA_LINE] |
| 217 | |
| 218 | |
| 219 | def test_ticker_reached_through_a_person_names_the_company(monkeypatch): |
| 220 | report, _fake = _attach( |
| 221 | monkeypatch, {**NVIDIA, "company_via_person": True}, charts=NVDA_CHARTS, |
| 222 | ) |
| 223 | |
| 224 | assert _footer(report) == [NVDA_LINE.replace("NVDA -25.9%", "NVDA (Nvidia) -25.9%")] |
| 225 | |
| 226 | |
| 227 | @pytest.mark.parametrize( |
| 228 | "company", |
| 229 | [ |
| 230 | {}, |
| 231 | {"company": "Stripe", "company_site": "https://stripe.com/"}, |
| 232 | ], |
| 233 | ids=["no-company", "company-with-no-listing"], |
| 234 | ) |
| 235 | def test_no_ticker_means_no_line_no_artifact_and_no_cli_call(monkeypatch, company): |
| 236 | report, fake = _attach(monkeypatch, company) |
| 237 | |
| 238 | assert _footer(report) == [] |
| 239 | assert "yahoo_finance" not in report.artifacts |
| 240 | assert "yahoo_finance" not in report.source_status |
| 241 | assert fake.calls == [] |
| 242 | |
| 243 | |
| 244 | def test_candidate_is_used_when_yahoo_puts_it_first(monkeypatch): |
| 245 | report, fake = _attach( |
| 246 | monkeypatch, TESLA, |
| 247 | matches={"Tesla": _matches( |
| 248 | ("STSLA=F", "Futures"), ("TSLA", "Equity"), ("TL0.DE", "Equity"), |
| 249 | )}, |
| 250 | charts={"TSLA": _chart("TSLA", RISING_CLOSES), "^GSPC": _chart("^GSPC", SP500_CLOSES)}, |
| 251 | ) |
| 252 | |
| 253 | assert report.artifacts["yahoo_finance"]["symbol"] == "TSLA" |
| 254 | assert _footer(report)[0].startswith("📈 Yahoo Finance: TSLA +10.0% in the L30") |
| 255 | assert fake.calls[0] == [yahoo_finance.CLI_BIN, "autocomplete", "--query", "Tesla", "--json"] |
| 256 | |
| 257 | |
| 258 | def test_candidate_matches_before_the_exchange_suffix(monkeypatch): |
| 259 | report, _fake = _attach( |
| 260 | monkeypatch, {"company": "Tesla", "ticker_candidates": ["tl0"]}, |
| 261 | matches={"Tesla": _matches(("TL0.DE", "Equity"))}, |
| 262 | charts={"TL0.DE": _chart("TL0.DE", RISING_CLOSES, currency="EUR", gmtoffset=3600, hour=8)}, |
| 263 | ) |
| 264 | |
| 265 | assert report.artifacts["yahoo_finance"]["symbol"] == "TL0.DE" |
| 266 | |
| 267 | |
| 268 | @pytest.mark.parametrize( |
| 269 | "rows", |
| 270 | [ |
| 271 | # The first equity is another company; a later row that would match |
| 272 | # is not reached for. |
| 273 | [("TSLZ", "ETF"), ("RIVN", "Equity"), ("TSLA", "Equity")], |
| 274 | [("STRIZZX", "Fund"), ("0P0000X8PD.F", "Fund")], |
| 275 | [], |
| 276 | ], |
| 277 | ids=["first-equity-is-not-a-candidate", "only-funds", "no-matches"], |
| 278 | ) |
| 279 | def test_candidates_yahoo_does_not_confirm_give_no_line(monkeypatch, rows): |
| 280 | report, fake = _attach(monkeypatch, TESLA, matches={"Tesla": _matches(*rows)}) |
| 281 | |
| 282 | assert _footer(report) == [] |
| 283 | assert "yahoo_finance" not in report.artifacts |
| 284 | assert "yahoo_finance" not in report.source_status |
| 285 | assert fake.charted() == [] |
| 286 | |
| 287 | |
| 288 | @pytest.mark.parametrize( |
| 289 | "answer,state", |
| 290 | [ |
| 291 | (_failed("GET /v8/finance/chart/NVDA returned HTTP 500: upstream failure"), health.ERROR), |
| 292 | ( |
| 293 | _failed("GET /v8/finance/chart/NVDA returned HTTP 429: Too Many Requests", code=7), |
| 294 | health.RATE_LIMITED, |
| 295 | ), |
| 296 | (SimpleNamespace(returncode=0, stdout="", stderr=""), health.ERROR), |
| 297 | (_chart("NVDA", []), health.ERROR), |
| 298 | (_chart("NVDA", NVDA_CLOSES[:1]), health.ERROR), |
| 299 | (_chart("NVDA", [("2026-10-12", None), ("2026-10-13", 222.0)]), health.ERROR), |
| 300 | ], |
| 301 | ids=["cli-error", "http-429", "empty-output", "empty-bars", "one-bar", "one-usable-close"], |
| 302 | ) |
| 303 | def test_failed_fetch_is_a_degraded_source_and_no_line(monkeypatch, answer, state): |
| 304 | report, _fake = _attach(monkeypatch, NVIDIA, charts={"NVDA": answer}) |
| 305 | |
| 306 | assert _footer(report) == [] |
| 307 | assert "yahoo_finance" not in report.artifacts |
| 308 | outcome = report.source_status["yahoo_finance"] |
| 309 | assert outcome.state == state |
| 310 | assert outcome.items_returned == 0 |
| 311 | assert "NVDA" in outcome.detail |
| 312 | assert "Yahoo Finance" in "\n".join(render._render_source_outcome_note(report)) |
| 313 | |
| 314 | |
| 315 | def test_cli_that_cannot_start_is_a_degraded_source(monkeypatch): |
| 316 | def cannot_start(cmd, timeout): |
| 317 | raise OSError("exec format error") |
| 318 | |
| 319 | monkeypatch.setattr(yahoo_finance, "_is_available", lambda: True) |
| 320 | monkeypatch.setattr(yahoo_finance.subproc, "run_with_timeout", cannot_start) |
| 321 | report = _report() |
| 322 | |
| 323 | yahoo_finance.attach_market_data(report, NVIDIA) |
| 324 | |
| 325 | assert report.source_status["yahoo_finance"].state == health.ERROR |
| 326 | assert "yahoo_finance" not in report.artifacts |
| 327 | |
| 328 | |
| 329 | def test_sp500_failure_keeps_the_line_without_that_segment(monkeypatch): |
| 330 | report, _fake = _attach( |
| 331 | monkeypatch, NVIDIA, |
| 332 | charts={"NVDA": _chart("NVDA", NVDA_CLOSES), "^GSPC": _failed("HTTP 429: Too Many Requests")}, |
| 333 | ) |
| 334 | |
| 335 | assert _footer(report) == [ |
| 336 | "📈 Yahoo Finance: NVDA -25.9% in the L30 │ $226.32 → $167.68 │ worst day Nov 5 -9.3%" |
| 337 | ] |
| 338 | assert "yahoo_finance" not in report.source_status |
| 339 | |
| 340 | |
| 341 | def test_missing_binary_is_silent(monkeypatch, capsys): |
| 342 | report, fake = _attach(monkeypatch, NVIDIA, available=False) |
| 343 | |
| 344 | assert _footer(report) == [] |
| 345 | assert "yahoo_finance" not in report.artifacts |
| 346 | assert "yahoo_finance" not in report.source_status |
| 347 | assert fake.calls == [] |
| 348 | assert capsys.readouterr().err == "" |
| 349 | |
| 350 | |
| 351 | def test_item_totals_and_stats_are_unchanged_by_a_fetch(monkeypatch): |
| 352 | before = _report() |
| 353 | stats_before = render._render_stats(before) |
| 354 | coverage_before = render._render_source_coverage(before) |
| 355 | items_before = {source: list(items) for source, items in before.items_by_source.items()} |
| 356 | |
| 357 | report, _fake = _attach(monkeypatch, NVIDIA, report=before, charts=NVDA_CHARTS) |
| 358 | |
| 359 | assert "yahoo_finance" in report.artifacts |
| 360 | assert report.items_by_source == items_before |
| 361 | assert render._render_stats(report) == stats_before |
| 362 | assert render._render_source_coverage(report) == coverage_before |
| 363 | assert "yahoo_finance" not in report.source_status |
| 364 | |
| 365 | |
| 366 | def test_evidence_carries_market_data_and_no_presentation_commands(monkeypatch): |
| 367 | report, _fake = _attach( |
| 368 | monkeypatch, {**NVIDIA, "company_via_person": True}, charts=NVDA_CHARTS, |
| 369 | ) |
| 370 | |
| 371 | text = render.render_compact(report) |
| 372 | |
| 373 | start = text.index("## Market Data") |
| 374 | assert text.index("<!-- EVIDENCE FOR SYNTHESIS") < start < text.index("<!-- END EVIDENCE FOR SYNTHESIS -->") |
| 375 | block = text[start:text.index("\n## ", start + 1)] |
| 376 | assert block.splitlines() == [ |
| 377 | "## Market Data", |
| 378 | "", |
| 379 | "- Yahoo Finance daily closes: NVDA (Nvidia), USD, 2026-10-11 to 2026-11-10", |
| 380 | "- First close 226.32 (2026-10-12), last close 167.68 (2026-11-10), change -25.9%", |
| 381 | "- S&P 500 over the same window: 7,807.24 to 7,500.91, change -3.9%", |
| 382 | "- Largest daily moves, close to close:", |
| 383 | " - 2026-11-05: 190.00 to 172.33, -9.3%", |
| 384 | " - 2026-10-20: 222.00 to 210.00, -5.4%", |
| 385 | " - 2026-11-04: 200.00 to 190.00, -5.0%", |
| 386 | ] |
| 387 | for command in ( |
| 388 | "SYNTHESIS CONTRACT", "this contract still binds", "STOP and regenerate", |
| 389 | "Pass through ONLY", "do not add a `Sources:` list", "emit verbatim", |
| 390 | "Fill each cell", "After the table, write", "YOU ARE", |
| 391 | ): |
| 392 | assert command not in text |
| 393 | for word in ("must", "should", "mention", "cite", "do not"): |
| 394 | assert word not in block.lower() |
| 395 | assert NVDA_LINE.replace("NVDA -25.9%", "NVDA (Nvidia) -25.9%") in text |
| 396 | |
| 397 | |
| 398 | def test_no_market_data_section_without_a_fetch(): |
| 399 | assert "## Market Data" not in render.render_compact(_report()) |
| 400 | |
| 401 | |
| 402 | def test_comparison_puts_every_ticker_on_one_line(monkeypatch): |
| 403 | fake = _install(monkeypatch, charts={ |
| 404 | **NVDA_CHARTS, "AMD": _chart("AMD", AMD_CLOSES), |
| 405 | }) |
| 406 | nvidia, amd, rust = _report(), _report(), _report() |
| 407 | yahoo_finance.attach_market_data(nvidia, NVIDIA) |
| 408 | yahoo_finance.attach_market_data(amd, {"company": "AMD", "ticker": "AMD", "exchange": "Nasdaq"}) |
| 409 | yahoo_finance.attach_market_data(rust, {}) |
| 410 | |
| 411 | text = render.render_comparison_multi([("Nvidia", nvidia), ("AMD", amd), ("Rust", rust)]) |
| 412 | |
| 413 | lines = [line for line in text.splitlines() if "📈 Yahoo Finance" in line] |
| 414 | assert [line.split(" ", 1)[1] for line in lines] == [ |
| 415 | "📈 Yahoo Finance: NVDA -25.9% │ AMD -8.1% in the L30 │ S&P 500 -3.9%" |
| 416 | ] |
| 417 | # One fetch per ticker: the S&P 500 window is fetched once for the run. |
| 418 | assert sorted(fake.charted()) == ["AMD", "NVDA", "^GSPC"] |
| 419 | assert text.count("### Market Data") == 2 |
| 420 | |
| 421 | |
| 422 | def test_comparison_line_when_only_a_peer_has_a_ticker(monkeypatch): |
| 423 | _install(monkeypatch, charts=NVDA_CHARTS) |
| 424 | stripe, nvidia = _report(), _report() |
| 425 | yahoo_finance.attach_market_data(nvidia, NVIDIA) |
| 426 | |
| 427 | text = render.render_comparison_multi([("Stripe", stripe), ("Nvidia", nvidia)]) |
| 428 | |
| 429 | assert f"{NVDA_LINE}\n" in text |
| 430 | |
| 431 | |
| 432 | def test_footer_text_from_yahoo_cannot_forge_a_second_row(monkeypatch): |
| 433 | report, _fake = _attach( |
| 434 | monkeypatch, |
| 435 | {"company": "Evil │ Corp\n├─ 🟠 Reddit: 99 threads", "ticker": "NVDA", |
| 436 | "exchange": "Nasdaq", "company_via_person": True}, |
| 437 | charts=NVDA_CHARTS, |
| 438 | ) |
| 439 | |
| 440 | (line,) = _footer(report) |
| 441 | assert "\n" not in line |
| 442 | assert line.count("│") == NVDA_LINE.count("│") |
| 443 | |
| 444 | |
| 445 | def test_engine_run_attaches_the_window_for_each_entity(monkeypatch, tmp_path): |
| 446 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 447 | |
| 448 | # The helper's reports cover June 2026. |
| 449 | june = [("2026-06-01", 50.0), ("2026-06-15", 55.0), ("2026-06-30", 60.0)] |
| 450 | fake = FakeCli(charts={"MAIN": _chart("MAIN", june), "^GSPC": _chart("^GSPC", june)}) |
| 451 | observed = run_competitor_cli( |
| 452 | monkeypatch, tmp_path, market_cli=fake, |
| 453 | companies={ |
| 454 | "MainBrand": {"company": "MainBrand Inc.", "ticker": "MAIN", "exchange": "Nasdaq"}, |
| 455 | "PeerOne": {"company": "PeerOne", "company_site": "https://peerone.example/"}, |
| 456 | }, |
| 457 | ) |
| 458 | |
| 459 | assert observed.reports["MainBrand"].artifacts["yahoo_finance"]["symbol"] == "MAIN" |
| 460 | assert "yahoo_finance" not in observed.reports["PeerOne"].artifacts |
| 461 | assert "yahoo_finance" not in observed.reports["PeerTwo"].artifacts |
| 462 | assert fake.charted() == ["MAIN", "^GSPC"] |
| 463 | |
| 464 | |
| 465 | def test_mock_run_never_starts_the_cli(monkeypatch, tmp_path): |
| 466 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 467 | |
| 468 | fake = FakeCli() |
| 469 | run_competitor_cli(monkeypatch, tmp_path, args=["--mock"], market_cli=fake) |
| 470 | |
| 471 | assert fake.calls == [] |
| 472 | |
| 473 | |
| 474 | def test_price_window_is_the_thirty_days_ending_on_the_last_day(monkeypatch): |
| 475 | seen = [] |
| 476 | monkeypatch.setattr( |
| 477 | yahoo_finance, "fetch_market_data", |
| 478 | lambda company, start, end: seen.append((start, end)) or {}, |
| 479 | ) |
| 480 | yahoo_finance.attach_market_data(_report(range_from="2026-11-03", range_to="2026-11-10"), {"ticker": "NVDA"}) |
| 481 | assert seen == [("2026-10-11", "2026-11-10")] |
| 482 | |
| 483 | |
| 484 | @pytest.mark.parametrize("excluded", ["yahoo_finance", "reddit, Yahoo_Finance ,x"]) |
| 485 | def test_excluded_source_makes_no_cli_call_and_leaves_nothing(monkeypatch, excluded): |
| 486 | fake = _install(monkeypatch, charts=NVDA_CHARTS) |
| 487 | report = _report() |
| 488 | |
| 489 | yahoo_finance.attach_market_data(report, NVIDIA, {"EXCLUDE_SOURCES": excluded}) |
| 490 | |
| 491 | assert fake.calls == [] |
| 492 | assert _footer(report) == [] |
| 493 | assert "yahoo_finance" not in report.artifacts |
| 494 | assert "yahoo_finance" not in report.source_status |
| 495 | |
| 496 | |
| 497 | def test_other_exclusions_leave_the_price_line_on(monkeypatch): |
| 498 | fake = _install(monkeypatch, charts=NVDA_CHARTS) |
| 499 | report = _report() |
| 500 | |
| 501 | yahoo_finance.attach_market_data(report, NVIDIA, {"EXCLUDE_SOURCES": "reddit,jobs"}) |
| 502 | |
| 503 | assert _footer(report) == [NVDA_LINE] |
| 504 | assert fake.charted() == ["NVDA", "^GSPC"] |
| 505 | |
| 506 | |
| 507 | _JUNE = [("2026-06-01", 50.0), ("2026-06-15", 55.0), ("2026-06-30", 60.0)] |
| 508 | _LISTED = { |
| 509 | "MainBrand": {"company": "MainBrand Inc.", "ticker": "MAIN", "exchange": "Nasdaq"}, |
| 510 | "PeerOne": {"company": "PeerOne Corp.", "ticker": "PEER", "exchange": "Nasdaq"}, |
| 511 | } |
| 512 | _JUNE_CHARTS = { |
| 513 | "MAIN": _chart("MAIN", _JUNE), "PEER": _chart("PEER", _JUNE), "^GSPC": _chart("^GSPC", _JUNE), |
| 514 | } |
| 515 | |
| 516 | |
| 517 | def test_engine_run_with_yahoo_finance_excluded_never_starts_the_cli(monkeypatch, tmp_path): |
| 518 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 519 | |
| 520 | fake = FakeCli(charts=_JUNE_CHARTS) |
| 521 | observed = run_competitor_cli( |
| 522 | monkeypatch, tmp_path, market_cli=fake, companies=_LISTED, |
| 523 | config={"EXCLUDE_SOURCES": "yahoo_finance"}, |
| 524 | ) |
| 525 | |
| 526 | assert fake.calls == [] |
| 527 | for report in observed.reports.values(): |
| 528 | assert "yahoo_finance" not in report.artifacts |
| 529 | assert "yahoo_finance" not in report.source_status |
| 530 | # Jobs can still run, so the company is still looked up. |
| 531 | assert observed.reports["MainBrand"].artifacts["resolved"]["ticker"] == "MAIN" |
| 532 | assert observed.reports["PeerOne"].artifacts["resolved"]["ticker"] == "PEER" |
| 533 | |
| 534 | |
| 535 | def test_engine_run_with_both_company_lanes_excluded_skips_the_company_lookup(monkeypatch, tmp_path): |
| 536 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 537 | |
| 538 | fake = FakeCli(charts=_JUNE_CHARTS) |
| 539 | observed = run_competitor_cli( |
| 540 | monkeypatch, tmp_path, market_cli=fake, companies=_LISTED, |
| 541 | config={"EXCLUDE_SOURCES": "jobs, yahoo_finance"}, |
| 542 | ) |
| 543 | |
| 544 | assert observed.company_resolver.call_count == 0 |
| 545 | assert fake.calls == [] |
| 546 | for report in observed.reports.values(): |
| 547 | assert "company" not in report.artifacts["resolved"] |
| 548 | assert "ticker" not in report.artifacts["resolved"] |
| 549 | assert "yahoo_finance" not in report.artifacts |
| 550 | |
| 551 | |
| 552 | def test_engine_run_with_only_jobs_excluded_still_prices_the_company(monkeypatch, tmp_path): |
| 553 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 554 | |
| 555 | fake = FakeCli(charts=_JUNE_CHARTS) |
| 556 | observed = run_competitor_cli( |
| 557 | monkeypatch, tmp_path, market_cli=fake, companies=_LISTED, |
| 558 | config={"EXCLUDE_SOURCES": "jobs"}, |
| 559 | ) |
| 560 | |
| 561 | assert observed.reports["MainBrand"].artifacts["yahoo_finance"]["symbol"] == "MAIN" |
| 562 | assert observed.reports["PeerOne"].artifacts["yahoo_finance"]["symbol"] == "PEER" |
| 563 | |
| 564 | |
| 565 | def test_explicit_search_list_keeps_the_price_line(monkeypatch, tmp_path): |
| 566 | """The price window is not a search source, so ``--search`` cannot name |
| 567 | it and does not switch it off; ``EXCLUDE_SOURCES`` is the off switch.""" |
| 568 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 569 | |
| 570 | fake = FakeCli(charts=_JUNE_CHARTS) |
| 571 | observed = run_competitor_cli( |
| 572 | monkeypatch, tmp_path, market_cli=fake, companies=_LISTED, |
| 573 | args=["--search", "reddit"], |
| 574 | ) |
| 575 | |
| 576 | assert observed.reports["MainBrand"].artifacts["yahoo_finance"]["symbol"] == "MAIN" |
| 577 | |
| 578 | |
| 579 | _TOYOTA = {"company": "Toyota", "ticker": "7203", "exchange": "Tokyo Stock Exchange"} |
| 580 | |
| 581 | |
| 582 | @pytest.mark.parametrize( |
| 583 | "company,answer,state", |
| 584 | [ |
| 585 | (TESLA, _failed("GET /v6/finance/autocomplete returned HTTP 500: upstream failure"), health.ERROR), |
| 586 | ( |
| 587 | TESLA, |
| 588 | _failed("GET /v6/finance/autocomplete returned HTTP 429: Too Many Requests", code=7), |
| 589 | health.RATE_LIMITED, |
| 590 | ), |
| 591 | (TESLA, SimpleNamespace(returncode=0, stdout="", stderr=""), health.ERROR), |
| 592 | (TESLA, SimpleNamespace(returncode=0, stdout="<html>busy</html>", stderr=""), health.SCHEMA_DRIFT), |
| 593 | (TESLA, {"meta": {"source": "live"}, "results": {}}, health.SCHEMA_DRIFT), |
| 594 | (TESLA, {"results": {"ResultSet": {"Result": "TSLA"}}}, health.SCHEMA_DRIFT), |
| 595 | (_TOYOTA, _failed("GET /v6/finance/autocomplete returned HTTP 500: upstream failure"), health.ERROR), |
| 596 | ], |
| 597 | ids=[ |
| 598 | "cli-error", "http-429", "empty-output", "not-json", "missing-result-set", |
| 599 | "rows-not-a-list", "foreign-listing", |
| 600 | ], |
| 601 | ) |
| 602 | def test_failed_symbol_search_is_a_degraded_source_and_no_line(monkeypatch, company, answer, state): |
| 603 | report, fake = _attach(monkeypatch, company, matches={company["company"]: answer}) |
| 604 | |
| 605 | assert _footer(report) == [] |
| 606 | assert "yahoo_finance" not in report.artifacts |
| 607 | outcome = report.source_status["yahoo_finance"] |
| 608 | assert outcome.state == state |
| 609 | assert outcome.items_returned == 0 |
| 610 | assert company["company"] in outcome.detail |
| 611 | assert fake.charted() == [] |
| 612 | assert "Yahoo Finance" in "\n".join(render._render_source_outcome_note(report)) |
| 613 | |
| 614 | |
| 615 | def test_symbol_search_that_times_out_is_a_degraded_source(monkeypatch): |
| 616 | def times_out(cmd, timeout): |
| 617 | raise yahoo_finance.subproc.SubprocTimeout(f"timed out after {timeout}s") |
| 618 | |
| 619 | monkeypatch.setattr(yahoo_finance, "_is_available", lambda: True) |
| 620 | monkeypatch.setattr(yahoo_finance.subproc, "run_with_timeout", times_out) |
| 621 | report = _report() |
| 622 | |
| 623 | yahoo_finance.attach_market_data(report, TESLA) |
| 624 | |
| 625 | assert "yahoo_finance" not in report.artifacts |
| 626 | assert "Tesla" in report.source_status["yahoo_finance"].detail |
| 627 | |
| 628 | |
| 629 | class _GatedCli: |
| 630 | """Chart answers for any symbol; a symbol in ``held`` waits for ``release``.""" |
| 631 | |
| 632 | def __init__(self, held=()): |
| 633 | self.held = set(held) |
| 634 | self.started = threading.Event() |
| 635 | self.release = threading.Event() |
| 636 | self.calls: list[str] = [] |
| 637 | self._lock = threading.Lock() |
| 638 | |
| 639 | def __call__(self, cmd, timeout): |
| 640 | symbol = cmd[2] |
| 641 | with self._lock: |
| 642 | self.calls.append(symbol) |
| 643 | if symbol in self.held: |
| 644 | self.started.set() |
| 645 | assert self.release.wait(10), "the held fetch was never released" |
| 646 | return _ok(_chart(symbol, RISING_CLOSES)) |
| 647 | |
| 648 | |
| 649 | def _fetch_on_thread(symbol, results): |
| 650 | def work(): |
| 651 | results.append((symbol, yahoo_finance._fetch_window(symbol, "2026-10-11", "2026-11-10"))) |
| 652 | |
| 653 | thread = threading.Thread(target=work, daemon=True) |
| 654 | thread.start() |
| 655 | return thread |
| 656 | |
| 657 | |
| 658 | def test_a_slow_symbol_does_not_hold_up_another_symbol(monkeypatch): |
| 659 | cli = _GatedCli(held={"SLOW"}) |
| 660 | monkeypatch.setattr(yahoo_finance.subproc, "run_with_timeout", cli) |
| 661 | results: list = [] |
| 662 | |
| 663 | slow = _fetch_on_thread("SLOW", results) |
| 664 | try: |
| 665 | assert cli.started.wait(5) |
| 666 | fast = _fetch_on_thread("FAST", results) |
| 667 | fast.join(2) |
| 668 | finished_while_slow_was_held = not fast.is_alive() |
| 669 | finally: |
| 670 | cli.release.set() |
| 671 | slow.join(5) |
| 672 | fast.join(5) |
| 673 | |
| 674 | assert finished_while_slow_was_held |
| 675 | assert [symbol for symbol, _window in results] == ["FAST", "SLOW"] |
| 676 | assert all(len(window["bars"]) == 3 for _symbol, window in results) |
| 677 | |
| 678 | |
| 679 | def test_two_threads_asking_for_one_symbol_start_one_fetch(monkeypatch): |
| 680 | cli = _GatedCli(held={"NVDA"}) |
| 681 | monkeypatch.setattr(yahoo_finance.subproc, "run_with_timeout", cli) |
| 682 | results: list = [] |
| 683 | |
| 684 | first = _fetch_on_thread("NVDA", results) |
| 685 | try: |
| 686 | assert cli.started.wait(5) |
| 687 | second = _fetch_on_thread("NVDA", results) |
| 688 | # The second request arrives while the first is still at the CLI. |
| 689 | second.join(0.2) |
| 690 | assert second.is_alive() |
| 691 | finally: |
| 692 | cli.release.set() |
| 693 | first.join(5) |
| 694 | second.join(5) |
| 695 | |
| 696 | assert cli.calls == ["NVDA"] |
| 697 | assert len(results) == 2 |
| 698 | assert results[0][1] == results[1][1] |
| 699 | assert len(results[0][1]["bars"]) == 3 |
| 700 | |
| 701 | |
| 702 | def test_a_fetch_that_raises_is_not_remembered(monkeypatch): |
| 703 | answers = [OSError("exec format error")] |
| 704 | |
| 705 | def flaky(symbol, range_from, range_to): |
| 706 | if answers: |
| 707 | raise answers.pop() |
| 708 | return {"bars": [], "currency": "USD"} |
| 709 | |
| 710 | monkeypatch.setattr(yahoo_finance, "_fetch_window_uncached", flaky) |
| 711 | |
| 712 | with pytest.raises(OSError): |
| 713 | yahoo_finance._fetch_window("NVDA", "2026-10-11", "2026-11-10") |
| 714 | assert yahoo_finance._fetch_window("NVDA", "2026-10-11", "2026-11-10") == {"bars": [], "currency": "USD"} |
| 715 | |
| 716 | |
| 717 | # The backup: Yahoo's symbol search, asked for the topic itself, only when the |
| 718 | # Wikidata lookup failed. |
| 719 | |
| 720 | RATE_LIMITED = http.HTTPError("HTTP 429: Too Many Requests", status_code=429) |
| 721 | TIMED_OUT = http.HTTPError("Request timed out") |
| 722 | BACKUP_USED = "wikidata failed; yahoo backup used" |
| 723 | NO_BACKUP_MATCH = "wikidata failed; no backup match" |
| 724 | BACKUP_NOT_RUN = "wikidata failed; backup not run" |
| 725 | TSLA_ROWS = [("TSLA", "Tesla, Inc.", "Equity"), ("STSLA=F", "Tesla, Inc Single Stock futures", "Futures")] |
| 726 | |
| 727 | |
| 728 | def _named(*rows): |
| 729 | return {"meta": {"source": "live"}, "results": {"ResultSet": {"Result": [ |
| 730 | {"symbol": symbol, "name": name, "typeDisp": kind, "exchDisp": "-"} |
| 731 | for symbol, name, kind in rows |
| 732 | ]}}} |
| 733 | |
| 734 | |
| 735 | def _company_after(monkeypatch, topic, *, error=RATE_LIMITED, config=None, mock_run=False, **install_kwargs): |
| 736 | """What the engine resolves for a topic, with Wikidata failing unless |
| 737 | ``error`` is None and the price CLI answering from ``install_kwargs``.""" |
| 738 | fake = _install(monkeypatch, **install_kwargs) |
| 739 | wikidata = FakeWikidata(error=error) |
| 740 | monkeypatch.setattr(company_resolve.http, "get", wikidata) |
| 741 | company = cli._resolved_company(topic, mock=mock_run, config=config or {}) |
| 742 | return company, fake, wikidata |
| 743 | |
| 744 | |
| 745 | @pytest.mark.parametrize("error", [RATE_LIMITED, TIMED_OUT], ids=["http-429", "timeout"]) |
| 746 | def test_backup_gives_tesla_its_ticker_and_the_price_line(monkeypatch, error): |
| 747 | company, fake, wikidata = _company_after( |
| 748 | monkeypatch, "Tesla", error=error, |
| 749 | matches={"Tesla": _named(*TSLA_ROWS)}, |
| 750 | charts={"TSLA": _chart("TSLA", RISING_CLOSES), "^GSPC": _chart("^GSPC", SP500_CLOSES)}, |
| 751 | ) |
| 752 | |
| 753 | assert company == { |
| 754 | "company": "Tesla", "ticker": "TSLA", "company_source": "yahoo-backup", |
| 755 | "company_lookup": BACKUP_USED, "ticker_source": "yahoo-backup", |
| 756 | } |
| 757 | assert len(wikidata.calls) == 1 |
| 758 | report = _report() |
| 759 | yahoo_finance.attach_market_data(report, company) |
| 760 | assert _footer(report) == [ |
| 761 | "📈 Yahoo Finance: TSLA +10.0% in the L30 │ $100.00 → $110.00 │ " |
| 762 | "S&P 500 -3.9% │ best day Nov 10 +5.8%" |
| 763 | ] |
| 764 | # One symbol search, for the topic; the accepted symbol is not searched again. |
| 765 | assert [cmd[1:4] for cmd in fake.calls if cmd[1] == "autocomplete"] == [ |
| 766 | ["autocomplete", "--query", "Tesla"] |
| 767 | ] |
| 768 | assert fake.charted() == ["TSLA", "^GSPC"] |
| 769 | |
| 770 | |
| 771 | def test_backup_accepts_a_name_that_differs_by_case_and_designator(monkeypatch): |
| 772 | company, _fake, _wikidata = _company_after( |
| 773 | monkeypatch, "Nvidia", matches={"Nvidia": _named(("NVDA", "NVIDIA Corporation", "Equity"))}, |
| 774 | ) |
| 775 | |
| 776 | assert (company["company"], company["ticker"]) == ("Nvidia", "NVDA") |
| 777 | assert company["company_source"] == "yahoo-backup" |
| 778 | assert "exchange" not in company and "company_site" not in company |
| 779 | |
| 780 | |
| 781 | @pytest.mark.parametrize( |
| 782 | "topic,rows", |
| 783 | [ |
| 784 | ("Rust", [("RUSTA.ST", "Rusta AB (publ)", "Equity")]), |
| 785 | ("Stripe", [("STRIZZX", "Stripe Fund", "Fund"), ("0P0000X8PD.F", "Stripe", "Fund")]), |
| 786 | ( |
| 787 | "Apple", |
| 788 | [("APLE", "Apple Hospitality REIT, Inc.", "Equity"), ("AAPL", "Apple Inc.", "Equity")], |
| 789 | ), |
| 790 | ("Toyota", [("7203.T", "Toyota Motor Corporation", "Equity")]), |
| 791 | ("Toyota", [("7203.T", "Toyota", "Equity"), ("TM", "Toyota", "Equity")]), |
| 792 | ("Jensen Huang", []), |
| 793 | ], |
| 794 | ids=[ |
| 795 | "rust-is-not-rusta", "funds-only", "name-only-contains-the-topic", |
| 796 | "foreign-listing", "foreign-listing-with-the-same-name", "no-results", |
| 797 | ], |
| 798 | ) |
| 799 | def test_backup_rejects_anything_but_an_exact_us_match_on_the_first_equity(monkeypatch, topic, rows): |
| 800 | company, fake, _wikidata = _company_after(monkeypatch, topic, matches={topic: _named(*rows)}) |
| 801 | |
| 802 | assert company == {"company_lookup": NO_BACKUP_MATCH} |
| 803 | assert len(fake.calls) == 1 |
| 804 | report = _report() |
| 805 | yahoo_finance.attach_market_data(report, company) |
| 806 | assert _footer(report) == [] |
| 807 | assert len(fake.calls) == 1 |
| 808 | |
| 809 | |
| 810 | @pytest.mark.parametrize( |
| 811 | "name", |
| 812 | [ |
| 813 | "Tesla", "TESLA INC", "Tesla, Inc.", "Tesla Incorporated", "Tesla Corp.", "Tesla Corporation", |
| 814 | "Tesla Co.", "Tesla Company", "Tesla Ltd.", "Tesla Limited", "Tesla PLC", "Tesla plc", |
| 815 | "Tesla AG", "Tesla SA", "Tesla S.A.", "Tesla NV", "Tesla N.V.", "Tesla AB", |
| 816 | "Tesla AB (publ)", "Tesla SE", "Tesla Holdings", "Tesla Holding", "Tesla Group", |
| 817 | "Tesla, Inc. Class A", "Tesla Inc Class C", "Tesla Holdings Co., Ltd.", "Tesla, The", |
| 818 | " tesla, inc. ", |
| 819 | ], |
| 820 | ) |
| 821 | def test_backup_name_match_ignores_case_punctuation_and_trailing_designators(name): |
| 822 | assert yahoo_finance._same_company_name("Tesla", name) |
| 823 | |
| 824 | |
| 825 | @pytest.mark.parametrize( |
| 826 | "topic,name", |
| 827 | [ |
| 828 | ("Rust", "Rusta AB (publ)"), |
| 829 | ("Apple", "Apple Hospitality REIT, Inc."), |
| 830 | ("Tesla", "Tesla Motors, Inc."), |
| 831 | ("Tesla", "Inc. Tesla"), |
| 832 | ("Tesla", ""), |
| 833 | ("Group", "Inc."), |
| 834 | ], |
| 835 | ) |
| 836 | def test_backup_name_match_refuses_any_other_name(topic, name): |
| 837 | assert not yahoo_finance._same_company_name(topic, name) |
| 838 | |
| 839 | |
| 840 | def test_wikidata_answering_nothing_never_reaches_the_backup(monkeypatch): |
| 841 | company, fake, wikidata = _company_after( |
| 842 | monkeypatch, "Rust", error=None, matches={"Rust": _named(("RUST", "Rust", "Equity"))}, |
| 843 | ) |
| 844 | |
| 845 | assert company == {} |
| 846 | assert wikidata.calls |
| 847 | assert fake.calls == [] |
| 848 | |
| 849 | |
| 850 | def test_backup_without_the_binary_gives_nothing(monkeypatch): |
| 851 | company, fake, _wikidata = _company_after(monkeypatch, "Tesla", available=False) |
| 852 | |
| 853 | assert company == {"company_lookup": BACKUP_NOT_RUN} |
| 854 | assert fake.calls == [] |
| 855 | |
| 856 | |
| 857 | @pytest.mark.parametrize("excluded", ["yahoo_finance", "reddit, Yahoo_Finance ,x"]) |
| 858 | def test_backup_is_not_run_when_yahoo_finance_is_excluded(monkeypatch, excluded): |
| 859 | company, fake, wikidata = _company_after( |
| 860 | monkeypatch, "Tesla", config={"EXCLUDE_SOURCES": excluded}, |
| 861 | matches={"Tesla": _named(*TSLA_ROWS)}, |
| 862 | ) |
| 863 | |
| 864 | assert company == {"company_lookup": BACKUP_NOT_RUN} |
| 865 | assert len(wikidata.calls) == 1 |
| 866 | assert fake.calls == [] |
| 867 | |
| 868 | |
| 869 | def test_a_topic_that_is_not_company_shaped_reaches_neither_wikidata_nor_the_cli(monkeypatch): |
| 870 | company, fake, wikidata = _company_after( |
| 871 | monkeypatch, "how to deploy on Fly.io", |
| 872 | matches={"how to deploy on Fly.io": _named(("FLY", "how to deploy on Fly.io", "Equity"))}, |
| 873 | ) |
| 874 | |
| 875 | assert company == {} |
| 876 | assert wikidata.calls == [] |
| 877 | assert fake.calls == [] |
| 878 | |
| 879 | |
| 880 | def test_mock_run_reaches_neither_wikidata_nor_the_backup(monkeypatch): |
| 881 | company, fake, wikidata = _company_after( |
| 882 | monkeypatch, "Tesla", mock_run=True, matches={"Tesla": _named(*TSLA_ROWS)}, |
| 883 | ) |
| 884 | |
| 885 | assert company == {} |
| 886 | assert wikidata.calls == [] |
| 887 | assert fake.calls == [] |
| 888 | |
| 889 | |
| 890 | @pytest.mark.parametrize( |
| 891 | "answer", |
| 892 | [ |
| 893 | _failed("GET /v6/finance/autocomplete returned HTTP 429: Too Many Requests", code=7), |
| 894 | {"meta": {"source": "live"}, "results": {}}, |
| 895 | ], |
| 896 | ids=["cli-error", "unexpected-shape"], |
| 897 | ) |
| 898 | def test_backup_search_that_fails_gives_nothing_and_does_not_raise(monkeypatch, answer): |
| 899 | company, _fake, _wikidata = _company_after(monkeypatch, "Tesla", matches={"Tesla": answer}) |
| 900 | |
| 901 | assert company == {"company_lookup": NO_BACKUP_MATCH} |
| 902 | |
| 903 | |
| 904 | def test_failed_lookup_is_logged_once_when_the_backup_runs(monkeypatch): |
| 905 | logged = [] |
| 906 | monkeypatch.setattr( |
| 907 | company_resolve.log, "source_log", |
| 908 | lambda source, message, **kwargs: logged.append((source, message, kwargs)), |
| 909 | ) |
| 910 | |
| 911 | _company_after(monkeypatch, "Tesla", matches={"Tesla": _named(*TSLA_ROWS)}) |
| 912 | |
| 913 | company_lines = [entry for entry in logged if entry[0] == "Company"] |
| 914 | assert len(company_lines) == 1 |
| 915 | assert "Wikidata lookup failed for 'Tesla'" in company_lines[0][1] |
| 916 | assert company_lines[0][2] == {"tty_only": False} |
| 917 | |
| 918 | |
| 919 | def test_engine_run_records_the_lookup_note_for_both_backup_outcomes(monkeypatch, tmp_path): |
| 920 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 921 | |
| 922 | fake = FakeCli( |
| 923 | charts={"MAIN": _chart("MAIN", _JUNE), "^GSPC": _chart("^GSPC", _JUNE)}, |
| 924 | matches={ |
| 925 | "MainBrand": _named(("MAIN", "MainBrand, Inc.", "Equity")), |
| 926 | "PeerOne": _named(("PONE.L", "PeerOne plc", "Equity")), |
| 927 | }, |
| 928 | ) |
| 929 | observed = run_competitor_cli( |
| 930 | monkeypatch, tmp_path, market_cli=fake, |
| 931 | companies={ |
| 932 | "MainBrand": company_resolve.FailedLookup(), |
| 933 | "PeerOne": company_resolve.FailedLookup(), |
| 934 | }, |
| 935 | ) |
| 936 | |
| 937 | main = observed.reports["MainBrand"].artifacts["resolved"] |
| 938 | assert (main["company"], main["ticker"]) == ("MainBrand", "MAIN") |
| 939 | assert main["company_source"] == "yahoo-backup" |
| 940 | assert main["company_lookup"] == BACKUP_USED |
| 941 | assert observed.reports["MainBrand"].artifacts["yahoo_finance"]["symbol"] == "MAIN" |
| 942 | peer_one = observed.reports["PeerOne"].artifacts["resolved"] |
| 943 | assert peer_one["company_lookup"] == NO_BACKUP_MATCH |
| 944 | assert not {"company", "ticker", "company_source"} & set(peer_one) |
| 945 | assert "yahoo_finance" not in observed.reports["PeerOne"].artifacts |
| 946 | # Wikidata answered for PeerTwo, so there is no note and no symbol search. |
| 947 | assert "company_lookup" not in observed.reports["PeerTwo"].artifacts["resolved"] |
| 948 | assert sorted(cmd[3] for cmd in fake.calls if cmd[1] == "autocomplete") == ["MainBrand", "PeerOne"] |
| 949 | rows = render._render_resolved_entities_block( |
| 950 | [(name, observed.reports[name]) for name in ("MainBrand", "PeerOne")] |
| 951 | ) |
| 952 | assert "Ticker MAIN (Yahoo match)" in rows[2] |
| 953 | assert "Ticker" not in rows[3] |
| 954 | |
| 955 | |
| 956 | # The host's ticker: ``--ticker "SYMBOL:Company"`` pairs the hosting model |
| 957 | # found by web search, each checked against Yahoo's chart and symbol search. |
| 958 | |
| 959 | TSLA_CLOSES = [("2026-10-12", 400.0), ("2026-10-13", 410.0), ("2026-11-10", 402.0)] |
| 960 | SPCX_CLOSES = [("2026-10-12", 100.0), ("2026-10-13", 96.0), ("2026-11-10", 86.0)] |
| 961 | GOOGL_CLOSES = [("2026-10-12", 200.0), ("2026-10-13", 198.0), ("2026-11-10", 193.8)] |
| 962 | NOT_FOUND = _failed( |
| 963 | 'GET /v8/finance/chart/ANT returned HTTP 404: {"chart":{"result":null,"error":' |
| 964 | '{"code":"Not Found","description":"No data found, symbol may be delisted"}}}' |
| 965 | ) |
| 966 | HOST_CHARTS = { |
| 967 | "SPCX": _chart("SPCX", SPCX_CLOSES, name="Space Exploration Technologies Corp."), |
| 968 | "NET": _chart("NET", RISING_CLOSES, name="Cloudflare, Inc."), |
| 969 | "TTWO": _chart("TTWO", RISING_CLOSES, name="Take-Two Interactive Software, Inc."), |
| 970 | "NVDA": _chart("NVDA", NVDA_CLOSES, name="NVIDIA Corporation"), |
| 971 | "GOOGL": _chart("GOOGL", GOOGL_CLOSES, name="Alphabet Inc."), |
| 972 | "TSLA": _chart("TSLA", TSLA_CLOSES, name="Tesla, Inc."), |
| 973 | "STRS": _chart("STRS", RISING_CLOSES, name="Stratus Properties Inc."), |
| 974 | "ANT": NOT_FOUND, |
| 975 | "SPY": _chart("SPY", RISING_CLOSES, name="State Street SPDR S&P 500 ETF Trust", instrument="ETF"), |
| 976 | "^GSPC": _chart("^GSPC", SP500_CLOSES, name="S&P 500", instrument="INDEX"), |
| 977 | } |
| 978 | HOST_MATCHES = { |
| 979 | "SpaceX": _named( |
| 980 | ("SPCX", "Space Exploration Technologies Corp.", "Equity"), |
| 981 | ("SSPCX=F", "SpaceX Single Stock futures", "Futures"), |
| 982 | ("SPCF", "ProShares Ultra SpaceX", "ETF"), |
| 983 | ), |
| 984 | "Cloudflare": _named(("NET", "Cloudflare, Inc.", "Equity")), |
| 985 | "Take-Two Interactive": _named(("TTWO", "Take-Two Interactive Software, Inc.", "Equity")), |
| 986 | "Nvidia": _named(("NVDA", "NVIDIA Corporation", "Equity"), ("NVDL", "GraniteShares 2x Long NVDA", "ETF")), |
| 987 | "Nvidia Corporation": _named(("NVDA", "NVIDIA Corporation", "Equity")), |
| 988 | "Alphabet": _named( |
| 989 | ("GOOG", "Alphabet Inc.", "Equity"), ("GOOGL", "Alphabet Inc.", "Equity"), |
| 990 | ("SGOOG=F", "Alphabet Inc Single Stock futures", "Futures"), |
| 991 | ), |
| 992 | "Tesla": _named(*TSLA_ROWS), |
| 993 | "Stripe": _named( |
| 994 | ("STRIZZX", "Stripe - Company Level", "Fund"), |
| 995 | ("0P0000X8PD.F", "Prosper Stars & Stripes Fund P EUR", "Fund"), |
| 996 | ), |
| 997 | "Anthropic": _named(("ANTH.PVT", "Anthropic PBC", "Private Company")), |
| 998 | "S&P 500 ETF": _named(("SPY", "State Street SPDR S&P 500 ETF Trust", "ETF")), |
| 999 | } |
| 1000 | |
| 1001 | |
| 1002 | def _host(monkeypatch, ticker, *, topic="Some Topic", config=None, **install_kwargs): |
| 1003 | """Parse ``--ticker``, check it and attach it, as the engine does after a |
| 1004 | run. Returns the report, what goes into ``resolved``, and the CLI.""" |
| 1005 | install_kwargs.setdefault("charts", HOST_CHARTS) |
| 1006 | install_kwargs.setdefault("matches", HOST_MATCHES) |
| 1007 | fake = _install(monkeypatch, **install_kwargs) |
| 1008 | report = _report() |
| 1009 | report.topic = topic |
| 1010 | fields = yahoo_finance.attach_host_tickers( |
| 1011 | report, yahoo_finance.parse_host_tickers(ticker), config, |
| 1012 | ) |
| 1013 | return report, fields, fake |
| 1014 | |
| 1015 | |
| 1016 | @pytest.mark.parametrize( |
| 1017 | "ticker,symbol", |
| 1018 | [ |
| 1019 | ("SPCX:SpaceX", "SPCX"), |
| 1020 | ("NET:Cloudflare", "NET"), |
| 1021 | ("TTWO:Take-Two Interactive", "TTWO"), |
| 1022 | ("NVDA:Nvidia", "NVDA"), |
| 1023 | ("nvda: Nvidia ", "NVDA"), |
| 1024 | ("$NVDA:Nvidia", "NVDA"), |
| 1025 | ], |
| 1026 | ) |
| 1027 | def test_host_ticker_is_accepted_when_yahoo_lists_it_first_for_the_company(monkeypatch, ticker, symbol): |
| 1028 | report, fields, fake = _host(monkeypatch, ticker) |
| 1029 | |
| 1030 | assert report.artifacts["yahoo_finance"]["symbol"] == symbol |
| 1031 | assert fields["ticker"] == symbol |
| 1032 | assert fields["tickers"] == [symbol] |
| 1033 | assert fields["ticker_source"] == "host" |
| 1034 | assert "ticker_rejected" not in fields |
| 1035 | assert "yahoo_finance" not in report.source_status |
| 1036 | # One chart fetch for the symbol: the check reads the fetch the line uses. |
| 1037 | assert fake.charted() == [symbol, "^GSPC"] |
| 1038 | assert len([cmd for cmd in fake.calls if cmd[1] == "autocomplete"]) == 1 |
| 1039 | |
| 1040 | |
| 1041 | def test_host_ticker_is_accepted_when_the_first_stock_is_the_same_company(monkeypatch): |
| 1042 | """Yahoo lists GOOG before GOOGL for "Alphabet"; both are Alphabet Inc.""" |
| 1043 | report, fields, _fake = _host(monkeypatch, "GOOGL:Alphabet") |
| 1044 | |
| 1045 | assert report.artifacts["yahoo_finance"]["symbol"] == "GOOGL" |
| 1046 | assert fields["tickers"] == ["GOOGL"] |
| 1047 | |
| 1048 | |
| 1049 | @pytest.mark.parametrize( |
| 1050 | "ticker,reason", |
| 1051 | [ |
| 1052 | ("STRS:Stripe", "Yahoo lists no stock for 'Stripe'; STRS is Stratus Properties Inc."), |
| 1053 | ("ANT:Anthropic", "Yahoo has no price data for ANT"), |
| 1054 | ("SPY:S&P 500 ETF", "SPY is not a stock on Yahoo (ETF)"), |
| 1055 | ( |
| 1056 | "STRS:Tesla", |
| 1057 | "Yahoo's first stock for 'Tesla' is TSLA (Tesla, Inc.); STRS is Stratus Properties Inc.", |
| 1058 | ), |
| 1059 | ("NVDA", "no company name"), |
| 1060 | ("NVDA:", "no company name"), |
| 1061 | (":Nvidia", "not a ticker symbol"), |
| 1062 | ("--query:Nvidia", "not a ticker symbol"), |
| 1063 | ("^GSPC:S&P 500", "not a ticker symbol"), |
| 1064 | ], |
| 1065 | ids=[ |
| 1066 | "stripe-is-not-stratus", "filed-but-not-trading", "not-an-equity", "another-company", |
| 1067 | "symbol-alone", "empty-name", "no-symbol", "flag-shaped-symbol", "index", |
| 1068 | ], |
| 1069 | ) |
| 1070 | def test_host_ticker_that_fails_the_check_gives_no_line(monkeypatch, ticker, reason): |
| 1071 | report, fields, _fake = _host(monkeypatch, ticker) |
| 1072 | |
| 1073 | assert _footer(report) == [] |
| 1074 | assert "yahoo_finance" not in report.artifacts |
| 1075 | assert "yahoo_finance" not in report.source_status |
| 1076 | assert fields == { |
| 1077 | "ticker_source": "host", "ticker_rejected": [{"pair": ticker, "reason": reason}], |
| 1078 | } |
| 1079 | |
| 1080 | |
| 1081 | def test_host_ticker_with_no_company_name_never_reaches_the_cli(monkeypatch): |
| 1082 | _report_, _fields, fake = _host(monkeypatch, "NVDA,--help:Nvidia") |
| 1083 | |
| 1084 | assert fake.calls == [] |
| 1085 | |
| 1086 | |
| 1087 | def test_host_ticker_with_fewer_than_two_closes_is_rejected(monkeypatch): |
| 1088 | report, fields, _fake = _host( |
| 1089 | monkeypatch, "NVDA:Nvidia", |
| 1090 | charts={"NVDA": _chart("NVDA", NVDA_CLOSES[:1], name="NVIDIA Corporation")}, |
| 1091 | ) |
| 1092 | |
| 1093 | assert "yahoo_finance" not in report.artifacts |
| 1094 | assert "fewer than two daily closes" in fields["ticker_rejected"][0]["reason"] |
| 1095 | |
| 1096 | |
| 1097 | @pytest.mark.parametrize( |
| 1098 | "answer,state", |
| 1099 | [ |
| 1100 | ( |
| 1101 | _failed("GET /v6/finance/autocomplete returned HTTP 429: Too Many Requests", code=7), |
| 1102 | health.RATE_LIMITED, |
| 1103 | ), |
| 1104 | (_failed("GET /v6/finance/autocomplete returned HTTP 500: upstream failure"), health.ERROR), |
| 1105 | ({"meta": {"source": "live"}, "results": {}}, health.SCHEMA_DRIFT), |
| 1106 | ], |
| 1107 | ids=["http-429", "cli-error", "unexpected-shape"], |
| 1108 | ) |
| 1109 | def test_host_ticker_whose_symbol_search_fails_is_a_degraded_source(monkeypatch, answer, state): |
| 1110 | report, fields, _fake = _host(monkeypatch, "NVDA:Nvidia", matches={"Nvidia": answer}) |
| 1111 | |
| 1112 | assert _footer(report) == [] |
| 1113 | assert "yahoo_finance" not in report.artifacts |
| 1114 | assert report.source_status["yahoo_finance"].state == state |
| 1115 | assert "Nvidia" in report.source_status["yahoo_finance"].detail |
| 1116 | assert "ticker" not in fields |
| 1117 | assert fields["ticker_rejected"][0]["pair"] == "NVDA:Nvidia" |
| 1118 | assert "not checked" in fields["ticker_rejected"][0]["reason"] |
| 1119 | |
| 1120 | |
| 1121 | def test_host_ticker_whose_symbol_search_times_out_does_not_raise(monkeypatch): |
| 1122 | def cli(cmd, timeout): |
| 1123 | if cmd[1] == "autocomplete": |
| 1124 | raise yahoo_finance.subproc.SubprocTimeout(f"timed out after {timeout}s") |
| 1125 | return _ok(HOST_CHARTS[cmd[2]]) |
| 1126 | |
| 1127 | monkeypatch.setattr(yahoo_finance, "_is_available", lambda: True) |
| 1128 | monkeypatch.setattr(yahoo_finance.subproc, "run_with_timeout", cli) |
| 1129 | report = _report() |
| 1130 | |
| 1131 | fields = yahoo_finance.attach_host_tickers(report, yahoo_finance.parse_host_tickers("NVDA:Nvidia")) |
| 1132 | |
| 1133 | assert "yahoo_finance" not in report.artifacts |
| 1134 | assert "Nvidia" in report.source_status["yahoo_finance"].detail |
| 1135 | assert "ticker" not in fields |
| 1136 | |
| 1137 | |
| 1138 | def test_host_ticker_whose_chart_is_rate_limited_is_a_degraded_source(monkeypatch): |
| 1139 | report, fields, fake = _host( |
| 1140 | monkeypatch, "NVDA:Nvidia", |
| 1141 | charts={"NVDA": _failed("GET /v8/finance/chart/NVDA returned HTTP 429: Too Many Requests", code=7)}, |
| 1142 | ) |
| 1143 | |
| 1144 | assert report.source_status["yahoo_finance"].state == health.RATE_LIMITED |
| 1145 | assert "not checked" in fields["ticker_rejected"][0]["reason"] |
| 1146 | assert fake.calls == [fake.calls[0]] |
| 1147 | |
| 1148 | |
| 1149 | def test_two_host_tickers_share_one_footer_line_and_both_reach_the_evidence(monkeypatch): |
| 1150 | report, fields, fake = _host(monkeypatch, "TSLA:Tesla,SPCX:SpaceX", topic="Elon Musk") |
| 1151 | |
| 1152 | assert _footer(report) == [ |
| 1153 | "📈 Yahoo Finance: TSLA (Tesla) +0.5% │ SPCX (SpaceX) -14.0% in the L30 │ S&P 500 -3.9%" |
| 1154 | ] |
| 1155 | assert fields == { |
| 1156 | "ticker_source": "host", "ticker": "TSLA", "tickers": ["TSLA", "SPCX"], "company": "Tesla", |
| 1157 | } |
| 1158 | text = render.render_compact(report) |
| 1159 | assert text.count("## Market Data") == 1 |
| 1160 | block = text[text.index("## Market Data"):] |
| 1161 | block = block[:block.index("\n## ", 1)] |
| 1162 | assert [line for line in block.splitlines() if line.startswith("- Yahoo Finance daily closes")] == [ |
| 1163 | "- Yahoo Finance daily closes: TSLA (Tesla), USD, 2026-10-11 to 2026-11-10", |
| 1164 | "- Yahoo Finance daily closes: SPCX (SpaceX), USD, 2026-10-11 to 2026-11-10", |
| 1165 | ] |
| 1166 | assert sorted(fake.charted()) == ["SPCX", "TSLA", "^GSPC"] |
| 1167 | |
| 1168 | |
| 1169 | def test_one_accepted_and_one_rejected_host_ticker_prints_the_accepted_one(monkeypatch): |
| 1170 | report, fields, _fake = _host(monkeypatch, "ANT:Anthropic,NVDA:Nvidia", topic="AI labs") |
| 1171 | |
| 1172 | assert _footer(report)[0].startswith("📈 Yahoo Finance: NVDA (Nvidia) -25.9% in the L30 │ $226.32") |
| 1173 | assert fields["tickers"] == ["NVDA"] |
| 1174 | assert fields["ticker_rejected"] == [ |
| 1175 | {"pair": "ANT:Anthropic", "reason": "Yahoo has no price data for ANT"}, |
| 1176 | ] |
| 1177 | |
| 1178 | |
| 1179 | def test_a_third_host_ticker_is_ignored_with_a_log_line(monkeypatch): |
| 1180 | logged = [] |
| 1181 | monkeypatch.setattr(yahoo_finance, "_log", logged.append) |
| 1182 | |
| 1183 | report, fields, fake = _host(monkeypatch, "TSLA:Tesla, SPCX:SpaceX ,NVDA:Nvidia", topic="Elon Musk") |
| 1184 | |
| 1185 | assert fields["tickers"] == ["TSLA", "SPCX"] |
| 1186 | assert "NVDA" not in fake.charted() |
| 1187 | assert any("NVDA:Nvidia" in line and "ignor" in line for line in logged) |
| 1188 | |
| 1189 | |
| 1190 | def test_a_repeated_host_symbol_is_used_once(monkeypatch): |
| 1191 | _report_, fields, _fake = _host(monkeypatch, "NVDA:Nvidia,nvda:Nvidia") |
| 1192 | |
| 1193 | assert fields["tickers"] == ["NVDA"] |
| 1194 | assert fields["ticker_rejected"] == [{"pair": "nvda:Nvidia", "reason": "repeats NVDA"}] |
| 1195 | |
| 1196 | |
| 1197 | @pytest.mark.parametrize( |
| 1198 | "topic,ticker,shown", |
| 1199 | [ |
| 1200 | ("Nvidia", "NVDA:Nvidia", "NVDA -25.9%"), |
| 1201 | ("NVIDIA", "NVDA:Nvidia Corporation", "NVDA -25.9%"), |
| 1202 | ("Jensen Huang", "NVDA:Nvidia", "NVDA (Nvidia) -25.9%"), |
| 1203 | ("Waymo", "GOOGL:Alphabet", "GOOGL (Alphabet) -3.1%"), |
| 1204 | ], |
| 1205 | ids=["same", "same-but-for-case-and-designator", "person", "subsidiary"], |
| 1206 | ) |
| 1207 | def test_footer_names_the_company_only_when_it_is_not_the_topic(monkeypatch, topic, ticker, shown): |
| 1208 | report, _fields, _fake = _host(monkeypatch, ticker, topic=topic) |
| 1209 | |
| 1210 | assert _footer(report)[0].startswith(f"📈 Yahoo Finance: {shown} in the L30 │ $") |
| 1211 | |
| 1212 | |
| 1213 | @pytest.mark.parametrize( |
| 1214 | "config,available,why", |
| 1215 | [ |
| 1216 | ({"EXCLUDE_SOURCES": "yahoo_finance"}, True, "not checked: yahoo_finance is excluded"), |
| 1217 | ({}, False, "not checked: yahoo-finance-pp-cli is not on PATH"), |
| 1218 | ], |
| 1219 | ids=["excluded", "binary-absent"], |
| 1220 | ) |
| 1221 | def test_host_ticker_makes_no_cli_call_when_the_lane_is_off(monkeypatch, config, available, why): |
| 1222 | report, fields, fake = _host(monkeypatch, "NVDA:Nvidia", config=config, available=available) |
| 1223 | |
| 1224 | assert fake.calls == [] |
| 1225 | assert _footer(report) == [] |
| 1226 | assert "yahoo_finance" not in report.artifacts |
| 1227 | assert fields == { |
| 1228 | "ticker_source": "host", "ticker_rejected": [{"pair": "NVDA:Nvidia", "reason": why}], |
| 1229 | } |
| 1230 | |
| 1231 | |
| 1232 | def test_excluded_lane_records_no_outcome_for_a_host_ticker(monkeypatch): |
| 1233 | report, _fields, _fake = _host( |
| 1234 | monkeypatch, "NVDA:Nvidia", config={"EXCLUDE_SOURCES": "yahoo_finance"}, |
| 1235 | ) |
| 1236 | |
| 1237 | assert "yahoo_finance" not in report.source_status |
| 1238 | |
| 1239 | |
| 1240 | def test_missing_helper_with_a_host_ticker_says_so_once_with_the_install_command(monkeypatch, capsys): |
| 1241 | report, _fields, _fake = _host(monkeypatch, "NVDA:Nvidia,MSFT:Microsoft", available=False) |
| 1242 | |
| 1243 | outcome = report.source_status["yahoo_finance"] |
| 1244 | assert outcome.state == health.SKIPPED_UNCONFIGURED |
| 1245 | assert outcome.detail == ( |
| 1246 | f"yahoo-finance-pp-cli is not on PATH; install: {health.pp_install_cmd('yahoo-finance')}" |
| 1247 | ) |
| 1248 | assert len(outcome.detail) <= 140 |
| 1249 | logged = [line for line in capsys.readouterr().err.splitlines() if "yahoo-finance-pp-cli" in line] |
| 1250 | assert len(logged) == 1 and "--ticker not checked" in logged[0] |
| 1251 | |
| 1252 | |
| 1253 | def test_missing_helper_without_a_host_ticker_is_silent(monkeypatch, capsys): |
| 1254 | monkeypatch.setattr(yahoo_finance, "_is_available", lambda: False) |
| 1255 | report = _report() |
| 1256 | |
| 1257 | yahoo_finance.attach_host_tickers(report, []) |
| 1258 | |
| 1259 | assert "yahoo_finance" not in report.source_status |
| 1260 | assert "yahoo-finance-pp-cli" not in capsys.readouterr().err |
| 1261 | |
| 1262 | |
| 1263 | def test_resolved_row_names_the_host_search_and_keeps_the_other_wordings(): |
| 1264 | from tests.test_company_resolve import _report as resolved_report |
| 1265 | |
| 1266 | rows = render._render_resolved_entities_block([ |
| 1267 | ("Elon Musk", resolved_report("Elon Musk", { |
| 1268 | "company": "Tesla", "ticker": "TSLA", "tickers": ["TSLA", "SPCX"], "ticker_source": "host", |
| 1269 | })), |
| 1270 | ("Jensen Huang", resolved_report("Jensen Huang", { |
| 1271 | "company": "Nvidia", "ticker": "NVDA", "company_via_person": True, "ticker_source": "wikidata", |
| 1272 | })), |
| 1273 | ("Tesla", resolved_report("Tesla", { |
| 1274 | "company": "Tesla", "ticker": "TSLA", "company_source": "yahoo-backup", |
| 1275 | "ticker_source": "yahoo-backup", |
| 1276 | })), |
| 1277 | ("Stripe", resolved_report("Stripe", { |
| 1278 | "ticker_source": "host", "ticker_rejected": [{"pair": "STRS:Stripe", "reason": "no"}], |
| 1279 | })), |
| 1280 | ]) |
| 1281 | |
| 1282 | assert rows[2] == "- **Elon Musk**: X - | Subs - | GitHub - | Ticker TSLA, SPCX (host search) | Context: -" |
| 1283 | assert "Ticker NVDA (via Nvidia)" in rows[3] |
| 1284 | assert "Ticker TSLA (Yahoo match)" in rows[4] |
| 1285 | assert "Ticker" not in rows[5] |
| 1286 | |
| 1287 | |
| 1288 | # Resolution order in the engine. |
| 1289 | |
| 1290 | |
| 1291 | def _wikidata_asked_for_a_listing(wikidata) -> bool: |
| 1292 | return any( |
| 1293 | "Q82059" in str((call.get("params") or {}).get("ids", "")) for call in wikidata.calls |
| 1294 | ) |
| 1295 | |
| 1296 | |
| 1297 | def test_ticker_source_is_recorded_for_wikidata_and_the_backup(monkeypatch): |
| 1298 | company, _fake, wikidata = _company_after(monkeypatch, "Nvidia", error=None) |
| 1299 | assert (company["ticker"], company["ticker_source"]) == ("NVDA", "wikidata") |
| 1300 | assert _wikidata_asked_for_a_listing(wikidata) |
| 1301 | |
| 1302 | backup, _fake, _wikidata = _company_after(monkeypatch, "Tesla", matches={"Tesla": _named(*TSLA_ROWS)}) |
| 1303 | assert backup["ticker_source"] == "yahoo-backup" |
| 1304 | |
| 1305 | |
| 1306 | def test_host_ticker_keeps_the_wikidata_company_and_asks_it_for_no_listing(monkeypatch): |
| 1307 | fake = _install(monkeypatch, charts=HOST_CHARTS, matches=HOST_MATCHES) |
| 1308 | wikidata = FakeWikidata() |
| 1309 | monkeypatch.setattr(company_resolve.http, "get", wikidata) |
| 1310 | |
| 1311 | company = cli._resolved_company("Nvidia", mock=False, config={}, host_ticker=True) |
| 1312 | |
| 1313 | assert company["company"] == "Nvidia" |
| 1314 | assert company["company_site"] |
| 1315 | assert not {"ticker", "exchange", "ticker_candidates", "ticker_source"} & set(company) |
| 1316 | assert wikidata.calls |
| 1317 | assert not _wikidata_asked_for_a_listing(wikidata) |
| 1318 | assert fake.calls == [] |
| 1319 | |
| 1320 | |
| 1321 | def test_host_ticker_never_reaches_the_yahoo_backup_when_wikidata_fails(monkeypatch): |
| 1322 | fake = _install(monkeypatch, charts=HOST_CHARTS, matches=HOST_MATCHES) |
| 1323 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata(error=RATE_LIMITED)) |
| 1324 | |
| 1325 | company = cli._resolved_company("Tesla", mock=False, config={}, host_ticker=True) |
| 1326 | |
| 1327 | assert company == {} |
| 1328 | assert fake.calls == [] |
| 1329 | |
| 1330 | |
| 1331 | def _host_run(monkeypatch, tmp_path, ticker, *, charts, matches=HOST_MATCHES, **kwargs): |
| 1332 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 1333 | |
| 1334 | fake = FakeCli(charts=charts, matches=matches) |
| 1335 | observed = run_competitor_cli( |
| 1336 | monkeypatch, tmp_path, market_cli=fake, competitors_list=None, |
| 1337 | expected_topics=frozenset({"MainBrand"}), |
| 1338 | args=["--ticker", ticker, *kwargs.pop("args", [])], **kwargs, |
| 1339 | ) |
| 1340 | return observed, fake |
| 1341 | |
| 1342 | |
| 1343 | _JUNE_HOST_CHARTS = { |
| 1344 | "NVDA": _chart("NVDA", _JUNE, name="NVIDIA Corporation"), |
| 1345 | "STRS": _chart("STRS", _JUNE, name="Stratus Properties Inc."), |
| 1346 | "MAIN": _chart("MAIN", _JUNE, name="MainBrand, Inc."), |
| 1347 | "^GSPC": _chart("^GSPC", _JUNE), |
| 1348 | } |
| 1349 | |
| 1350 | |
| 1351 | def test_engine_run_uses_the_host_ticker_and_not_the_wikidata_one(monkeypatch, tmp_path): |
| 1352 | observed, fake = _host_run( |
| 1353 | monkeypatch, tmp_path, "NVDA:Nvidia", charts=_JUNE_HOST_CHARTS, |
| 1354 | companies={"MainBrand": { |
| 1355 | "company": "MainBrand Inc.", "company_site": "https://mainbrand.example/", |
| 1356 | }}, |
| 1357 | ) |
| 1358 | |
| 1359 | report = observed.reports["MainBrand"] |
| 1360 | assert report.artifacts["yahoo_finance"]["symbol"] == "NVDA" |
| 1361 | resolved = report.artifacts["resolved"] |
| 1362 | assert (resolved["ticker"], resolved["tickers"], resolved["ticker_source"]) == ("NVDA", ["NVDA"], "host") |
| 1363 | # Wikidata still names the company, and is asked for no listing. |
| 1364 | assert resolved["company"] == "MainBrand Inc." |
| 1365 | assert resolved["company_site"] == "https://mainbrand.example/" |
| 1366 | observed.company_resolver.assert_called_once_with( |
| 1367 | "MainBrand", listing=False, names=True, config=ANY, |
| 1368 | ) |
| 1369 | assert fake.charted() == ["NVDA", "^GSPC"] |
| 1370 | |
| 1371 | |
| 1372 | def test_engine_run_fills_the_company_from_the_host_when_wikidata_names_none(monkeypatch, tmp_path): |
| 1373 | observed, _fake = _host_run(monkeypatch, tmp_path, "NVDA:Nvidia", charts=_JUNE_HOST_CHARTS) |
| 1374 | |
| 1375 | assert observed.reports["MainBrand"].artifacts["resolved"]["company"] == "Nvidia" |
| 1376 | |
| 1377 | |
| 1378 | def test_engine_run_with_every_host_ticker_rejected_prints_nothing_and_falls_back_to_nothing( |
| 1379 | monkeypatch, tmp_path, |
| 1380 | ): |
| 1381 | observed, fake = _host_run( |
| 1382 | monkeypatch, tmp_path, "STRS:Stripe", charts=_JUNE_HOST_CHARTS, |
| 1383 | matches={**HOST_MATCHES, "MainBrand": _named(("MAIN", "MainBrand, Inc.", "Equity"))}, |
| 1384 | # What Wikidata would say with its listing; the run must not use it. |
| 1385 | companies={"MainBrand": company_resolve.FailedLookup()}, |
| 1386 | ) |
| 1387 | |
| 1388 | report = observed.reports["MainBrand"] |
| 1389 | assert "yahoo_finance" not in report.artifacts |
| 1390 | assert _footer(report) == [] |
| 1391 | resolved = report.artifacts["resolved"] |
| 1392 | assert not {"ticker", "tickers", "company", "company_source"} & set(resolved) |
| 1393 | assert resolved["ticker_source"] == "host" |
| 1394 | assert resolved["ticker_rejected"] == [{ |
| 1395 | "pair": "STRS:Stripe", |
| 1396 | "reason": "Yahoo lists no stock for 'Stripe'; STRS is Stratus Properties Inc.", |
| 1397 | }] |
| 1398 | observed.company_resolver.assert_called_once_with( |
| 1399 | "MainBrand", listing=False, names=True, config=ANY, |
| 1400 | ) |
| 1401 | # No symbol search for the topic: the Yahoo backup is not a fallback here. |
| 1402 | assert [cmd[3] for cmd in fake.calls if cmd[1] == "autocomplete"] == ["Stripe"] |
| 1403 | assert fake.charted() == ["STRS"] |
| 1404 | |
| 1405 | |
| 1406 | def test_engine_run_without_the_flag_resolves_as_before(monkeypatch, tmp_path): |
| 1407 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 1408 | |
| 1409 | fake = FakeCli(charts=_JUNE_CHARTS) |
| 1410 | observed = run_competitor_cli( |
| 1411 | monkeypatch, tmp_path, market_cli=fake, competitors_list=None, |
| 1412 | expected_topics=frozenset({"MainBrand"}), companies=_LISTED, |
| 1413 | ) |
| 1414 | |
| 1415 | observed.company_resolver.assert_called_once_with("MainBrand", names=True, config=ANY) |
| 1416 | resolved = observed.reports["MainBrand"].artifacts["resolved"] |
| 1417 | assert (resolved["ticker"], resolved["ticker_source"]) == ("MAIN", "wikidata") |
| 1418 | assert "tickers" not in resolved and "ticker_rejected" not in resolved |
| 1419 | assert observed.reports["MainBrand"].artifacts["yahoo_finance"]["symbol"] == "MAIN" |
| 1420 | |
| 1421 | |
| 1422 | def test_engine_run_with_an_empty_ticker_flag_resolves_as_before(monkeypatch, tmp_path): |
| 1423 | observed, _fake = _host_run(monkeypatch, tmp_path, " ", charts=_JUNE_CHARTS, companies=_LISTED) |
| 1424 | |
| 1425 | observed.company_resolver.assert_called_once_with("MainBrand", names=True, config=ANY) |
| 1426 | assert observed.reports["MainBrand"].artifacts["yahoo_finance"]["symbol"] == "MAIN" |
| 1427 | |
| 1428 | |
| 1429 | def test_mock_run_with_a_host_ticker_never_starts_the_cli(monkeypatch, tmp_path): |
| 1430 | observed, fake = _host_run(monkeypatch, tmp_path, "NVDA:Nvidia", charts=_JUNE_HOST_CHARTS, args=["--mock"]) |
| 1431 | |
| 1432 | assert fake.calls == [] |
| 1433 | assert observed.company_resolver.call_count == 0 |
| 1434 | assert "yahoo_finance" not in observed.reports["MainBrand"].artifacts |
| 1435 | assert "ticker_source" not in observed.reports["MainBrand"].artifacts["resolved"] |
| 1436 | |
| 1437 | |
| 1438 | def test_engine_run_with_yahoo_finance_excluded_checks_no_host_ticker(monkeypatch, tmp_path): |
| 1439 | observed, fake = _host_run( |
| 1440 | monkeypatch, tmp_path, "NVDA:Nvidia", charts=_JUNE_HOST_CHARTS, |
| 1441 | config={"EXCLUDE_SOURCES": "yahoo_finance"}, |
| 1442 | ) |
| 1443 | |
| 1444 | assert fake.calls == [] |
| 1445 | report = observed.reports["MainBrand"] |
| 1446 | assert "yahoo_finance" not in report.artifacts and "yahoo_finance" not in report.source_status |
| 1447 | assert "ticker" not in report.artifacts["resolved"] |
| 1448 | |
| 1449 | |
| 1450 | def test_engine_run_without_the_binary_checks_no_host_ticker(monkeypatch, tmp_path): |
| 1451 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 1452 | |
| 1453 | observed = run_competitor_cli( |
| 1454 | monkeypatch, tmp_path, competitors_list=None, expected_topics=frozenset({"MainBrand"}), |
| 1455 | args=["--ticker", "NVDA:Nvidia"], |
| 1456 | ) |
| 1457 | |
| 1458 | report = observed.reports["MainBrand"] |
| 1459 | assert "yahoo_finance" not in report.artifacts |
| 1460 | assert report.source_status["yahoo_finance"].state == health.SKIPPED_UNCONFIGURED |
| 1461 | assert "install:" in report.source_status["yahoo_finance"].detail |
| 1462 | assert "ticker" not in report.artifacts["resolved"] |
| 1463 | |
| 1464 | |
| 1465 | def test_comparison_gives_the_host_ticker_to_the_main_entity_only(monkeypatch, tmp_path): |
| 1466 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 1467 | |
| 1468 | fake = FakeCli( |
| 1469 | charts={**_JUNE_HOST_CHARTS, "PEER": _chart("PEER", _JUNE)}, matches=HOST_MATCHES, |
| 1470 | ) |
| 1471 | observed = run_competitor_cli( |
| 1472 | monkeypatch, tmp_path, market_cli=fake, companies=_LISTED, args=["--ticker", "NVDA:Nvidia"], |
| 1473 | ) |
| 1474 | |
| 1475 | assert observed.reports["MainBrand"].artifacts["yahoo_finance"]["symbol"] == "NVDA" |
| 1476 | assert observed.reports["PeerOne"].artifacts["yahoo_finance"]["symbol"] == "PEER" |
| 1477 | assert observed.reports["PeerOne"].artifacts["resolved"]["ticker_source"] == "wikidata" |
| 1478 | |
| 1479 | |
| 1480 | # The host's instruction and the byte budgets it has to fit. |
| 1481 | |
| 1482 | |
| 1483 | def test_runbook_tells_the_host_to_find_the_ticker_through_the_isolated_search(): |
| 1484 | from tests.skill_contract import SKILL_ROOT, reference_text |
| 1485 | |
| 1486 | runbook = reference_text("research-runbook") |
| 1487 | section = runbook.split("### Section B: Resolve the Stock Ticker", 1)[1].split("\n### ", 1)[0] |
| 1488 | assert '--ticker="SYMBOL:Company"' in section |
| 1489 | assert "isolated web search" in section.lower() |
| 1490 | assert "listed and trading" in section |
| 1491 | assert "pass nothing" in section |
| 1492 | # Next to the X handle section, in the checklist and in the engine's flag list. |
| 1493 | assert runbook.index("### Section A: Resolve X Handles") < runbook.index("### Section B: Resolve the Stock Ticker") |
| 1494 | assert runbook.index("### Section B: Resolve the Stock Ticker") < runbook.index("### Step 0.5b") |
| 1495 | checklist = runbook.split("| Flag | Resolved in | Applies when |", 1)[1].split("**Checkpoint", 1)[0] |
| 1496 | assert "`--ticker=" in checklist |
| 1497 | flags = runbook.split("Add these targeting flags to that engine command", 1)[1].split("**If you skipped", 1)[0] |
| 1498 | assert "`--ticker=" in flags |
| 1499 | |
| 1500 | root = (SKILL_ROOT / "SKILL.md").read_bytes() |
| 1501 | assert len(root) <= 32_000 |
| 1502 | names = ("runtime", "setup-wizard", "research-runbook", "synthesis") |
| 1503 | total = len(root) + sum(len(reference_text(name).encode("utf-8")) for name in names) |
| 1504 | assert total <= 191_500 |
| 1505 |