| 1 | """Regression tests for PR 36: jobs ownership/Workday timeouts/teams crash, |
| 2 | Hacker News query matching, StockTwits symbol gating, and Meta Ads failures. |
| 3 | |
| 4 | Covers HIGH-165, HIGH-166, HIGH-172, HIGH-193, HIGH-197, HIGH-198, and HIGH-206. |
| 5 | """ |
| 6 | |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | import copy |
| 10 | from unittest.mock import patch |
| 11 | from urllib.parse import parse_qs, urlsplit |
| 12 | |
| 13 | import pytest |
| 14 | |
| 15 | from lib import hackernews, health, http, jobs, jobs_teams, meta_ads, pipeline, schema, stocktwits |
| 16 | from lib.job_boards import robots, sitemap |
| 17 | |
| 18 | |
| 19 | WINDOW = ("2026-10-15", "2026-11-14") |
| 20 | |
| 21 | |
| 22 | # --------------------------------------------------------------------------- |
| 23 | # HIGH-165: jobs.py sitemap ownership & multi-tenant host exclusion |
| 24 | # --------------------------------------------------------------------------- |
| 25 | |
| 26 | |
| 27 | def _sitemap_xml(host: str, slug: str) -> tuple[str, str]: |
| 28 | robots_txt = f"User-agent: *\nSitemap: https://{host}/jobs/sitemap.xml\n" |
| 29 | urlset = ( |
| 30 | f"<urlset><url><loc>https://{host}/jobs/10001/{slug}</loc></url></urlset>" |
| 31 | ) |
| 32 | return robots_txt, urlset |
| 33 | |
| 34 | |
| 35 | @pytest.fixture |
| 36 | def _fresh_jobs_robots(monkeypatch): |
| 37 | robots.clear_cache() |
| 38 | monkeypatch.setattr(sitemap, "_resolves_public", lambda _name: True) |
| 39 | yield |
| 40 | robots.clear_cache() |
| 41 | |
| 42 | |
| 43 | def test_high165_sitemap_hosts_filters_shared_and_untrusted_hosts(): |
| 44 | assert jobs._sitemap_hosts( |
| 45 | [ |
| 46 | "careers.kula.ai", |
| 47 | "jpmc.fa.oraclecloud.com", |
| 48 | "eeho.fa.us2.oraclecloud.com", |
| 49 | "boards.greenhouse.io", |
| 50 | "acme.wd5.myworkdayjobs.com", |
| 51 | "stranger.example", |
| 52 | ], |
| 53 | "https://www.acme.com/", |
| 54 | ) == ["jobs.acme.com", "careers.acme.com", "www.acme.com"] |
| 55 | |
| 56 | assert jobs._sitemap_hosts(["stranger.example", "careers.kula.ai"], "") == [] |
| 57 | assert jobs._sitemap_hosts(["join.disneycareers.com"], "https://disney.com/")[0] == ( |
| 58 | "join.disneycareers.com" |
| 59 | ) |
| 60 | assert jobs._sitemap_hosts(["www.amazon.jobs"], "https://www.amazon.com/")[0] == ( |
| 61 | "www.amazon.jobs" |
| 62 | ) |
| 63 | assert jobs._sitemap_hosts(["explore.jobs.netflix.net"], "https://www.netflix.com/")[0] == ( |
| 64 | "explore.jobs.netflix.net" |
| 65 | ) |
| 66 | |
| 67 | |
| 68 | def test_high165_search_discovered_careers_host_never_stamped_owned_sitemap(_fresh_jobs_robots): |
| 69 | stranger_robots, stranger_xml = _sitemap_xml("careers.stranger.example", "unrelated-role") |
| 70 | asked: list[str] = [] |
| 71 | |
| 72 | def fake_get_text(url, *_args, **kwargs): |
| 73 | asked.append(url) |
| 74 | if url == "https://careers.stranger.example/jobs": |
| 75 | if kwargs.get("landed") is not None: |
| 76 | kwargs["landed"].append(url) |
| 77 | return "<html><body><h1>Open positions</h1></body></html>" |
| 78 | if url == "https://careers.stranger.example/robots.txt": |
| 79 | return stranger_robots |
| 80 | if url == "https://careers.stranger.example/jobs/sitemap.xml": |
| 81 | return stranger_xml |
| 82 | return None |
| 83 | |
| 84 | with patch.object(jobs.http, "get_text", side_effect=fake_get_text), \ |
| 85 | patch.object(jobs.http, "get", side_effect=http.HTTPError("404", status_code=404)), \ |
| 86 | patch.object(jobs, "_search_for_careers_url", return_value="https://careers.stranger.example/jobs"), \ |
| 87 | patch.object(jobs, "search_jobs_web", return_value=([], {"tier": "web"})): |
| 88 | items, artifact = jobs.search_jobs( |
| 89 | "Acme", WINDOW, {}, web_backend="auto", site="https://www.acme.com/", |
| 90 | ) |
| 91 | |
| 92 | assert "https://careers.stranger.example/robots.txt" not in asked |
| 93 | assert items == [] |
| 94 | assert artifact["tier"] == "web" |
| 95 | assert artifact.get("owned") is not True |
| 96 | |
| 97 | |
| 98 | def test_high165_search_discovered_host_does_not_preempt_company_sitemap(_fresh_jobs_robots): |
| 99 | stranger_robots, stranger_xml = _sitemap_xml("careers.stranger.example", "stranger-role") |
| 100 | acme_robots, acme_xml = _sitemap_xml("jobs.acme.com", "acme-staff-engineer") |
| 101 | asked: list[str] = [] |
| 102 | |
| 103 | def fake_get_text(url, *_args, **kwargs): |
| 104 | asked.append(url) |
| 105 | table = { |
| 106 | "https://careers.stranger.example/jobs": "<html><body><h1>Open positions</h1></body></html>", |
| 107 | "https://careers.stranger.example/robots.txt": stranger_robots, |
| 108 | "https://careers.stranger.example/jobs/sitemap.xml": stranger_xml, |
| 109 | "https://jobs.acme.com/robots.txt": acme_robots, |
| 110 | "https://jobs.acme.com/jobs/sitemap.xml": acme_xml, |
| 111 | } |
| 112 | body = table.get(url) |
| 113 | if body is not None and kwargs.get("landed") is not None: |
| 114 | kwargs["landed"].append(url) |
| 115 | return body |
| 116 | |
| 117 | with patch.object(jobs.http, "get_text", side_effect=fake_get_text), \ |
| 118 | patch.object(jobs.http, "get", side_effect=http.HTTPError("404", status_code=404)), \ |
| 119 | patch.object(jobs, "_search_for_careers_url", return_value="https://careers.stranger.example/jobs"): |
| 120 | items, artifact = jobs.search_jobs( |
| 121 | "Acme", WINDOW, {}, web_backend="auto", site="https://www.acme.com/", |
| 122 | ) |
| 123 | |
| 124 | assert "https://careers.stranger.example/robots.txt" not in asked |
| 125 | assert artifact["provider"] == "sitemap" |
| 126 | assert artifact["board_sitemap_host"] == "jobs.acme.com" |
| 127 | assert artifact["owned"] is True |
| 128 | assert [item["title"] for item in items] == ["Acme Staff Engineer"] |
| 129 | |
| 130 | |
| 131 | def test_high165_kula_multi_tenant_host_not_queried_on_platform_fallthrough(_fresh_jobs_robots): |
| 132 | kula_robots, kula_xml = _sitemap_xml("careers.kula.ai", "other-company-role") |
| 133 | asked: list[str] = [] |
| 134 | |
| 135 | def fake_get_text(url, *_args, **kwargs): |
| 136 | asked.append(url) |
| 137 | if url == "https://careers.kula.ai/nothing": |
| 138 | if kwargs.get("landed") is not None: |
| 139 | kwargs["landed"].append(url) |
| 140 | # Contains Kula link but invalid payload so kula.read_board raises BoardShapeError. |
| 141 | return '<html><a href="https://careers.kula.ai/nothing">Open roles</a></html>' |
| 142 | if url == "https://careers.kula.ai/robots.txt": |
| 143 | return kula_robots |
| 144 | if url == "https://careers.kula.ai/jobs/sitemap.xml": |
| 145 | return kula_xml |
| 146 | return None |
| 147 | |
| 148 | with patch.object(jobs.http, "get_text", side_effect=fake_get_text), \ |
| 149 | patch.object(jobs.http, "get", side_effect=http.HTTPError("404", status_code=404)): |
| 150 | items, artifact = jobs.search_jobs( |
| 151 | "Nothing", WINDOW, {}, web_backend="none", site="https://nothing.tech/", |
| 152 | ) |
| 153 | |
| 154 | assert "https://careers.kula.ai/robots.txt" not in asked |
| 155 | assert items == [] |
| 156 | assert artifact.get("provider") != "sitemap" |
| 157 | assert artifact["job_site_unreadable"] == "Nothing" |
| 158 | |
| 159 | |
| 160 | def test_high165_oracle_multi_tenant_host_not_queried_on_platform_fallthrough(_fresh_jobs_robots): |
| 161 | oracle_robots, oracle_xml = _sitemap_xml("jpmc.fa.oraclecloud.com", "oracle-shared-role") |
| 162 | oracle_page = ( |
| 163 | '<a href="https://jpmc.fa.oraclecloud.com/hcmUI/CandidateExperience/en/sites/CX_1001/requisitions">' |
| 164 | "Search jobs</a><p>Join our team</p>" |
| 165 | ) |
| 166 | asked: list[str] = [] |
| 167 | |
| 168 | def fake_get_text(url, *_args, **kwargs): |
| 169 | asked.append(url) |
| 170 | table = { |
| 171 | "https://www.jpmorganchase.com/careers": oracle_page, |
| 172 | "https://jpmc.fa.oraclecloud.com/robots.txt": oracle_robots, |
| 173 | "https://jpmc.fa.oraclecloud.com/jobs/sitemap.xml": oracle_xml, |
| 174 | } |
| 175 | body = table.get(url) |
| 176 | if body is not None and kwargs.get("landed") is not None: |
| 177 | kwargs["landed"].append(url) |
| 178 | return body |
| 179 | |
| 180 | with patch.object(jobs.http, "get_text", side_effect=fake_get_text), \ |
| 181 | patch.object(jobs.http, "get", side_effect=http.HTTPError("404", status_code=404)): |
| 182 | items, artifact = jobs.search_jobs( |
| 183 | "JPMorgan", WINDOW, {}, web_backend="none", site="https://www.jpmorganchase.com/", |
| 184 | ) |
| 185 | |
| 186 | assert "https://jpmc.fa.oraclecloud.com/robots.txt" not in asked |
| 187 | assert items == [] |
| 188 | assert artifact.get("provider") != "sitemap" |
| 189 | assert artifact["job_site_unreadable"] == "JPMorgan" |
| 190 | |
| 191 | |
| 192 | # --------------------------------------------------------------------------- |
| 193 | # HIGH-166: Workday & SmartRecruiters first-page timeouts/429/5xx unanswered |
| 194 | # --------------------------------------------------------------------------- |
| 195 | |
| 196 | |
| 197 | @pytest.mark.parametrize( |
| 198 | "exc", |
| 199 | [ |
| 200 | http.DeadlineExceeded(), |
| 201 | http.HTTPError("timed out", outcome_state=health.TIMEOUT), |
| 202 | http.HTTPError("rate limited", status_code=429), |
| 203 | http.HTTPError("server error", status_code=503), |
| 204 | ], |
| 205 | ) |
| 206 | def test_high166_workday_first_page_marks_board_unanswered(exc): |
| 207 | with patch.object(jobs.http, "post", side_effect=exc): |
| 208 | items, info = jobs.search_workday_board("intel.wd1/External") |
| 209 | assert items == [] |
| 210 | assert info.get("board_unanswered") is True |
| 211 | |
| 212 | |
| 213 | def test_high166_workday_first_page_out_of_time_marks_board_unanswered(): |
| 214 | with patch.object(jobs.http, "post", side_effect=AssertionError("should not run")): |
| 215 | items, info = jobs.search_workday_board( |
| 216 | "intel.wd1/External", deadline=10.0, clock=lambda: 15.0, |
| 217 | ) |
| 218 | assert items == [] |
| 219 | assert info.get("board_unanswered") is True |
| 220 | |
| 221 | |
| 222 | @pytest.mark.parametrize("status", [403, 404]) |
| 223 | def test_high166_workday_403_404_not_marked_unanswered(status): |
| 224 | with patch.object(jobs.http, "post", side_effect=http.HTTPError("refused", status_code=status)): |
| 225 | items, info = jobs.search_workday_board("intel.wd1/External") |
| 226 | assert items == [] |
| 227 | assert not info.get("board_unanswered") |
| 228 | |
| 229 | |
| 230 | @pytest.mark.parametrize( |
| 231 | "exc", |
| 232 | [ |
| 233 | http.DeadlineExceeded(), |
| 234 | http.HTTPError("rate limited", status_code=429), |
| 235 | http.HTTPError("server error", status_code=500), |
| 236 | ], |
| 237 | ) |
| 238 | def test_high166_smartrecruiters_first_page_marks_board_unanswered(exc): |
| 239 | with patch.object(jobs.http, "get", side_effect=exc): |
| 240 | items, info = jobs.read_smartrecruiters_board("acme") |
| 241 | assert items == [] |
| 242 | assert info.get("board_unanswered") is True |
| 243 | |
| 244 | |
| 245 | def test_high166_smartrecruiters_first_page_out_of_time_and_404(): |
| 246 | with patch.object(jobs.http, "get", side_effect=AssertionError("should not run")): |
| 247 | items, info = jobs.read_smartrecruiters_board("acme", deadline=10.0, clock=lambda: 12.0) |
| 248 | assert items == [] |
| 249 | assert info.get("board_unanswered") is True |
| 250 | |
| 251 | with patch.object(jobs.http, "get", side_effect=http.HTTPError("not found", status_code=404)): |
| 252 | items, info = jobs.read_smartrecruiters_board("acme") |
| 253 | assert items == [] |
| 254 | assert not info.get("board_unanswered") |
| 255 | |
| 256 | |
| 257 | @pytest.mark.parametrize( |
| 258 | ("company", "site", "board_token"), |
| 259 | [ |
| 260 | ("Intel", "https://www.intel.com/", "intel.wd1/External"), |
| 261 | ("Salesforce", "https://www.salesforce.com/", "salesforce.wd12/External_Career_Site"), |
| 262 | ], |
| 263 | ) |
| 264 | @pytest.mark.parametrize( |
| 265 | "exc", |
| 266 | [ |
| 267 | http.DeadlineExceeded(), |
| 268 | http.HTTPError("rate limited", status_code=429), |
| 269 | http.HTTPError("server error", status_code=503), |
| 270 | ], |
| 271 | ) |
| 272 | def test_high166_registry_workday_timeout_reports_retryable_timeout_not_unreadable( |
| 273 | company, site, board_token, exc, |
| 274 | ): |
| 275 | budget = jobs.LaneBudget(45.0) |
| 276 | with patch.object(jobs.http, "get_text", return_value=None), \ |
| 277 | patch.object(jobs.http, "post", side_effect=exc): |
| 278 | items, artifact = jobs.search_jobs( |
| 279 | company, WINDOW, {}, web_backend="none", site=site, budget=budget, |
| 280 | ) |
| 281 | |
| 282 | assert items == [] |
| 283 | assert "job_site_unreadable" not in artifact |
| 284 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 285 | assert f"the workday board {board_token} did not answer" in artifact["_source_outcome"]["detail"] |
| 286 | assert "_source_out_of_time" not in artifact |
| 287 | assert f"the workday board {board_token} did not answer" in budget.slow |
| 288 | |
| 289 | |
| 290 | @pytest.mark.parametrize( |
| 291 | ("provider", "html", "board_id", "patch_target"), |
| 292 | [ |
| 293 | ( |
| 294 | "workday", |
| 295 | '<a href="https://acme.wd5.myworkdayjobs.com/en-US/AcmeCareers">Jobs</a>', |
| 296 | "acme.wd5/AcmeCareers", |
| 297 | "post", |
| 298 | ), |
| 299 | ( |
| 300 | "smartrecruiters", |
| 301 | '<a href="https://careers.smartrecruiters.com/AcmeCorp">Jobs</a>', |
| 302 | "AcmeCorp", |
| 303 | "get", |
| 304 | ), |
| 305 | ], |
| 306 | ) |
| 307 | def test_high166_careers_discovered_hosted_board_timeout_reports_timeout_not_no_board( |
| 308 | provider, html, board_id, patch_target, capsys, |
| 309 | ): |
| 310 | budget = jobs.LaneBudget(45.0) |
| 311 | exc = http.DeadlineExceeded() |
| 312 | |
| 313 | def fake_text(url, *_args, **kwargs): |
| 314 | if url == "https://www.acme.com/careers": |
| 315 | if kwargs.get("landed") is not None: |
| 316 | kwargs["landed"].append(url) |
| 317 | return html |
| 318 | return None |
| 319 | |
| 320 | with patch.object(jobs.http, "get_text", side_effect=fake_text), \ |
| 321 | patch.object(jobs.http, patch_target, side_effect=exc): |
| 322 | items, artifact = jobs.search_jobs( |
| 323 | "Acme", WINDOW, {}, web_backend="none", site="https://www.acme.com/", budget=budget, |
| 324 | ) |
| 325 | |
| 326 | assert items == [] |
| 327 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 328 | assert f"the {provider} board {board_id} did not answer" in artifact["_source_outcome"]["detail"] |
| 329 | assert "_source_out_of_time" not in artifact |
| 330 | assert "no supported job board found" not in capsys.readouterr().err |
| 331 | |
| 332 | |
| 333 | # --------------------------------------------------------------------------- |
| 334 | # HIGH-172: jobs_teams.py ZeroDivisionError on &-joined company names |
| 335 | # --------------------------------------------------------------------------- |
| 336 | |
| 337 | |
| 338 | def _team_role(title: str, idx: int) -> dict: |
| 339 | return { |
| 340 | "title": title, |
| 341 | "department": "", |
| 342 | "location": "San Francisco, CA", |
| 343 | "date": "2026-11-05", |
| 344 | "posted_date_true": True, |
| 345 | "url": f"https://jobs.example.com/{idx}", |
| 346 | } |
| 347 | |
| 348 | |
| 349 | @pytest.mark.parametrize( |
| 350 | ("company", "segment", "expected_team"), |
| 351 | [ |
| 352 | ("AI", "Cloud&AI", "cloud"), |
| 353 | ("X", "X&Safety", "safety"), |
| 354 | ("S&P", "S&P&Analytics", "analytics"), |
| 355 | ("AI", "Cloud&AI&Data", "cloud data"), |
| 356 | ("AI", "Cloud & AI", "cloud"), |
| 357 | ("AT&T", "AT&T", None), |
| 358 | ], |
| 359 | ) |
| 360 | def test_high172_ampersand_joined_company_stripping_never_raises(company, segment, expected_team): |
| 361 | rows = [_team_role(f"Engineer {i}, {segment}", i) for i in range(4)] |
| 362 | result = jobs_teams.named_teams(rows, company=company, window_start="2026-10-15") |
| 363 | team_names = [t["name"] for t in result["teams"]] |
| 364 | if expected_team is None: |
| 365 | assert team_names == [] |
| 366 | else: |
| 367 | assert expected_team in team_names |
| 368 | assert all(not name.startswith("&") and not name.endswith("&") for name in team_names) |
| 369 | |
| 370 | |
| 371 | def test_high172_legitimate_ampersand_team_names_stay_intact(): |
| 372 | rows = ( |
| 373 | [_team_role(f"Specialist {i}, Trust & Safety", i) for i in range(4)] |
| 374 | + [_team_role(f"Scientist {i}, R&D", i + 10) for i in range(4)] |
| 375 | ) |
| 376 | result = jobs_teams.named_teams(rows, company="Acme", window_start="2026-10-15") |
| 377 | team_names = {t["name"] for t in result["teams"]} |
| 378 | assert "trust & safety" in team_names |
| 379 | assert "r&d" in team_names |
| 380 | |
| 381 | |
| 382 | # --------------------------------------------------------------------------- |
| 383 | # HIGH-193: hackernews.py quoted proper nouns, punctuation, symbol-edged terms |
| 384 | # --------------------------------------------------------------------------- |
| 385 | |
| 386 | |
| 387 | @pytest.mark.parametrize( |
| 388 | ("title", "query", "expected"), |
| 389 | [ |
| 390 | # Planner-quoted multi-word proper nouns |
| 391 | ("Claude Code v2.1 released", '"Claude Code"', True), |
| 392 | ("Hermes Agent launches open-source framework", '"Hermes Agent"', True), |
| 393 | ("Nous Research releases new model", '"Nous Research"', True), |
| 394 | ("Totally unrelated gardening post", '"Claude Code"', False), |
| 395 | # Symbol-edged tech terms |
| 396 | ("Why C++ is fast", "C++", True), |
| 397 | ("C++23 modules in practice", "C++", True), |
| 398 | ("C# 14 new features", "C#", True), |
| 399 | (".NET 10 performance benchmarks", ".NET", True), |
| 400 | ("F# for backend services", "F#", True), |
| 401 | # Punctuated queries |
| 402 | ("Rust 1.90 released", "What is Rust?", True), |
| 403 | ("What is happening with Java?", "What is Rust?", False), |
| 404 | ("Claude Code overview", '"What is Claude Code?"', True), |
| 405 | # Anti-substring boundaries preserved |
| 406 | ("New email service", "ai", False), |
| 407 | ("Best artists of 2026", "ts", False), |
| 408 | ("Hosting at example.net", ".NET", False), |
| 409 | ("Fishing net design", ".NET", False), |
| 410 | ("C+++ weird syntax", "C++", False), |
| 411 | ], |
| 412 | ) |
| 413 | def test_high193_title_matches_query_quotes_symbols_and_boundaries(title, query, expected): |
| 414 | assert hackernews._title_matches_query(title, query) is expected |
| 415 | |
| 416 | |
| 417 | def test_high193_parse_hackernews_response_keeps_quoted_and_symbol_hits(): |
| 418 | response = { |
| 419 | "hits": [ |
| 420 | {"objectID": "1", "title": "Claude Code v2.1 released", "points": 200, "num_comments": 50}, |
| 421 | {"objectID": "2", "title": "Unrelated article", "points": 100, "num_comments": 10}, |
| 422 | ] |
| 423 | } |
| 424 | items = hackernews.parse_hackernews_response(response, query='"Claude Code"') |
| 425 | assert [item["id"] for item in items] == ["1"] |
| 426 | |
| 427 | cpp_response = { |
| 428 | "hits": [ |
| 429 | {"objectID": "3", "title": "Why C++ is fast", "points": 150, "num_comments": 40}, |
| 430 | {"objectID": "4", "title": "Rust borrow checker", "points": 150, "num_comments": 40}, |
| 431 | ] |
| 432 | } |
| 433 | cpp_items = hackernews.parse_hackernews_response(cpp_response, query="C++") |
| 434 | assert [item["id"] for item in cpp_items] == ["3"] |
| 435 | |
| 436 | |
| 437 | def test_high193_search_hackernews_strips_quotes_from_query_and_optional_words(): |
| 438 | with patch.object(hackernews.http, "request", return_value={"hits": [], "nbHits": 0}) as mock_req: |
| 439 | hackernews.search_hackernews('"Claude Code"', "2026-01-01", "2026-01-31", depth="quick") |
| 440 | url = mock_req.call_args.args[1] |
| 441 | qs = parse_qs(urlsplit(url).query) |
| 442 | assert qs["query"] == ["claude code"] |
| 443 | assert qs["optionalWords"] == ["code"] |
| 444 | assert '"' not in qs["query"][0] and '"' not in qs["optionalWords"][0] |
| 445 | |
| 446 | |
| 447 | # --------------------------------------------------------------------------- |
| 448 | # HIGH-197 & HIGH-198: stocktwits.py symbol gating & crypto alias gating |
| 449 | # --------------------------------------------------------------------------- |
| 450 | |
| 451 | |
| 452 | def test_high197_cashtag_handles_lowercase_suffixes(): |
| 453 | assert stocktwits.is_financial_topic("$btc.x") is True |
| 454 | assert stocktwits.is_financial_topic("$brk.b") is True |
| 455 | assert stocktwits.detect_symbols("$btc.x", resolve=False) == ["BTC.X"] |
| 456 | assert stocktwits.detect_symbols("$brk.b", resolve=False) == ["BRK.B"] |
| 457 | |
| 458 | |
| 459 | def test_high197_search_stocktwits_routes_short_words_and_names_via_detect_symbols(): |
| 460 | stream_ok = {"symbol": {"watchlist_count": 10}, "messages": [], "cursor": {"more": False}} |
| 461 | |
| 462 | def fake_get(url, timeout=20): |
| 463 | if "search/symbols.json" in url: |
| 464 | if "q=Apple" in url: |
| 465 | return {"results": [{"symbol": "AAPL"}]} |
| 466 | if "q=Tesla" in url: |
| 467 | return {"results": [{"symbol": "TSLA"}]} |
| 468 | return {"results": []} |
| 469 | return copy.deepcopy(stream_ok) |
| 470 | |
| 471 | with patch.object(stocktwits, "_get_json", side_effect=fake_get) as mock_get: |
| 472 | for query, expected_sym in [("btc", "BTC.X"), ("BTC", "BTC.X"), ("xrp", "XRP.X"), ("XRP", "XRP.X")]: |
| 473 | res = stocktwits.search_stocktwits(query) |
| 474 | assert res["symbols"] == [expected_sym] |
| 475 | assert mock_get.call_args.args[0].endswith(f"/symbol/{expected_sym}.json") |
| 476 | |
| 477 | for generic in ("defi", "DEFI", "stock", "STOCK", "Apple", "Tesla"): |
| 478 | mock_get.reset_mock() |
| 479 | res = stocktwits.search_stocktwits(generic) |
| 480 | assert res["symbols"] == [] |
| 481 | assert res["error"] == "no symbol resolved" |
| 482 | mock_get.assert_not_called() |
| 483 | |
| 484 | for phrase, expected_sym in [("Apple stock", "AAPL"), ("Tesla stock", "TSLA")]: |
| 485 | res = stocktwits.search_stocktwits(phrase) |
| 486 | assert res["symbols"] == [expected_sym] |
| 487 | |
| 488 | |
| 489 | @pytest.mark.parametrize( |
| 490 | ("raw", "expected"), |
| 491 | [ |
| 492 | ("$AAPL", "AAPL"), |
| 493 | ("$btc.x", "BTC.X"), |
| 494 | ("$brk.b", "BRK.B"), |
| 495 | ("AAPL", "AAPL"), |
| 496 | ("NVDA", "NVDA"), |
| 497 | ("TSLA", "TSLA"), |
| 498 | ("BRK.B", "BRK.B"), |
| 499 | ("BTC.X", "BTC.X"), |
| 500 | ], |
| 501 | ) |
| 502 | def test_high197_explicit_cashtags_and_uppercase_tickers_hit_stream_directly(raw, expected): |
| 503 | stream_ok = {"symbol": {"watchlist_count": 10}, "messages": [], "cursor": {"more": False}} |
| 504 | with patch.object(stocktwits, "_get_json", return_value=stream_ok) as mock_get: |
| 505 | res = stocktwits.search_stocktwits(raw) |
| 506 | assert res["symbols"] == [expected] |
| 507 | mock_get.assert_called_once() |
| 508 | assert mock_get.call_args.args[0].endswith(f"/symbol/{expected}.json") |
| 509 | |
| 510 | |
| 511 | @pytest.mark.parametrize( |
| 512 | "topic", |
| 513 | ["ADA compliance", "ETH Zurich", "ripple effect", "doge memes", "sol system"], |
| 514 | ) |
| 515 | def test_high198_ambiguous_short_crypto_aliases_blocked_on_non_financial_topics(topic): |
| 516 | assert stocktwits.is_financial_topic(topic) is False |
| 517 | assert stocktwits.detect_symbols(topic, resolve=False) == [] |
| 518 | with patch.object(stocktwits, "_get_json") as mock_get: |
| 519 | assert stocktwits.detect_symbols(topic, resolve=True) == [] |
| 520 | mock_get.assert_not_called() |
| 521 | |
| 522 | |
| 523 | @pytest.mark.parametrize( |
| 524 | ("topic", "expected"), |
| 525 | [ |
| 526 | ("ETH crypto", ["ETH.X"]), |
| 527 | ("Bitcoin", ["BTC.X"]), |
| 528 | ("$ETH", ["ETH"]), |
| 529 | ("Solana price", ["SOL.X"]), |
| 530 | ("ADA price target", ["ADA.X"]), |
| 531 | ("doge crypto", ["DOGE.X"]), |
| 532 | ("ripple crypto", ["XRP.X"]), |
| 533 | ], |
| 534 | ) |
| 535 | def test_high198_crypto_aliases_still_resolve_on_financial_topics_and_cashtags(topic, expected): |
| 536 | assert stocktwits.detect_symbols(topic, resolve=False) == expected |
| 537 | |
| 538 | |
| 539 | # --------------------------------------------------------------------------- |
| 540 | # HIGH-206: meta_ads.py 0-row _Fatal classification & transcript suppression |
| 541 | # --------------------------------------------------------------------------- |
| 542 | |
| 543 | |
| 544 | def _video_ad_row(ad_id: str = "1001") -> dict: |
| 545 | return { |
| 546 | "ad_archive_id": ad_id, |
| 547 | "collation_id": f"col-{ad_id}", |
| 548 | "collation_count": 1, |
| 549 | "page_id": "300000000000001", |
| 550 | "page_name": "Brightpan", |
| 551 | "is_active": True, |
| 552 | "start_date_string": "2026-09-01T07:00:00.000Z", |
| 553 | "end_date_string": "2026-09-14T07:00:00.000Z", |
| 554 | "publisher_platform": ["FACEBOOK", "INSTAGRAM"], |
| 555 | "url": f"https://www.facebook.com/ads/library/?id={ad_id}", |
| 556 | "snapshot": { |
| 557 | "body": {"text": "Shop Brightpan."}, |
| 558 | "title": "", |
| 559 | "cta_text": "Shop now", |
| 560 | "display_format": "VIDEO", |
| 561 | "link_url": "https://brightpan.example/kettles", |
| 562 | "cards": [], |
| 563 | "videos": [{"video_hd_url": "https://cdn.example/v.mp4"}], |
| 564 | }, |
| 565 | } |
| 566 | |
| 567 | |
| 568 | def _ads_envelope(rows: list[dict], *, key: str = "results", cursor: str = "") -> dict: |
| 569 | return { |
| 570 | "success": True, |
| 571 | key: rows, |
| 572 | "searchResultsCount": len(rows), |
| 573 | "cursor": cursor, |
| 574 | } |
| 575 | |
| 576 | |
| 577 | @pytest.mark.parametrize( |
| 578 | ("status", "expected_state"), |
| 579 | [ |
| 580 | (401, schema.AUTH_FAILED), |
| 581 | (402, schema.PAYMENT_REQUIRED), |
| 582 | (403, schema.AUTH_FAILED), |
| 583 | (429, schema.RATE_LIMITED), |
| 584 | ], |
| 585 | ) |
| 586 | def test_high206_zero_row_fatal_with_page_override_not_masked_as_partial(status, expected_state): |
| 587 | err = http.HTTPError(f"boom {status}", status_code=status) |
| 588 | with patch.object(meta_ads.http, "get", side_effect=err): |
| 589 | result = meta_ads.search_meta_ads( |
| 590 | "Brightpan", |
| 591 | "2026-08-15", |
| 592 | "2026-09-14", |
| 593 | token="fake-sc-key", |
| 594 | page_override="300000000000001", |
| 595 | ) |
| 596 | assert result["ads"] == [] |
| 597 | assert "partial" not in result |
| 598 | assert str(status) in result["error"] |
| 599 | |
| 600 | subquery = schema.SubQuery( |
| 601 | label="primary", search_query="Brightpan", ranking_query="Brightpan", sources=["meta_ads"], |
| 602 | ) |
| 603 | with patch.object(meta_ads.http, "get", side_effect=err): |
| 604 | items, artifact = pipeline._retrieve_stream_impl( |
| 605 | topic="Brightpan", |
| 606 | subquery=subquery, |
| 607 | source="meta_ads", |
| 608 | config={"SCRAPECREATORS_API_KEY": "fake-sc-key", "_meta_ads_page": "300000000000001"}, |
| 609 | depth="default", |
| 610 | date_range=("2026-08-15", "2026-09-14"), |
| 611 | runtime=schema.ProviderRuntime("none", "none", "none"), |
| 612 | mock=False, |
| 613 | raw_topic="Brightpan", |
| 614 | ) |
| 615 | assert items == [] |
| 616 | assert artifact["_source_outcome"]["state"] == expected_state |
| 617 | |
| 618 | |
| 619 | @pytest.mark.parametrize("status", [401, 402, 403, 429, 500]) |
| 620 | def test_high206_interrupted_window_fetch_skips_paid_transcript_calls(status): |
| 621 | discovery = _ads_envelope([_video_ad_row("1000")], key="searchResults") |
| 622 | page_one = _ads_envelope([_video_ad_row("1001")], key="results", cursor="cur-2") |
| 623 | boom = http.HTTPError(f"boom {status}", status_code=status) |
| 624 | responses = [discovery, page_one, boom] |
| 625 | calls: list[str] = [] |
| 626 | |
| 627 | def fake_get(url, **_kwargs): |
| 628 | calls.append(url) |
| 629 | nxt = responses.pop(0) |
| 630 | if isinstance(nxt, Exception): |
| 631 | raise nxt |
| 632 | return nxt |
| 633 | |
| 634 | with patch.object(meta_ads.http, "get", side_effect=fake_get): |
| 635 | result = meta_ads.search_meta_ads( |
| 636 | "Brightpan", "2026-08-15", "2026-09-14", depth="default", token="fake-sc-key", |
| 637 | ) |
| 638 | |
| 639 | assert meta_ads.AD_TRANSCRIPT_URL not in calls |
| 640 | assert len(calls) == 3 |
| 641 | assert len(result["ads"]) == 1 |
| 642 | assert result.get("partial") is True |
| 643 | assert result["tally"]["transcribed"] == 0 |
| 644 | assert str(status) in result["error"] |
| 645 | |
| 646 | |
| 647 | # --------------------------------------------------------------------------- |
| 648 | # PR #1611 Greptile review regressions |
| 649 | # --------------------------------------------------------------------------- |
| 650 | |
| 651 | |
| 652 | @pytest.mark.parametrize( |
| 653 | "exc", |
| 654 | [ |
| 655 | http.DeadlineExceeded(), |
| 656 | http.HTTPError("server error", status_code=503), |
| 657 | ], |
| 658 | ) |
| 659 | def test_greptile_registry_workday_unanswered_tries_owned_sitemap_first(_fresh_jobs_robots, exc): |
| 660 | sf_robots, sf_xml = _sitemap_xml("jobs.salesforce.com", "principal-distributed-systems-engineer") |
| 661 | asked: list[str] = [] |
| 662 | |
| 663 | def fake_get_text(url, *_args, **kwargs): |
| 664 | asked.append(url) |
| 665 | table = { |
| 666 | "https://jobs.salesforce.com/robots.txt": sf_robots, |
| 667 | "https://jobs.salesforce.com/jobs/sitemap.xml": sf_xml, |
| 668 | } |
| 669 | body = table.get(url) |
| 670 | if body is not None and kwargs.get("landed") is not None: |
| 671 | kwargs["landed"].append(url) |
| 672 | return body |
| 673 | |
| 674 | budget = jobs.LaneBudget(45.0) |
| 675 | with patch.object(jobs.http, "get_text", side_effect=fake_get_text), \ |
| 676 | patch.object(jobs.http, "post", side_effect=exc): |
| 677 | items, artifact = jobs.search_jobs( |
| 678 | "Salesforce", WINDOW, {}, web_backend="none", |
| 679 | site="https://www.salesforce.com/", budget=budget, |
| 680 | ) |
| 681 | |
| 682 | assert "https://jobs.salesforce.com/robots.txt" in asked |
| 683 | assert artifact["tier"] == "ats" |
| 684 | assert artifact["provider"] == "sitemap" |
| 685 | assert artifact["owned"] is True |
| 686 | assert artifact["board_sitemap_host"] == "jobs.salesforce.com" |
| 687 | assert "workday board did not answer" in artifact["board_fallback"] |
| 688 | assert "_source_outcome" not in artifact |
| 689 | assert [item["title"] for item in items] == ["Principal Distributed Systems Engineer"] |
| 690 | |
| 691 | |
| 692 | def test_greptile_registry_workday_unanswered_preserves_timeout_when_sitemap_and_web_empty( |
| 693 | _fresh_jobs_robots, |
| 694 | ): |
| 695 | budget = jobs.LaneBudget(45.0) |
| 696 | with patch.object(jobs.http, "get_text", return_value=None), \ |
| 697 | patch.object(jobs.http, "post", side_effect=http.HTTPError("503", status_code=503)), \ |
| 698 | patch.object(jobs, "search_jobs_web", return_value=([], {"tier": "web"})): |
| 699 | items, artifact = jobs.search_jobs( |
| 700 | "Salesforce", WINDOW, {}, web_backend="auto", |
| 701 | site="https://www.salesforce.com/", budget=budget, |
| 702 | ) |
| 703 | |
| 704 | assert items == [] |
| 705 | assert "job_site_unreadable" not in artifact |
| 706 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 707 | assert "salesforce.wd12/External_Career_Site did not answer" in artifact["_source_outcome"]["detail"] |
| 708 | assert "_source_out_of_time" not in artifact |
| 709 | |
| 710 | |
| 711 | @pytest.mark.parametrize( |
| 712 | ("topic", "expected_query", "expected_sym"), |
| 713 | [ |
| 714 | ("Equity Residential stock", "Equity Residential", "EQR"), |
| 715 | ("Capital One stock", "Capital One", "COF"), |
| 716 | ("Bank of America earnings", "Bank of America", "BAC"), |
| 717 | ("Digital Realty Trust stock", "Digital Realty Trust", "DLR"), |
| 718 | ("The Trade Desk stock", "The Trade Desk", "TTD"), |
| 719 | ], |
| 720 | ) |
| 721 | def test_greptile_stocktwits_preserves_company_name_words(topic, expected_query, expected_sym): |
| 722 | captured_q: list[str] = [] |
| 723 | |
| 724 | def fake_get(url, timeout=20): |
| 725 | qs = parse_qs(urlsplit(url).query) |
| 726 | captured_q.extend(qs.get("q", [])) |
| 727 | return {"results": [{"symbol": expected_sym}]} |
| 728 | |
| 729 | with patch.object(stocktwits, "_get_json", side_effect=fake_get): |
| 730 | syms = stocktwits.detect_symbols(topic, resolve=True) |
| 731 | |
| 732 | assert captured_q == [expected_query] |
| 733 | assert syms == [expected_sym] |
| 734 | |
| 735 | |
| 736 | def test_greptile_meta_ads_budget_exhausted_after_discovery_classifies_as_timeout(): |
| 737 | discovery = _ads_envelope([_video_ad_row("1000")], key="searchResults") |
| 738 | ticks = {"n": 0} |
| 739 | real_monotonic = meta_ads.time.monotonic |
| 740 | |
| 741 | def advancing_clock(): |
| 742 | ticks["n"] += 1 |
| 743 | # Budget initialized + discovery call pass; before first /company/ads call, budget expires. |
| 744 | return real_monotonic() + (0.0 if ticks["n"] <= 3 else 10_000.0) |
| 745 | |
| 746 | with patch.object(meta_ads.time, "monotonic", side_effect=advancing_clock), \ |
| 747 | patch.object(meta_ads.http, "get", side_effect=[discovery]) as mock_get: |
| 748 | result = meta_ads.search_meta_ads( |
| 749 | "Brightpan", "2026-08-15", "2026-09-14", depth="default", token="fake-sc-key", |
| 750 | ) |
| 751 | |
| 752 | assert mock_get.call_count == 1 |
| 753 | assert result["ads"] == [] |
| 754 | assert "partial" not in result |
| 755 | assert result.get("outcome_state") == health.TIMEOUT |
| 756 | assert "budget" in result["error"] |
| 757 | |
| 758 | subquery = schema.SubQuery( |
| 759 | label="primary", search_query="Brightpan", ranking_query="Brightpan", sources=["meta_ads"], |
| 760 | ) |
| 761 | ticks["n"] = 0 |
| 762 | with patch.object(meta_ads.time, "monotonic", side_effect=advancing_clock), \ |
| 763 | patch.object(meta_ads.http, "get", side_effect=[discovery]): |
| 764 | items, artifact = pipeline._retrieve_stream_impl( |
| 765 | topic="Brightpan", |
| 766 | subquery=subquery, |
| 767 | source="meta_ads", |
| 768 | config={"SCRAPECREATORS_API_KEY": "fake-sc-key"}, |
| 769 | depth="default", |
| 770 | date_range=("2026-08-15", "2026-09-14"), |
| 771 | runtime=schema.ProviderRuntime("none", "none", "none"), |
| 772 | mock=False, |
| 773 | raw_topic="Brightpan", |
| 774 | ) |
| 775 | |
| 776 | assert items == [] |
| 777 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 778 | |
| 779 | |
| 780 | def test_greptile_meta_ads_deadline_exceeded_on_first_window_call_classifies_as_timeout(): |
| 781 | discovery = _ads_envelope([_video_ad_row("1000")], key="searchResults") |
| 782 | subquery = schema.SubQuery( |
| 783 | label="primary", search_query="Brightpan", ranking_query="Brightpan", sources=["meta_ads"], |
| 784 | ) |
| 785 | with patch.object(meta_ads.http, "get", side_effect=[discovery, http.DeadlineExceeded()]): |
| 786 | items, artifact = pipeline._retrieve_stream_impl( |
| 787 | topic="Brightpan", |
| 788 | subquery=subquery, |
| 789 | source="meta_ads", |
| 790 | config={"SCRAPECREATORS_API_KEY": "fake-sc-key"}, |
| 791 | depth="default", |
| 792 | date_range=("2026-08-15", "2026-09-14"), |
| 793 | runtime=schema.ProviderRuntime("none", "none", "none"), |
| 794 | mock=False, |
| 795 | raw_topic="Brightpan", |
| 796 | ) |
| 797 | |
| 798 | assert items == [] |
| 799 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 800 | |
| 801 | |
| 802 | def test_greptile_jobs_teams_preserves_ampersands_when_company_not_adjacent(): |
| 803 | rows = [ |
| 804 | _team_role(f"Engineer {i}, Research &Development", i) for i in range(4) |
| 805 | ] + [ |
| 806 | _team_role(f"Scientist {i}, Acme Research &Development", i + 10) for i in range(4) |
| 807 | ] |
| 808 | result = jobs_teams.named_teams(rows, company="Acme", window_start="2026-10-15") |
| 809 | by_name = {t["name"]: t["roles"] for t in result["teams"]} |
| 810 | assert by_name == {"research &development": 8} |
| 811 | |
| 812 | mixed = [_team_role(f"Engineer {i}, R&D Cloud&AI", i) for i in range(4)] |
| 813 | mixed_result = jobs_teams.named_teams(mixed, company="AI", window_start="2026-10-15") |
| 814 | assert [t["name"] for t in mixed_result["teams"]] == ["r&d cloud"] |
| 815 | |
| 816 | |
| 817 | # --------------------------------------------------------------------------- |
| 818 | # PR #1611 Greptile round-2 regressions (4/5 -> 5/5) |
| 819 | # --------------------------------------------------------------------------- |
| 820 | |
| 821 | |
| 822 | def test_greptile2_registry_unanswered_sitemap_respects_discovery_share(_fresh_jobs_robots): |
| 823 | now = [1000.0] |
| 824 | budget = jobs.LaneBudget(45.0, clock=lambda: now[0]) |
| 825 | seen_remaining: list[float] = [] |
| 826 | seen_deadlines: list[float] = [] |
| 827 | |
| 828 | def fake_read_roster(hosts, *, company, deadline): |
| 829 | seen_remaining.append(budget.remaining()) |
| 830 | seen_deadlines.append(deadline - now[0]) |
| 831 | return [], {"board_total": 0} |
| 832 | |
| 833 | with patch.object(jobs.http, "get_text", return_value=None), \ |
| 834 | patch.object(jobs.http, "post", side_effect=http.HTTPError("503", status_code=503)), \ |
| 835 | patch.object(sitemap, "read_roster", side_effect=fake_read_roster): |
| 836 | items, artifact = jobs.search_jobs( |
| 837 | "Salesforce", WINDOW, {}, web_backend="none", |
| 838 | site="https://www.salesforce.com/", budget=budget, discovery_seconds=12.0, |
| 839 | ) |
| 840 | |
| 841 | assert items == [] |
| 842 | assert seen_remaining and seen_remaining[0] <= 12.0 |
| 843 | assert seen_deadlines and seen_deadlines[0] <= 12.0 |
| 844 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 845 | |
| 846 | |
| 847 | def test_greptile2_jobs_teams_spaced_ampersand_around_company_name(): |
| 848 | rows = ( |
| 849 | [_team_role(f"Engineer {i}, Cloud& AI&Data", i) for i in range(4)] |
| 850 | + [_team_role(f"Specialist {i}, Cloud&AI&Data", i + 10) for i in range(4)] |
| 851 | ) |
| 852 | result = jobs_teams.named_teams(rows, company="AI", window_start="2026-10-15") |
| 853 | by_name = {t["name"]: t["roles"] for t in result["teams"]} |
| 854 | assert by_name == {"cloud data": 8} |
| 855 | |
| 856 | |
| 857 | @pytest.mark.parametrize( |
| 858 | "topic", |
| 859 | [ |
| 860 | "crypto token", |
| 861 | "market cap", |
| 862 | "dividend valuation", |
| 863 | "pre-market trading", |
| 864 | "after hours", |
| 865 | "equity markets", |
| 866 | "defi tokens", |
| 867 | "crypto coin", |
| 868 | ], |
| 869 | ) |
| 870 | def test_greptile2_stocktwits_skips_generic_finance_only_topics(topic): |
| 871 | with patch.object(stocktwits, "_get_json") as mock_get: |
| 872 | assert stocktwits.detect_symbols(topic, resolve=True) == [] |
| 873 | mock_get.assert_not_called() |
| 874 | |
| 875 | |
| 876 | # --------------------------------------------------------------------------- |
| 877 | # PR #1611 Greptile round-3 regression (COIN stock vs crypto coin / CRYPTO COIN) |
| 878 | # --------------------------------------------------------------------------- |
| 879 | |
| 880 | |
| 881 | @pytest.mark.parametrize("topic", ["COIN stock", "COIN earnings"]) |
| 882 | def test_greptile3_stocktwits_allows_uppercase_ticker_matching_generic_word(topic): |
| 883 | captured_q: list[str] = [] |
| 884 | |
| 885 | def fake_get(url, timeout=20): |
| 886 | qs = parse_qs(urlsplit(url).query) |
| 887 | captured_q.extend(qs.get("q", [])) |
| 888 | return {"results": [{"symbol": "COIN"}]} |
| 889 | |
| 890 | with patch.object(stocktwits, "_get_json", side_effect=fake_get): |
| 891 | syms = stocktwits.detect_symbols(topic, resolve=True) |
| 892 | |
| 893 | assert captured_q == ["COIN"] |
| 894 | assert syms == ["COIN"] |
| 895 | |
| 896 | |
| 897 | @pytest.mark.parametrize("topic", ["crypto coin", "CRYPTO COIN"]) |
| 898 | def test_greptile3_stocktwits_still_blocks_generic_coin_phrases(topic): |
| 899 | with patch.object(stocktwits, "_get_json") as mock_get: |
| 900 | assert stocktwits.detect_symbols(topic, resolve=True) == [] |
| 901 | mock_get.assert_not_called() |
| 902 |