| 1 | """Topic to company, site and ticker through Wikidata, replayed offline. |
| 2 | |
| 3 | The fixture holds real Wikidata responses trimmed to the statements the |
| 4 | resolver reads. A row with ``edit`` changes one recorded entity to cover a |
| 5 | shape the live data did not have on the day it was recorded. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import copy |
| 11 | import json |
| 12 | import re |
| 13 | from pathlib import Path |
| 14 | from unittest import mock |
| 15 | |
| 16 | import pytest |
| 17 | |
| 18 | from lib import company_resolve, http, render, schema |
| 19 | |
| 20 | FIXTURE = json.loads( |
| 21 | (Path(__file__).parent / "fixtures" / "wikidata_company_resolve.json").read_text( |
| 22 | encoding="utf-8" |
| 23 | ) |
| 24 | ) |
| 25 | |
| 26 | NVIDIA = "Q182477" |
| 27 | ALPHABET = "Q20800404" |
| 28 | TOYOTA = "Q53268" |
| 29 | NASDAQ = "Q82059" |
| 30 | TOKYO = "Q217475" |
| 31 | AUTOMOBILE_MANUFACTURER = "Q786820" |
| 32 | GOOGLE = "Q95" |
| 33 | |
| 34 | |
| 35 | class FakeWikidata: |
| 36 | """Stands in for ``http.get`` and answers from the recorded fixture.""" |
| 37 | |
| 38 | def __init__( |
| 39 | self, entities: dict | None = None, error: Exception | None = None, |
| 40 | search: dict | None = None, |
| 41 | ): |
| 42 | self.entities = {**FIXTURE["entities"], **(entities or {})} |
| 43 | self.search = {**FIXTURE["search"], **(search or {})} |
| 44 | self.error = error |
| 45 | self.calls: list[dict] = [] |
| 46 | |
| 47 | def __call__(self, url, headers=None, **kwargs): |
| 48 | params = kwargs.get("params") or {} |
| 49 | self.calls.append({"url": url, "headers": headers, **kwargs}) |
| 50 | if self.error is not None: |
| 51 | raise self.error |
| 52 | action = params.get("action") |
| 53 | if action == "wbsearchentities": |
| 54 | return self.search.get(params["search"], {"search": [], "success": 1}) |
| 55 | if action == "wbgetentities": |
| 56 | return { |
| 57 | "entities": { |
| 58 | qid: copy.deepcopy(self.entities.get(qid, {"id": qid, "missing": ""})) |
| 59 | for qid in params["ids"].split("|") |
| 60 | }, |
| 61 | "success": 1, |
| 62 | } |
| 63 | if action == "query": |
| 64 | person = params["srsearch"].rsplit("=", 1)[1] |
| 65 | return FIXTURE["chief_executive_of"][person] |
| 66 | raise AssertionError(f"unexpected Wikidata request: {params}") |
| 67 | |
| 68 | |
| 69 | def _resolve( |
| 70 | monkeypatch, topic: str, *, names: bool = False, **fake_kwargs, |
| 71 | ) -> tuple[dict, FakeWikidata]: |
| 72 | fake = FakeWikidata(**fake_kwargs) |
| 73 | monkeypatch.setattr(company_resolve.http, "get", fake) |
| 74 | return company_resolve.resolve_company(topic, names=names), fake |
| 75 | |
| 76 | |
| 77 | def _label_requests(fake: FakeWikidata) -> list[list[str]]: |
| 78 | """The ids of each request that asked for labels only.""" |
| 79 | return [ |
| 80 | call["params"]["ids"].split("|") |
| 81 | for call in fake.calls |
| 82 | if call["params"].get("props") == "labels" |
| 83 | ] |
| 84 | |
| 85 | |
| 86 | def _edited(qid: str, change) -> dict: |
| 87 | entity = copy.deepcopy(FIXTURE["entities"][qid]) |
| 88 | change(entity) |
| 89 | return {qid: entity} |
| 90 | |
| 91 | |
| 92 | def _listing(entity: dict, ticker: str) -> dict: |
| 93 | for statement in entity["claims"]["P414"]: |
| 94 | if statement["qualifiers"]["P249"][0]["datavalue"]["value"] == ticker: |
| 95 | return statement |
| 96 | raise AssertionError(f"no {ticker} listing in the fixture") |
| 97 | |
| 98 | |
| 99 | def _prefer(ticker: str, exchange: str | None = None): |
| 100 | def change(entity: dict) -> None: |
| 101 | for statement in entity["claims"]["P414"]: |
| 102 | listed_on = statement["mainsnak"]["datavalue"]["value"]["id"] |
| 103 | if statement["qualifiers"]["P249"][0]["datavalue"]["value"] == ticker and ( |
| 104 | exchange is None or listed_on == exchange |
| 105 | ): |
| 106 | statement["rank"] = "preferred" |
| 107 | return |
| 108 | raise AssertionError(f"no {ticker} listing in the fixture") |
| 109 | |
| 110 | return change |
| 111 | |
| 112 | |
| 113 | def _end_listing(ticker: str): |
| 114 | def change(entity: dict) -> None: |
| 115 | _listing(entity, ticker)["qualifiers"]["P582"] = [{ |
| 116 | "snaktype": "value", |
| 117 | "property": "P582", |
| 118 | "datavalue": { |
| 119 | "value": { |
| 120 | "time": "+2024-01-01T00:00:00Z", "timezone": 0, "before": 0, |
| 121 | "after": 0, "precision": 11, |
| 122 | "calendarmodel": "http://www.wikidata.org/entity/Q1985727", |
| 123 | }, |
| 124 | "type": "time", |
| 125 | }, |
| 126 | }] |
| 127 | |
| 128 | return change |
| 129 | |
| 130 | |
| 131 | def _only_instance_of(class_id: str): |
| 132 | def change(entity: dict) -> None: |
| 133 | template = entity["claims"]["P31"][0] |
| 134 | template["mainsnak"]["datavalue"]["value"] = { |
| 135 | "entity-type": "item", "numeric-id": int(class_id[1:]), "id": class_id, |
| 136 | } |
| 137 | entity["claims"]["P31"] = [template] |
| 138 | |
| 139 | return change |
| 140 | |
| 141 | |
| 142 | NVIDIA_RESULT = { |
| 143 | "company": "Nvidia", |
| 144 | "company_site": "https://www.nvidia.com/", |
| 145 | "ticker": "NVDA", |
| 146 | "exchange": "Nasdaq", |
| 147 | } |
| 148 | |
| 149 | # (topic, edited entities, expected result) |
| 150 | CASES = [ |
| 151 | # Company and ticker. |
| 152 | pytest.param("Nvidia", None, NVIDIA_RESULT, id="nvidia"), |
| 153 | pytest.param( |
| 154 | "Jensen Huang", None, {**NVIDIA_RESULT, "company_via_person": True}, |
| 155 | id="jensen-huang-leads-nvidia", |
| 156 | ), |
| 157 | pytest.param( |
| 158 | "Apple", None, |
| 159 | # Apple's regional sites carry no preferred one but share one host, |
| 160 | # so the site is that host's root. |
| 161 | { |
| 162 | "company": "Apple Inc.", "company_site": "https://apple.com/", |
| 163 | "ticker": "AAPL", "exchange": "Nasdaq", |
| 164 | }, |
| 165 | id="apple-ignores-its-ended-tokyo-listing", |
| 166 | ), |
| 167 | # Recorded Tesla data lists four exchanges and marks none as primary, so |
| 168 | # the listings are only candidates. |
| 169 | pytest.param( |
| 170 | "Tesla", None, |
| 171 | { |
| 172 | "company": "Tesla", "company_site": "https://www.tesla.com/", |
| 173 | "ticker_candidates": ["TSLA", "TL0", "0R0X"], |
| 174 | }, |
| 175 | id="tesla-four-exchanges-none-primary", |
| 176 | ), |
| 177 | # Company with no ticker. |
| 178 | pytest.param( |
| 179 | "Stripe", None, |
| 180 | {"company": "Stripe", "company_site": "https://stripe.com/"}, |
| 181 | id="stripe-private", |
| 182 | ), |
| 183 | pytest.param( |
| 184 | "OpenAI", None, |
| 185 | {"company": "OpenAI", "company_site": "https://openai.com/"}, |
| 186 | id="openai-private", |
| 187 | ), |
| 188 | pytest.param( |
| 189 | "Anthropic", None, |
| 190 | {"company": "Anthropic", "company_site": "https://www.anthropic.com/"}, |
| 191 | id="anthropic-private", |
| 192 | ), |
| 193 | pytest.param( |
| 194 | "Nvidia", _edited(NVIDIA, _end_listing("NVDA")), |
| 195 | {"company": "Nvidia", "company_site": "https://www.nvidia.com/"}, |
| 196 | id="delisted-listing-has-an-end-time", |
| 197 | ), |
| 198 | pytest.param( |
| 199 | "Patrick Collison", None, |
| 200 | { |
| 201 | "company": "Stripe", "company_site": "https://stripe.com/", |
| 202 | "company_via_person": True, |
| 203 | }, |
| 204 | id="person-leads-a-private-company", |
| 205 | ), |
| 206 | # Nothing at all. |
| 207 | pytest.param("Kanye West", None, {}, id="kanye-west"), |
| 208 | pytest.param("Taylor Swift", None, {}, id="taylor-swift"), |
| 209 | pytest.param("Rust", None, {}, id="rust-programming-language"), |
| 210 | pytest.param("Sundar Pichai", None, {}, id="person-leads-two-organizations"), |
| 211 | # Two share classes on one exchange. |
| 212 | pytest.param( |
| 213 | "Alphabet", _edited(ALPHABET, _prefer("GOOGL")), |
| 214 | { |
| 215 | "company": "Alphabet Inc.", "company_site": "https://abc.xyz/", |
| 216 | "ticker": "GOOGL", "exchange": "Nasdaq", |
| 217 | }, |
| 218 | id="alphabet-class-marked-primary", |
| 219 | ), |
| 220 | pytest.param( |
| 221 | "Alphabet", None, |
| 222 | { |
| 223 | "company": "Alphabet Inc.", "company_site": "https://abc.xyz/", |
| 224 | "ticker_candidates": ["GOOG", "GOOGL"], |
| 225 | }, |
| 226 | id="alphabet-no-class-marked", |
| 227 | ), |
| 228 | # Listings on several exchanges. |
| 229 | pytest.param( |
| 230 | "Toyota", _edited(TOYOTA, _prefer("7203", TOKYO)), |
| 231 | { |
| 232 | "company": "Toyota", "company_site": "https://global.toyota", |
| 233 | "ticker": "7203", "exchange": "Tokyo Stock Exchange", |
| 234 | }, |
| 235 | id="toyota-exchange-marked-primary", |
| 236 | ), |
| 237 | pytest.param( |
| 238 | "Toyota", None, |
| 239 | { |
| 240 | "company": "Toyota", "company_site": "https://global.toyota", |
| 241 | "ticker_candidates": ["7203", "TYT", "TM"], |
| 242 | }, |
| 243 | id="toyota-no-exchange-marked", |
| 244 | ), |
| 245 | # An organization typed only by a kind of enterprise. |
| 246 | pytest.param( |
| 247 | "Toyota", _edited(TOYOTA, _only_instance_of(AUTOMOBILE_MANUFACTURER)), |
| 248 | { |
| 249 | "company": "Toyota", "company_site": "https://global.toyota", |
| 250 | "ticker_candidates": ["7203", "TYT", "TM"], |
| 251 | }, |
| 252 | id="typed-as-a-subclass-of-enterprise", |
| 253 | ), |
| 254 | ] |
| 255 | |
| 256 | |
| 257 | @pytest.mark.parametrize("topic,entities,expected", CASES) |
| 258 | def test_fixture_table(monkeypatch, topic, entities, expected): |
| 259 | result, fake = _resolve(monkeypatch, topic, entities=entities) |
| 260 | |
| 261 | # Names are not asked for here; they are covered by their own tests below. |
| 262 | assert result == expected |
| 263 | assert 1 <= len(fake.calls) <= 5 |
| 264 | for call in fake.calls: |
| 265 | assert call["url"] == company_resolve.WIKIDATA_API |
| 266 | assert call["timeout"] == 5 |
| 267 | assert call["retries"] == 1 |
| 268 | |
| 269 | |
| 270 | # The record's one own name, "Google holding", is a nickname without a legal |
| 271 | # designator, so Alphabet has no own names to return. |
| 272 | ALPHABET_OWN_NAMES: list[str] = [] |
| 273 | # Alphabet's twelve current subsidiaries whose labels can be told from a |
| 274 | # stranger's. GV is two letters and Fitbit's statement is deprecated. |
| 275 | ALPHABET_SUBSIDIARY_NAMES = [ |
| 276 | "Google", "X Development", "Calico", "Google Nest", "Google Fiber", |
| 277 | "Google Ireland Holdings Unlimited Company", "Loon", "Wing", "Owlchemy Labs", |
| 278 | "Waymo", "Waymo Holding", "XXVI Holdings", |
| 279 | ] |
| 280 | |
| 281 | # topic -> the exact names from the recorded data: own names that could be a |
| 282 | # legal filing name, then the labels of subsidiaries and owned entities. |
| 283 | COMPANY_NAMES = { |
| 284 | "Alphabet": ALPHABET_OWN_NAMES + ALPHABET_SUBSIDIARY_NAMES, |
| 285 | "Microsoft": [ |
| 286 | "Xbox Game Studios", "Avanade", "Lionhead Studios", "Rare Ltd.", "Ensemble Studios", |
| 287 | "ProClarity", "Danger, Inc.", "BigPark", "Games for Windows", |
| 288 | ], |
| 289 | "IBM": [ |
| 290 | "International Business Machines Corporation", |
| 291 | "SoftLayer", "Internet Security Systems", "Lotus Software", "Rational Software", |
| 292 | "Companhia IBM Portuguesa", "Telelogic", |
| 293 | ], |
| 294 | # "Stripe, LLC" and "Stripe, Inc." are the company's name and a designator. |
| 295 | "Stripe": ["TaxJar", "Lemon Squeezy"], |
| 296 | } |
| 297 | |
| 298 | # Names the records list that must not come back, and why. |
| 299 | REJECTED_NAMES = { |
| 300 | "Alphabet": [ |
| 301 | "Alphabet", # one word |
| 302 | "Alphabet company", "Alphabet Incorporated", "Alphabet, Inc.", # name and designator |
| 303 | "abc.xyz", # a domain |
| 304 | "GV", # a subsidiary label shorter than three characters |
| 305 | ], |
| 306 | "Microsoft": [ |
| 307 | "Microsoft Corporation", "Microsoft Corp.", # name and designator |
| 308 | "microsoft.com", # a domain |
| 309 | "MS", "MSFT", # one word |
| 310 | # Subsidiaries whose label extends the company's name. |
| 311 | "Microsoft Algeria", "Microsoft India R & D", "Microsoft Mobile", "Microsoft Store", |
| 312 | ], |
| 313 | "IBM": [ |
| 314 | "IBM Corp.", "IBM Corporation", # name and designator |
| 315 | "18M", "I.B.M.", # one word |
| 316 | "ibm.com", # a domain |
| 317 | "International Business Machines Corporation (Armonk, NY)", # a parenthetical variant |
| 318 | "International Business Machines", # the official name without its designator |
| 319 | "IBM India Private Limited", "IBM Denmark", "IBM Canada", # extend the company's name |
| 320 | ], |
| 321 | } |
| 322 | |
| 323 | _DOMAIN = re.compile(r"(?:[\w-]+\.)+[a-z]{2,}", re.IGNORECASE) |
| 324 | |
| 325 | |
| 326 | def _current_subsidiary_ids(qid: str) -> list[str]: |
| 327 | ids = [ |
| 328 | statement["mainsnak"]["datavalue"]["value"]["id"] |
| 329 | for prop in ("P355", "P1830") |
| 330 | for statement in FIXTURE["entities"][qid]["claims"].get(prop, []) |
| 331 | if statement["rank"] != "deprecated" and "P582" not in statement.get("qualifiers", {}) |
| 332 | ] |
| 333 | return list(dict.fromkeys(ids)) |
| 334 | |
| 335 | |
| 336 | def _subsidiary_label_requests(fake: FakeWikidata) -> list[list[str]]: |
| 337 | exchanges = ([NASDAQ], ["Q13677"]) |
| 338 | return [ids for ids in _label_requests(fake) if ids not in exchanges] |
| 339 | |
| 340 | |
| 341 | @pytest.mark.parametrize("topic,names", COMPANY_NAMES.items(), ids=list(COMPANY_NAMES)) |
| 342 | def test_company_names_are_filing_names_then_subsidiaries(monkeypatch, topic, names): |
| 343 | result, fake = _resolve(monkeypatch, topic, names=True) |
| 344 | |
| 345 | assert result["company_names"] == names |
| 346 | assert result["company"] not in names |
| 347 | assert len(names) == len({name.casefold() for name in names}) <= 15 |
| 348 | # One request asks for the label of every current subsidiary, so a label |
| 349 | # that is filtered out does not cost a later one its place. |
| 350 | (asked,) = _subsidiary_label_requests(fake) |
| 351 | assert asked == _current_subsidiary_ids(result_id(topic)) |
| 352 | assert len(asked) <= 50 |
| 353 | for call in fake.calls: |
| 354 | assert call["timeout"] == 5 |
| 355 | assert call["retries"] == 1 |
| 356 | |
| 357 | |
| 358 | def result_id(topic: str) -> str: |
| 359 | return FIXTURE["search"][topic]["search"][0]["id"] |
| 360 | |
| 361 | |
| 362 | @pytest.mark.parametrize("topic", list(REJECTED_NAMES)) |
| 363 | def test_no_name_is_a_short_token_a_domain_or_the_company_again(monkeypatch, topic): |
| 364 | result, _fake = _resolve(monkeypatch, topic, names=True) |
| 365 | names = result["company_names"] |
| 366 | |
| 367 | assert not set(REJECTED_NAMES[topic]) & set(names) |
| 368 | company = result["company"].casefold().removesuffix(" inc.") |
| 369 | for name in names: |
| 370 | assert len(re.sub(r"[\W_]", "", name)) >= 3 |
| 371 | assert name not in ("MS", "GV", "18M") |
| 372 | assert not _DOMAIN.fullmatch(name) |
| 373 | assert "(" not in name |
| 374 | assert not name.casefold().startswith(company + " ") |
| 375 | |
| 376 | |
| 377 | def test_alphabet_names_include_google_and_waymo(monkeypatch): |
| 378 | result, _fake = _resolve(monkeypatch, "Alphabet", names=True) |
| 379 | |
| 380 | assert {"Google", "Waymo"} <= set(result["company_names"]) |
| 381 | assert len(_current_subsidiary_ids(ALPHABET)) == 13 |
| 382 | |
| 383 | |
| 384 | def test_names_are_not_read_unless_asked_for(monkeypatch): |
| 385 | result, fake = _resolve(monkeypatch, "Alphabet") |
| 386 | |
| 387 | assert result == { |
| 388 | "company": "Alphabet Inc.", "company_site": "https://abc.xyz/", |
| 389 | "ticker_candidates": ["GOOG", "GOOGL"], |
| 390 | } |
| 391 | assert "company_names" not in result |
| 392 | assert _label_requests(fake) == [] |
| 393 | assert len(fake.calls) == 2 |
| 394 | |
| 395 | |
| 396 | def test_ibm_keeps_every_key_it_had_beside_its_names(monkeypatch): |
| 397 | result, _fake = _resolve(monkeypatch, "IBM", names=True) |
| 398 | |
| 399 | assert result == { |
| 400 | "company": "IBM", "company_site": "https://www.ibm.com/", |
| 401 | "ticker": "IBM", "exchange": "New York Stock Exchange", |
| 402 | "company_names": COMPANY_NAMES["IBM"], |
| 403 | } |
| 404 | |
| 405 | |
| 406 | def test_a_company_whose_names_add_nothing_has_no_names_key(monkeypatch): |
| 407 | """Anthropic lists "Anthropic, PBC" and "Anthropic PBC" and no subsidiary.""" |
| 408 | result, fake = _resolve(monkeypatch, "Anthropic", names=True) |
| 409 | |
| 410 | assert result == {"company": "Anthropic", "company_site": "https://www.anthropic.com/"} |
| 411 | assert _label_requests(fake) == [] |
| 412 | assert len(fake.calls) == 2 |
| 413 | |
| 414 | |
| 415 | def test_at_most_three_own_names_are_kept(monkeypatch): |
| 416 | def more_aliases(entity: dict) -> None: |
| 417 | entity["aliases"]["en"] = [ |
| 418 | {"language": "en", "value": value} |
| 419 | for value in ( |
| 420 | "Acme Holdings Corporation", "Acme Widgets Inc.", |
| 421 | "Acme Industries LLC", "Acme Global Ltd.", |
| 422 | ) |
| 423 | ] + entity["aliases"]["en"] |
| 424 | |
| 425 | result, _fake = _resolve( |
| 426 | monkeypatch, "IBM", names=True, entities=_edited("Q37156", more_aliases), |
| 427 | ) |
| 428 | |
| 429 | # The official name and two aliases fill the three places; the two further |
| 430 | # aliases that carry a designator are cut and the subsidiaries are untouched. |
| 431 | assert result["company_names"] == [ |
| 432 | "International Business Machines Corporation", |
| 433 | "Acme Holdings Corporation", "Acme Widgets Inc.", |
| 434 | ] + COMPANY_NAMES["IBM"][1:] |
| 435 | |
| 436 | |
| 437 | def test_a_nickname_without_a_legal_designator_is_not_an_own_name(monkeypatch): |
| 438 | """IBM lists "Big Blue" as an alias; only names that end in a designator stay.""" |
| 439 | recorded = FIXTURE["entities"]["Q37156"]["aliases"]["mul"] |
| 440 | assert "Big Blue" in {alias["value"] for alias in recorded} |
| 441 | |
| 442 | result, _fake = _resolve(monkeypatch, "IBM", names=True) |
| 443 | |
| 444 | names = result["company_names"] |
| 445 | assert "Big Blue" not in names |
| 446 | assert "International Business Machines Corporation" in names |
| 447 | |
| 448 | |
| 449 | def test_at_most_twelve_subsidiary_names_are_kept(monkeypatch): |
| 450 | """With a label that passes in GV's place Alphabet has thirteen.""" |
| 451 | longer_label = {"Q2591662": {"id": "Q2591662", "labels": {"en": {"language": "en", "value": "Example Ventures"}}}} |
| 452 | |
| 453 | result, _fake = _resolve(monkeypatch, "Alphabet", names=True, entities=longer_label) |
| 454 | |
| 455 | expected = ALPHABET_SUBSIDIARY_NAMES[:2] + ["Example Ventures"] + ALPHABET_SUBSIDIARY_NAMES[2:] |
| 456 | assert result["company_names"] == ALPHABET_OWN_NAMES + expected[:12] |
| 457 | assert "XXVI Holdings" not in result["company_names"] |
| 458 | assert len(result["company_names"]) <= 15 |
| 459 | |
| 460 | |
| 461 | def test_the_label_request_never_asks_for_more_than_fifty_ids(monkeypatch): |
| 462 | def sixty_more(entity: dict) -> None: |
| 463 | template = entity["claims"]["P355"][0] |
| 464 | for number in range(900000001, 900000061): |
| 465 | statement = copy.deepcopy(template) |
| 466 | statement["mainsnak"]["datavalue"]["value"] = { |
| 467 | "entity-type": "item", "numeric-id": number, "id": f"Q{number}", |
| 468 | } |
| 469 | entity["claims"]["P355"].append(statement) |
| 470 | |
| 471 | monkeypatch.setattr(company_resolve.log, "source_log", mock.Mock()) |
| 472 | result, fake = _resolve( |
| 473 | monkeypatch, "Alphabet", names=True, entities=_edited(ALPHABET, sixty_more), |
| 474 | ) |
| 475 | |
| 476 | (asked,) = _subsidiary_label_requests(fake) |
| 477 | assert len(asked) == 50 |
| 478 | assert asked[:13] == _current_subsidiary_ids(ALPHABET) |
| 479 | assert result["company"] == "Alphabet Inc." |
| 480 | |
| 481 | |
| 482 | def test_a_subsidiary_that_ended_or_is_deprecated_is_not_a_name(monkeypatch): |
| 483 | def end_google(entity: dict) -> None: |
| 484 | google = entity["claims"]["P355"][0] |
| 485 | assert google["mainsnak"]["datavalue"]["value"]["id"] == GOOGLE |
| 486 | google["qualifiers"] = {"P582": [{"snaktype": "value", "property": "P582"}]} |
| 487 | |
| 488 | result, fake = _resolve( |
| 489 | monkeypatch, "Alphabet", names=True, entities=_edited(ALPHABET, end_google), |
| 490 | ) |
| 491 | |
| 492 | assert result["company_names"] == ALPHABET_OWN_NAMES + ALPHABET_SUBSIDIARY_NAMES[1:] |
| 493 | # Fitbit is recorded as a deprecated subsidiary statement. |
| 494 | assert not {GOOGLE, "Q5455414"} & set(_label_requests(fake)[-1]) |
| 495 | |
| 496 | |
| 497 | @pytest.mark.parametrize( |
| 498 | "error", |
| 499 | [http.HTTPError("Request timed out"), http.HTTPError("HTTP 429: Too Many Requests", status_code=429)], |
| 500 | ) |
| 501 | def test_a_failed_label_request_keeps_the_company_without_subsidiaries(monkeypatch, error): |
| 502 | fake = FakeWikidata() |
| 503 | |
| 504 | def flaky(url, headers=None, **kwargs): |
| 505 | if GOOGLE in kwargs["params"].get("ids", "").split("|"): |
| 506 | raise error |
| 507 | return fake(url, headers, **kwargs) |
| 508 | |
| 509 | logged = mock.Mock() |
| 510 | monkeypatch.setattr(company_resolve.log, "source_log", logged) |
| 511 | monkeypatch.setattr(company_resolve.http, "get", flaky) |
| 512 | |
| 513 | result = company_resolve.resolve_company("Alphabet", names=True) |
| 514 | |
| 515 | assert not isinstance(result, company_resolve.FailedLookup) |
| 516 | assert result == { |
| 517 | "company": "Alphabet Inc.", "company_site": "https://abc.xyz/", |
| 518 | "ticker_candidates": ["GOOG", "GOOGL"], |
| 519 | } |
| 520 | assert logged.call_count == 1 |
| 521 | assert logged.call_args.kwargs == {"tty_only": False} |
| 522 | |
| 523 | |
| 524 | def test_a_subsidiary_wikidata_no_longer_has_costs_only_the_subsidiaries(monkeypatch): |
| 525 | monkeypatch.setattr(company_resolve.log, "source_log", mock.Mock()) |
| 526 | |
| 527 | result, _fake = _resolve( |
| 528 | monkeypatch, "Alphabet", names=True, |
| 529 | entities={"Q133928": {"id": "Q133928", "missing": ""}}, |
| 530 | ) |
| 531 | |
| 532 | assert not isinstance(result, company_resolve.FailedLookup) |
| 533 | # Alphabet has no own name with a designator, so nothing is left to return. |
| 534 | assert "company_names" not in result |
| 535 | |
| 536 | |
| 537 | def test_a_person_carries_the_names_of_the_company_they_lead(monkeypatch): |
| 538 | result, _fake = _resolve(monkeypatch, "Patrick Collison", names=True) |
| 539 | |
| 540 | assert result == { |
| 541 | "company": "Stripe", "company_site": "https://stripe.com/", |
| 542 | "company_via_person": True, |
| 543 | "company_names": COMPANY_NAMES["Stripe"], |
| 544 | } |
| 545 | |
| 546 | |
| 547 | def test_names_are_read_when_the_listing_is_not(monkeypatch): |
| 548 | fake = FakeWikidata() |
| 549 | monkeypatch.setattr(company_resolve.http, "get", fake) |
| 550 | |
| 551 | result = company_resolve.resolve_company("IBM", listing=False, names=True) |
| 552 | |
| 553 | assert "ticker" not in result |
| 554 | assert result["company_names"] == COMPANY_NAMES["IBM"] |
| 555 | |
| 556 | |
| 557 | @pytest.mark.parametrize( |
| 558 | "topic", |
| 559 | ["how to deploy on Fly.io", "What is Nvidia?", "best noise cancelling headphones", "nvidia stock", ""], |
| 560 | ) |
| 561 | def test_no_network_when_the_topic_is_not_company_shaped(monkeypatch, topic): |
| 562 | result, fake = _resolve(monkeypatch, topic) |
| 563 | |
| 564 | assert result == {} |
| 565 | assert fake.calls == [] |
| 566 | |
| 567 | |
| 568 | @pytest.mark.parametrize( |
| 569 | "error", |
| 570 | [ |
| 571 | http.HTTPError("Request timed out"), |
| 572 | http.HTTPError("HTTP 503: Service Unavailable", status_code=503), |
| 573 | TimeoutError("timed out"), |
| 574 | ], |
| 575 | ) |
| 576 | def test_wikidata_failure_returns_nothing_and_logs_once(monkeypatch, error): |
| 577 | logged = mock.Mock() |
| 578 | monkeypatch.setattr(company_resolve.log, "source_log", logged) |
| 579 | |
| 580 | result, fake = _resolve(monkeypatch, "Nvidia", error=error) |
| 581 | |
| 582 | assert result == {} |
| 583 | assert isinstance(result, company_resolve.FailedLookup) |
| 584 | assert len(fake.calls) == 1 |
| 585 | assert logged.call_count == 1 |
| 586 | assert logged.call_args.kwargs == {"tty_only": False} |
| 587 | assert "Nvidia" in logged.call_args.args[1] |
| 588 | |
| 589 | |
| 590 | @pytest.mark.parametrize( |
| 591 | "response", |
| 592 | [[], {"search": "not a list"}, {"search": [{"label": "Nvidia"}]}], |
| 593 | ) |
| 594 | def test_unexpected_search_shape_returns_nothing_and_logs_once(monkeypatch, response): |
| 595 | logged = mock.Mock() |
| 596 | monkeypatch.setattr(company_resolve.log, "source_log", logged) |
| 597 | monkeypatch.setattr(company_resolve.http, "get", lambda *_args, **_kwargs: response) |
| 598 | |
| 599 | result = company_resolve.resolve_company("Nvidia") |
| 600 | |
| 601 | assert result == {} |
| 602 | assert isinstance(result, company_resolve.FailedLookup) |
| 603 | assert logged.call_count == 1 |
| 604 | |
| 605 | |
| 606 | def test_http_429_is_a_failed_lookup(monkeypatch): |
| 607 | monkeypatch.setattr(company_resolve.log, "source_log", mock.Mock()) |
| 608 | |
| 609 | result, _fake = _resolve( |
| 610 | monkeypatch, "Tesla", |
| 611 | error=http.HTTPError("HTTP 429: Too Many Requests", status_code=429), |
| 612 | ) |
| 613 | |
| 614 | assert result == {} |
| 615 | assert isinstance(result, company_resolve.FailedLookup) |
| 616 | |
| 617 | |
| 618 | @pytest.mark.parametrize("topic", ["Rust", "Kanye West", "Sundar Pichai"]) |
| 619 | def test_an_answer_of_nothing_certain_is_not_a_failed_lookup(monkeypatch, topic): |
| 620 | result, fake = _resolve(monkeypatch, topic) |
| 621 | |
| 622 | assert result == {} |
| 623 | assert fake.calls |
| 624 | assert not isinstance(result, company_resolve.FailedLookup) |
| 625 | |
| 626 | |
| 627 | def test_a_topic_that_is_not_company_shaped_is_not_a_failed_lookup(monkeypatch): |
| 628 | result, fake = _resolve(monkeypatch, "how to deploy on Fly.io") |
| 629 | |
| 630 | assert fake.calls == [] |
| 631 | assert not isinstance(result, company_resolve.FailedLookup) |
| 632 | |
| 633 | |
| 634 | def test_a_failure_after_the_company_is_known_still_returns_nothing(monkeypatch): |
| 635 | """The exchange lookup is the last call; its failure must not leak a |
| 636 | half-resolved company.""" |
| 637 | fake = FakeWikidata() |
| 638 | |
| 639 | def flaky(url, headers=None, **kwargs): |
| 640 | if kwargs["params"].get("ids") == NASDAQ: |
| 641 | raise http.HTTPError("Request timed out") |
| 642 | return fake(url, headers, **kwargs) |
| 643 | |
| 644 | logged = mock.Mock() |
| 645 | monkeypatch.setattr(company_resolve.log, "source_log", logged) |
| 646 | monkeypatch.setattr(company_resolve.http, "get", flaky) |
| 647 | |
| 648 | result = company_resolve.resolve_company("Nvidia") |
| 649 | |
| 650 | assert result == {} |
| 651 | assert isinstance(result, company_resolve.FailedLookup) |
| 652 | assert logged.call_count == 1 |
| 653 | |
| 654 | |
| 655 | def test_each_entity_of_a_comparison_resolves_on_its_own(monkeypatch): |
| 656 | fake = FakeWikidata() |
| 657 | monkeypatch.setattr(company_resolve.http, "get", fake) |
| 658 | |
| 659 | results = { |
| 660 | entity: company_resolve.resolve_company(entity) |
| 661 | for entity in ("Nvidia", "Stripe", "Rust") |
| 662 | } |
| 663 | |
| 664 | assert results["Nvidia"]["ticker"] == "NVDA" |
| 665 | assert results["Stripe"] == { |
| 666 | "company": "Stripe", "company_site": "https://stripe.com/", |
| 667 | } |
| 668 | assert results["Rust"] == {} |
| 669 | |
| 670 | |
| 671 | def test_comparison_run_writes_each_entity_its_own_company(monkeypatch, tmp_path): |
| 672 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 673 | |
| 674 | companies = { |
| 675 | "MainBrand": {"company": "MainBrand Inc.", "ticker": "MAIN", "exchange": "Nasdaq"}, |
| 676 | "PeerOne": {"company": "PeerOne", "company_site": "https://peerone.example/"}, |
| 677 | } |
| 678 | observed = run_competitor_cli(monkeypatch, tmp_path, companies=companies) |
| 679 | |
| 680 | assert sorted(call.args[0] for call in observed.company_resolver.call_args_list) == [ |
| 681 | "MainBrand", "PeerOne", "PeerTwo", |
| 682 | ] |
| 683 | main = observed.reports["MainBrand"].artifacts["resolved"] |
| 684 | assert (main["company"], main["ticker"], main["exchange"]) == ("MainBrand Inc.", "MAIN", "Nasdaq") |
| 685 | assert "company_site" not in main |
| 686 | peer_one = observed.reports["PeerOne"].artifacts["resolved"] |
| 687 | assert peer_one["company"] == "PeerOne" |
| 688 | assert peer_one["company_site"] == "https://peerone.example/" |
| 689 | assert "ticker" not in peer_one |
| 690 | peer_two = observed.reports["PeerTwo"].artifacts["resolved"] |
| 691 | assert not {"company", "company_site", "ticker", "exchange"} & set(peer_two) |
| 692 | |
| 693 | |
| 694 | def test_mock_run_never_asks_for_a_company(monkeypatch, tmp_path): |
| 695 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 696 | |
| 697 | observed = run_competitor_cli(monkeypatch, tmp_path, args=["--mock"]) |
| 698 | |
| 699 | observed.company_resolver.assert_not_called() |
| 700 | |
| 701 | |
| 702 | def test_company_resolves_when_the_host_supplied_a_plan(monkeypatch, tmp_path): |
| 703 | from tests.competitor_cli_audit_helpers import run_competitor_cli |
| 704 | |
| 705 | plan = { |
| 706 | "intent": "exploration", "freshness_mode": "balanced_recent", |
| 707 | "cluster_mode": "topic", "raw_topic": "MainBrand", |
| 708 | "source_weights": {"reddit": 1.0}, |
| 709 | "subqueries": [{ |
| 710 | "label": "primary", "search_query": "MainBrand", |
| 711 | "ranking_query": "MainBrand", "sources": ["reddit"], |
| 712 | }], |
| 713 | } |
| 714 | observed = run_competitor_cli( |
| 715 | monkeypatch, tmp_path, |
| 716 | args=["--plan", json.dumps(plan), "--x-handle", "mainbrand"], |
| 717 | competitors_list=None, expected_topics={"MainBrand"}, |
| 718 | companies={"MainBrand": {"company": "MainBrand Inc.", "ticker": "MAIN"}}, |
| 719 | ) |
| 720 | |
| 721 | assert observed.calls["MainBrand"]["external_plan"] is not None |
| 722 | assert observed.reports["MainBrand"].artifacts["resolved"]["ticker"] == "MAIN" |
| 723 | |
| 724 | |
| 725 | def _report(topic: str, resolved: dict) -> schema.Report: |
| 726 | return schema.Report( |
| 727 | topic=topic, range_from="2026-06-01", range_to="2026-06-30", |
| 728 | generated_at="2026-06-30T12:00:00Z", |
| 729 | provider_runtime=schema.ProviderRuntime("local", "none", "none"), |
| 730 | query_plan=schema.QueryPlan("general", "recent", "none", topic, [], {}), |
| 731 | clusters=[], ranked_candidates=[], items_by_source={}, errors_by_source={}, |
| 732 | artifacts={"resolved": {"entity": topic, **resolved}}, |
| 733 | ) |
| 734 | |
| 735 | |
| 736 | def test_resolved_entities_row_shows_the_ticker(): |
| 737 | rows = render._render_resolved_entities_block([ |
| 738 | ("Nvidia", _report("Nvidia", {"x_handle": "nvidia", **NVIDIA_RESULT})), |
| 739 | ("Jensen Huang", _report("Jensen Huang", {**NVIDIA_RESULT, "company_via_person": True})), |
| 740 | ("Stripe", _report("Stripe", {"company": "Stripe"})), |
| 741 | ]) |
| 742 | |
| 743 | assert rows[2] == "- **Nvidia**: X @nvidia | Subs - | GitHub - | Ticker NVDA | Context: -" |
| 744 | assert rows[3] == ( |
| 745 | "- **Jensen Huang**: X - | Subs - | GitHub - | Ticker NVDA (via Nvidia) | Context: -" |
| 746 | ) |
| 747 | assert rows[4] == "- **Stripe**: X - | Subs - | GitHub - | Context: -" |
| 748 | |
| 749 | |
| 750 | def test_resolved_entities_row_marks_a_ticker_from_the_yahoo_backup(): |
| 751 | rows = render._render_resolved_entities_block([ |
| 752 | ("Tesla", _report("Tesla", { |
| 753 | "company": "Tesla", "ticker": "TSLA", "company_source": "yahoo-backup", |
| 754 | "company_lookup": "wikidata failed; yahoo backup used", |
| 755 | })), |
| 756 | ("Rust", _report("Rust", {"company_lookup": "wikidata failed; no backup match"})), |
| 757 | ]) |
| 758 | |
| 759 | assert rows[2] == "- **Tesla**: X - | Subs - | GitHub - | Ticker TSLA (Yahoo match) | Context: -" |
| 760 | assert rows[3] == "- **Rust**: X - | Subs - | GitHub - | Context: -" |
| 761 | |
| 762 | |
| 763 | @pytest.mark.parametrize( |
| 764 | ("urls", "expected"), |
| 765 | [ |
| 766 | pytest.param(["https://apple.com/de/", "https://www.apple.com/tw", "https://apple.com.cn/"], |
| 767 | "https://apple.com/", id="majority-host-root"), |
| 768 | pytest.param(["https://a.example/", "https://b.example/"], "", id="split-hosts-settle-nothing"), |
| 769 | pytest.param(["https://a.example/", "https://a.example/x", "https://b.example/", "https://c.example/"], |
| 770 | "", id="half-is-not-a-majority"), |
| 771 | pytest.param(["https://only.example/path"], "https://only.example/path", id="single-site-kept"), |
| 772 | ], |
| 773 | ) |
| 774 | def test_official_site_from_several_statements(urls, expected): |
| 775 | statements = [ |
| 776 | {"rank": "normal", "mainsnak": {"snaktype": "value", "datavalue": {"value": url}}} |
| 777 | for url in urls |
| 778 | ] |
| 779 | assert company_resolve._official_site(statements) == expected |
| 780 | |
| 781 | |
| 782 | def test_wikidata_requests_send_a_contact_user_agent(monkeypatch): |
| 783 | _, fake = _resolve(monkeypatch, "Nvidia") |
| 784 | assert fake.calls |
| 785 | for call in fake.calls: |
| 786 | agent = (call.get("headers") or {}).get("User-Agent", "") |
| 787 | assert "https://github.com/mvanhorn/last30days-skill" in agent |
| 788 | |
| 789 | |
| 790 | def test_exa_fills_an_official_site_when_wikidata_names_nothing(monkeypatch): |
| 791 | fake = FakeWikidata() |
| 792 | monkeypatch.setattr(company_resolve.http, "get", fake) |
| 793 | exa = mock.Mock(return_value=([ |
| 794 | { |
| 795 | "title": "AcmePayments | Billing APIs", |
| 796 | "url": "https://acmepayments.com/", |
| 797 | "snippet": "Billing infrastructure", |
| 798 | }, |
| 799 | { |
| 800 | "title": "AcmePayments - Crunchbase", |
| 801 | "url": "https://www.crunchbase.com/organization/acmepayments", |
| 802 | }, |
| 803 | ], {})) |
| 804 | monkeypatch.setattr(company_resolve.grounding, "exa_search", exa) |
| 805 | |
| 806 | result = company_resolve.resolve_company("AcmePayments", config={"EXA_API_KEY": "exa-key"}) |
| 807 | |
| 808 | # AcmePayments is company-shaped but not in the Wikidata fixture. |
| 809 | assert fake.calls |
| 810 | assert result == { |
| 811 | "company": "AcmePayments", |
| 812 | "company_site": "https://acmepayments.com/", |
| 813 | "company_source": "exa", |
| 814 | } |
| 815 | query, date_range, key = exa.call_args.args[:3] |
| 816 | assert "AcmePayments" in query |
| 817 | assert date_range is None |
| 818 | assert key == "exa-key" |
| 819 | # Only Exa's company index: a person or project with a matching domain |
| 820 | # (kanyewest.com, python.org) must not become a company, which would turn |
| 821 | # on the jobs and patents lanes and the company competitor index. |
| 822 | assert exa.call_args.kwargs.get("category") == "company" |
| 823 | assert "startPublishedDate" not in (exa.call_args.kwargs or {}) |
| 824 | |
| 825 | |
| 826 | def test_exa_official_site_uses_host_root_when_the_hit_is_not_the_homepage(monkeypatch): |
| 827 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 828 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 829 | {"title": "AcmePayments blog", "url": "https://www.acmepayments.com/blog/hello"}, |
| 830 | ], {}))) |
| 831 | |
| 832 | result = company_resolve.resolve_company("AcmePayments", config={"EXA_API_KEY": "exa-key"}) |
| 833 | |
| 834 | assert result["company_site"] == "https://acmepayments.com/" |
| 835 | |
| 836 | |
| 837 | def test_exa_official_site_rejects_directory_and_lookalike_hosts(monkeypatch): |
| 838 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 839 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 840 | {"title": "Crunchbase", "url": "https://www.crunchbase.com/organization/stripe"}, |
| 841 | {"title": "Stripe-like", "url": "https://stripes.com/"}, |
| 842 | {"title": "Wikipedia", "url": "https://en.wikipedia.org/wiki/Stripe,_Inc."}, |
| 843 | ], {}))) |
| 844 | |
| 845 | result = company_resolve.resolve_company("StripeCo", config={"EXA_API_KEY": "exa-key"}) |
| 846 | |
| 847 | assert result == {} |
| 848 | assert not isinstance(result, company_resolve.FailedLookup) |
| 849 | |
| 850 | |
| 851 | def test_exa_official_site_rejects_shared_prefix_on_another_company(monkeypatch): |
| 852 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 853 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 854 | {"title": "Stripe", "url": "https://stripe.com/"}, |
| 855 | ], {}))) |
| 856 | |
| 857 | result = company_resolve.resolve_company("StripeCo", config={"EXA_API_KEY": "exa-key"}) |
| 858 | |
| 859 | assert result == {} |
| 860 | assert not company_resolve._exa_site_matches_topic("StripeCo", "https://stripe.com/") |
| 861 | |
| 862 | |
| 863 | def test_exa_official_site_rejects_subdomain_of_unrelated_registrable_domain(monkeypatch): |
| 864 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 865 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 866 | {"title": "StripeCo", "url": "https://stripeco.example.org/"}, |
| 867 | ], {}))) |
| 868 | |
| 869 | result = company_resolve.resolve_company("StripeCo", config={"EXA_API_KEY": "exa-key"}) |
| 870 | |
| 871 | assert result == {} |
| 872 | assert not company_resolve._exa_site_matches_topic( |
| 873 | "StripeCo", "https://stripeco.example.org/", |
| 874 | ) |
| 875 | |
| 876 | |
| 877 | def test_exa_official_site_accepts_anthropic_dot_com(monkeypatch): |
| 878 | monkeypatch.setattr(company_resolve, "_resolve", lambda *_args, **_kwargs: {}) |
| 879 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 880 | {"title": "Anthropic", "url": "https://www.anthropic.com/"}, |
| 881 | ], {}))) |
| 882 | |
| 883 | result = company_resolve.resolve_company("Anthropic", config={"EXA_API_KEY": "exa-key"}) |
| 884 | |
| 885 | assert result == { |
| 886 | "company": "Anthropic", |
| 887 | "company_site": "https://anthropic.com/", |
| 888 | "company_source": "exa", |
| 889 | } |
| 890 | assert company_resolve._exa_site_matches_topic("Anthropic", "https://anthropic.com/") |
| 891 | |
| 892 | |
| 893 | def test_exa_is_not_called_when_wikidata_already_named_the_company(monkeypatch): |
| 894 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 895 | exa = mock.Mock(side_effect=AssertionError("Exa must not run after a Wikidata hit")) |
| 896 | monkeypatch.setattr(company_resolve.grounding, "exa_search", exa) |
| 897 | |
| 898 | result = company_resolve.resolve_company("Stripe", config={"EXA_API_KEY": "exa-key"}) |
| 899 | |
| 900 | assert result["company"] == "Stripe" |
| 901 | assert result["company_site"] == "https://stripe.com/" |
| 902 | assert "company_source" not in result |
| 903 | exa.assert_not_called() |
| 904 | |
| 905 | |
| 906 | def test_exa_is_not_called_after_a_failed_wikidata_lookup(monkeypatch): |
| 907 | monkeypatch.setattr(company_resolve.log, "source_log", mock.Mock()) |
| 908 | monkeypatch.setattr( |
| 909 | company_resolve.http, "get", |
| 910 | FakeWikidata(error=http.HTTPError("Request timed out")), |
| 911 | ) |
| 912 | exa = mock.Mock(side_effect=AssertionError("Failed Wikidata lookups keep the Yahoo path")) |
| 913 | monkeypatch.setattr(company_resolve.grounding, "exa_search", exa) |
| 914 | |
| 915 | result = company_resolve.resolve_company("Nvidia", config={"EXA_API_KEY": "exa-key"}) |
| 916 | |
| 917 | assert isinstance(result, company_resolve.FailedLookup) |
| 918 | exa.assert_not_called() |
| 919 | |
| 920 | |
| 921 | def test_exa_is_not_called_without_a_key(monkeypatch): |
| 922 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 923 | exa = mock.Mock(side_effect=AssertionError("No Exa call without EXA_API_KEY")) |
| 924 | monkeypatch.setattr(company_resolve.grounding, "exa_search", exa) |
| 925 | |
| 926 | result = company_resolve.resolve_company("AcmePayments") |
| 927 | |
| 928 | assert result == {} |
| 929 | exa.assert_not_called() |
| 930 | |
| 931 | |
| 932 | def test_exa_failure_leaves_wikidata_nothing_certain(monkeypatch): |
| 933 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 934 | logged = mock.Mock() |
| 935 | monkeypatch.setattr(company_resolve.log, "source_log", logged) |
| 936 | monkeypatch.setattr( |
| 937 | company_resolve.grounding, "exa_search", |
| 938 | mock.Mock(side_effect=http.HTTPError("HTTP 400: INVALID_REQUEST_BODY", status_code=400)), |
| 939 | ) |
| 940 | |
| 941 | result = company_resolve.resolve_company("AcmePayments", config={"EXA_API_KEY": "exa-key"}) |
| 942 | |
| 943 | assert result == {} |
| 944 | assert not isinstance(result, company_resolve.FailedLookup) |
| 945 | assert logged.call_count >= 1 |
| 946 | assert logged.call_args.kwargs == {"tty_only": False} |
| 947 | assert "AcmePayments" in logged.call_args.args[1] |
| 948 | |
| 949 | |
| 950 | def test_wikidata_exposes_why_nothing_is_certain(monkeypatch): |
| 951 | cases = ( |
| 952 | ("AcmePayments", company_resolve.WIKIDATA_NONE), |
| 953 | ("Kanye West", company_resolve.WIKIDATA_HUMAN), |
| 954 | ("Rust", company_resolve.WIKIDATA_SOFTWARE), |
| 955 | ) |
| 956 | for topic, kind in cases: |
| 957 | result, fake = _resolve(monkeypatch, topic) |
| 958 | assert result == {} |
| 959 | assert isinstance(result, company_resolve.UncertainLookup) |
| 960 | assert result.kind == kind |
| 961 | assert fake.calls |
| 962 | assert not isinstance(result, company_resolve.FailedLookup) |
| 963 | |
| 964 | |
| 965 | def test_exa_keeps_a_human_site_and_uses_keyword_peers(monkeypatch): |
| 966 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 967 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 968 | {"title": "Kanye West", "url": "https://www.kanyewest.com/"}, |
| 969 | ], {}))) |
| 970 | |
| 971 | result = company_resolve.resolve_company("Kanye West", config={"EXA_API_KEY": "exa-key"}) |
| 972 | |
| 973 | assert result == { |
| 974 | "company": "Kanye West", |
| 975 | "company_site": "https://kanyewest.com/", |
| 976 | "company_source": "exa", |
| 977 | "company_peer_discovery": "keyword", |
| 978 | } |
| 979 | assert "company_via_person" not in result |
| 980 | |
| 981 | |
| 982 | def test_exa_python_style_language_uses_keyword_peers(monkeypatch): |
| 983 | python = copy.deepcopy(FIXTURE["entities"]["Q575650"]) |
| 984 | python["id"] = "Q28865" |
| 985 | python["labels"] = { |
| 986 | "en": {"language": "en", "value": "Python"}, |
| 987 | "mul": {"language": "mul", "value": "Python"}, |
| 988 | } |
| 989 | fake = FakeWikidata( |
| 990 | entities={"Q28865": python}, |
| 991 | search={"Python": { |
| 992 | "search": [{"id": "Q28865", "label": "Python"}], |
| 993 | "success": 1, |
| 994 | }}, |
| 995 | ) |
| 996 | monkeypatch.setattr(company_resolve.http, "get", fake) |
| 997 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 998 | {"title": "Python", "url": "https://www.python.org/"}, |
| 999 | ], {}))) |
| 1000 | |
| 1001 | result = company_resolve.resolve_company("Python", config={"EXA_API_KEY": "exa-key"}) |
| 1002 | |
| 1003 | assert result == { |
| 1004 | "company": "Python", |
| 1005 | "company_site": "https://python.org/", |
| 1006 | "company_source": "exa", |
| 1007 | "company_peer_discovery": "keyword", |
| 1008 | } |
| 1009 | assert "company_via_person" not in result |
| 1010 | |
| 1011 | |
| 1012 | def _p31_claim(class_id: str) -> dict: |
| 1013 | return { |
| 1014 | "rank": "normal", |
| 1015 | "type": "statement", |
| 1016 | "mainsnak": { |
| 1017 | "snaktype": "value", |
| 1018 | "property": "P31", |
| 1019 | "datavalue": { |
| 1020 | "value": { |
| 1021 | "entity-type": "item", |
| 1022 | "numeric-id": int(class_id[1:]), |
| 1023 | "id": class_id, |
| 1024 | }, |
| 1025 | "type": "wikibase-entityid", |
| 1026 | }, |
| 1027 | }, |
| 1028 | } |
| 1029 | |
| 1030 | |
| 1031 | def test_exa_granola_style_food_homonym_keeps_company_peers(monkeypatch): |
| 1032 | granola = { |
| 1033 | "type": "item", |
| 1034 | "id": "Q999001", |
| 1035 | "labels": {"en": {"language": "en", "value": "Granola"}}, |
| 1036 | "claims": {"P31": [_p31_claim("Q2095")]}, |
| 1037 | } |
| 1038 | food = {"type": "item", "id": "Q2095", "claims": {}} |
| 1039 | fake = FakeWikidata( |
| 1040 | entities={"Q999001": granola, "Q2095": food}, |
| 1041 | search={"Granola": { |
| 1042 | "search": [{"id": "Q999001", "label": "Granola"}], |
| 1043 | "success": 1, |
| 1044 | }}, |
| 1045 | ) |
| 1046 | monkeypatch.setattr(company_resolve.http, "get", fake) |
| 1047 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 1048 | {"title": "Granola", "url": "https://www.granola.so/"}, |
| 1049 | ], {}))) |
| 1050 | |
| 1051 | result = company_resolve.resolve_company("Granola", config={"EXA_API_KEY": "exa-key"}) |
| 1052 | |
| 1053 | assert result == { |
| 1054 | "company": "Granola", |
| 1055 | "company_site": "https://granola.so/", |
| 1056 | "company_source": "exa", |
| 1057 | } |
| 1058 | assert "company_via_person" not in result |
| 1059 | assert "company_peer_discovery" not in result |
| 1060 | |
| 1061 | |
| 1062 | def _p279_claim(class_id: str) -> dict: |
| 1063 | claim = _p31_claim(class_id) |
| 1064 | claim["mainsnak"]["property"] = "P279" |
| 1065 | return claim |
| 1066 | |
| 1067 | |
| 1068 | def _homonym_fake( |
| 1069 | topic: str, entity_id: str, class_id: str, *, parent_id: str | None = None, |
| 1070 | ) -> FakeWikidata: |
| 1071 | entity = { |
| 1072 | "type": "item", |
| 1073 | "id": entity_id, |
| 1074 | "labels": {"en": {"language": "en", "value": topic}}, |
| 1075 | "claims": {"P31": [_p31_claim(class_id)]}, |
| 1076 | } |
| 1077 | klass: dict = {"type": "item", "id": class_id, "claims": {}} |
| 1078 | entities = {entity_id: entity, class_id: klass} |
| 1079 | if parent_id: |
| 1080 | klass["claims"]["P279"] = [_p279_claim(parent_id)] |
| 1081 | entities[parent_id] = {"type": "item", "id": parent_id, "claims": {}} |
| 1082 | return FakeWikidata( |
| 1083 | entities=entities, |
| 1084 | search={topic: { |
| 1085 | "search": [{"id": entity_id, "label": topic}], |
| 1086 | "success": 1, |
| 1087 | }}, |
| 1088 | ) |
| 1089 | |
| 1090 | |
| 1091 | def test_exa_linux_style_os_uses_keyword_peers(monkeypatch): |
| 1092 | monkeypatch.setattr(company_resolve.http, "get", _homonym_fake("Linux", "Q388", "Q9135")) |
| 1093 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 1094 | {"title": "Linux", "url": "https://www.linux.org/"}, |
| 1095 | ], {}))) |
| 1096 | |
| 1097 | result = company_resolve.resolve_company("Linux", config={"EXA_API_KEY": "exa-key"}) |
| 1098 | |
| 1099 | assert result == { |
| 1100 | "company": "Linux", |
| 1101 | "company_site": "https://linux.org/", |
| 1102 | "company_source": "exa", |
| 1103 | "company_peer_discovery": "keyword", |
| 1104 | } |
| 1105 | |
| 1106 | |
| 1107 | def test_exa_raycast_style_software_product_keeps_company_peers(monkeypatch): |
| 1108 | monkeypatch.setattr( |
| 1109 | company_resolve.http, "get", |
| 1110 | _homonym_fake("Raycast", "Q124372806", "Q7397"), |
| 1111 | ) |
| 1112 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 1113 | {"title": "Raycast", "url": "https://www.raycast.com/"}, |
| 1114 | ], {}))) |
| 1115 | |
| 1116 | result = company_resolve.resolve_company("Raycast", config={"EXA_API_KEY": "exa-key"}) |
| 1117 | |
| 1118 | assert result == { |
| 1119 | "company": "Raycast", |
| 1120 | "company_site": "https://raycast.com/", |
| 1121 | "company_source": "exa", |
| 1122 | } |
| 1123 | assert "company_peer_discovery" not in result |
| 1124 | assert "company_via_person" not in result |
| 1125 | |
| 1126 | |
| 1127 | def test_exa_application_homonym_keeps_company_peers(monkeypatch): |
| 1128 | monkeypatch.setattr( |
| 1129 | company_resolve.http, "get", |
| 1130 | _homonym_fake("Exa", "Q57838499", "Q166142", parent_id="Q7397"), |
| 1131 | ) |
| 1132 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 1133 | {"title": "Exa", "url": "https://exa.ai/"}, |
| 1134 | ], {}))) |
| 1135 | |
| 1136 | result = company_resolve.resolve_company("Exa", config={"EXA_API_KEY": "exa-key"}) |
| 1137 | |
| 1138 | assert result == { |
| 1139 | "company": "Exa", |
| 1140 | "company_site": "https://exa.ai/", |
| 1141 | "company_source": "exa", |
| 1142 | } |
| 1143 | assert "company_peer_discovery" not in result |
| 1144 | assert "company_via_person" not in result |
| 1145 | |
| 1146 | |
| 1147 | def test_exa_modal_labs_matches_modal_com(monkeypatch): |
| 1148 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 1149 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 1150 | {"title": "Modal", "url": "https://modal.com/"}, |
| 1151 | ], {}))) |
| 1152 | |
| 1153 | result = company_resolve.resolve_company("Modal Labs", config={"EXA_API_KEY": "exa-key"}) |
| 1154 | |
| 1155 | assert result == { |
| 1156 | "company": "Modal Labs", |
| 1157 | "company_site": "https://modal.com/", |
| 1158 | "company_source": "exa", |
| 1159 | } |
| 1160 | assert company_resolve._exa_site_matches_topic("Modal Labs", "https://modal.com/") |
| 1161 | assert not company_resolve._exa_site_matches_topic("StripeCo", "https://stripe.com/") |
| 1162 | assert not company_resolve._exa_site_matches_topic( |
| 1163 | "StripeCo", "https://stripeco.example.org/", |
| 1164 | ) |
| 1165 | |
| 1166 | |
| 1167 | def test_exa_prefers_exact_label_over_trimmed_generic(monkeypatch): |
| 1168 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 1169 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 1170 | {"title": "Acme", "url": "https://acme.com/"}, |
| 1171 | {"title": "Acme Labs", "url": "https://acmelabs.com/"}, |
| 1172 | ], {}))) |
| 1173 | |
| 1174 | result = company_resolve.resolve_company("Acme Labs", config={"EXA_API_KEY": "exa-key"}) |
| 1175 | |
| 1176 | assert result == { |
| 1177 | "company": "Acme Labs", |
| 1178 | "company_site": "https://acmelabs.com/", |
| 1179 | "company_source": "exa", |
| 1180 | } |
| 1181 | |
| 1182 | |
| 1183 | def test_exa_browserbase_is_an_unresolved_company(monkeypatch): |
| 1184 | monkeypatch.setattr(company_resolve.http, "get", FakeWikidata()) |
| 1185 | monkeypatch.setattr(company_resolve.grounding, "exa_search", mock.Mock(return_value=([ |
| 1186 | {"title": "Browserbase", "url": "https://www.browserbase.com/"}, |
| 1187 | ], {}))) |
| 1188 | |
| 1189 | result = company_resolve.resolve_company("Browserbase", config={"EXA_API_KEY": "exa-key"}) |
| 1190 | |
| 1191 | assert result == { |
| 1192 | "company": "Browserbase", |
| 1193 | "company_site": "https://browserbase.com/", |
| 1194 | "company_source": "exa", |
| 1195 | } |
| 1196 | assert "company_via_person" not in result |
| 1197 | assert "company_peer_discovery" not in result |
| 1198 |