| 1 | """The person's own LinkedIn posts in a person run. |
| 2 | |
| 3 | Posts inside the window become ranked ``linkedin_profile`` items; older posts |
| 4 | (up to a year back) go to the Person Profile artifact only. These tests drive |
| 5 | ``pipeline.run`` with the Deepline posts read faked at ``lib.http.request`` |
| 6 | and every other source faked at ``_retrieve_stream``, and read the report. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | from datetime import date, timedelta |
| 12 | from unittest.mock import patch |
| 13 | |
| 14 | import pytest |
| 15 | |
| 16 | from lib import dates, http, person, pipeline, render |
| 17 | |
| 18 | NAME = "Dana Okafor" |
| 19 | PROFILE_URL = "https://www.linkedin.com/in/dana-okafor" |
| 20 | POSTS_TOOL = "harvestapi_get_profile_posts" |
| 21 | PLAN = { |
| 22 | "intent": "research", "freshness_mode": "balanced_recent", "cluster_mode": "topic", |
| 23 | "subqueries": [{"label": "primary", "search_query": NAME, |
| 24 | "ranking_query": f"What has {NAME} done lately?", "sources": ["reddit"]}], |
| 25 | } |
| 26 | |
| 27 | |
| 28 | def _days_ago(days: int) -> str: |
| 29 | _, to_date = dates.get_date_range(30) |
| 30 | return (date.fromisoformat(to_date) - timedelta(days=days)).isoformat() |
| 31 | |
| 32 | |
| 33 | def _context(**overrides) -> person.PersonContext: |
| 34 | ctx = person.PersonContext( |
| 35 | full_name=NAME, employer_name="Northwind Freight", employer_domain="northwind.example", |
| 36 | linkedin_url=PROFILE_URL, anchors=["Northwind Freight", "northwind.example", PROFILE_URL], |
| 37 | linkedin_status="checked", profile={"source": "deepline", "current_roles": []}, |
| 38 | ) |
| 39 | for key, value in overrides.items(): |
| 40 | setattr(ctx, key, value) |
| 41 | return ctx |
| 42 | |
| 43 | |
| 44 | def _element(index: int, days: int, text: str, *, reshare: bool = False) -> dict: |
| 45 | element = { |
| 46 | "id": f"p{index}", |
| 47 | "linkedinUrl": f"https://www.linkedin.com/posts/dana-okafor-{index}", |
| 48 | "content": text, |
| 49 | "postedAt": {"date": f"{_days_ago(days)}T09:00:00Z"}, |
| 50 | "author": {"name": NAME, "linkedinUrl": PROFILE_URL}, |
| 51 | "engagement": {"likes": 40 + index, "comments": 3, "shares": 1}, |
| 52 | } |
| 53 | if reshare: |
| 54 | element["repost"] = {"content": text} |
| 55 | return element |
| 56 | |
| 57 | |
| 58 | def _posts_response(elements: list[dict]) -> dict: |
| 59 | return {"status": "completed", "result": {"data": {"elements": elements, "pagination": {}}}} |
| 60 | |
| 61 | |
| 62 | def _fake_http(elements=None, *, error: http.HTTPError | None = None): |
| 63 | calls: list[dict] = [] |
| 64 | |
| 65 | def request(method, url, **kwargs): |
| 66 | calls.append({"url": url, "payload": (kwargs.get("json_data") or {}).get("payload")}) |
| 67 | assert url.endswith(f"/{POSTS_TOOL}/execute"), url |
| 68 | if error is not None: |
| 69 | raise error |
| 70 | return _posts_response(elements or []) |
| 71 | |
| 72 | return request, calls |
| 73 | |
| 74 | |
| 75 | def _run(config: dict, *, request=None, sources=("reddit",)): |
| 76 | patches = [ |
| 77 | patch.object(pipeline, "_retrieve_stream", return_value=([], {})), |
| 78 | patch.object(pipeline, "_retry_thin_sources"), |
| 79 | ] |
| 80 | if request is not None: |
| 81 | patches.append(patch.object(http, "request", side_effect=request)) |
| 82 | for p in patches: |
| 83 | p.start() |
| 84 | try: |
| 85 | return pipeline.run( |
| 86 | topic=NAME, config=config, depth="quick", requested_sources=list(sources), |
| 87 | web_backend="none", external_plan=PLAN, |
| 88 | ) |
| 89 | finally: |
| 90 | for p in reversed(patches): |
| 91 | p.stop() |
| 92 | |
| 93 | |
| 94 | def test_in_window_posts_rank_and_older_posts_go_to_the_artifact_only(): |
| 95 | ctx = _context() |
| 96 | request, calls = _fake_http([ |
| 97 | _element(1, 5, "Our cold-chain lanes cut dwell time by a third this quarter."), |
| 98 | _element(2, 20, "Hiring two planners for the Rotterdam hub this month."), |
| 99 | _element(3, 120, "Notes from the regional logistics meetup in the spring."), |
| 100 | ]) |
| 101 | report = _run({"DEEPLINE_API_KEY": "test-key", "_person": ctx}, request=request) |
| 102 | |
| 103 | assert len(calls) == 1 |
| 104 | assert calls[0]["payload"]["scrapePostedLimit"] == "year" |
| 105 | ranked_urls = {c.url for c in report.ranked_candidates} |
| 106 | assert ranked_urls == { |
| 107 | "https://www.linkedin.com/posts/dana-okafor-1", |
| 108 | "https://www.linkedin.com/posts/dana-okafor-2", |
| 109 | } |
| 110 | items = report.items_by_source["linkedin_profile"] |
| 111 | assert len(items) == 2 |
| 112 | assert all(item.metadata["identity_anchor"] is True for item in items) |
| 113 | assert all(item.author == NAME for item in items) |
| 114 | assert all(item.engagement.get("likes") for item in items) |
| 115 | |
| 116 | profile = report.artifacts["person_profile"] |
| 117 | assert [post["url"] for post in profile["older_posts"]] == [ |
| 118 | "https://www.linkedin.com/posts/dana-okafor-3", |
| 119 | ] |
| 120 | assert profile["older_posts"][0]["date"] == _days_ago(120) |
| 121 | assert profile["in_window_posts"] == 2 |
| 122 | assert profile["first_party_in_window"] == 2 |
| 123 | assert report.source_status["linkedin_profile"].items_returned == 2 |
| 124 | |
| 125 | |
| 126 | def test_older_posts_are_newest_first_truncated_and_capped(): |
| 127 | ctx = _context() |
| 128 | long_text = "Freight planning notes " * 40 |
| 129 | request, _ = _fake_http( |
| 130 | [_element(i, 40 + 30 * i, long_text) for i in range(1, 9)] |
| 131 | + [_element(20, 500, "Too old to show.")] |
| 132 | ) |
| 133 | report = _run({"DEEPLINE_API_KEY": "test-key", "_person": ctx}, request=request) |
| 134 | |
| 135 | older = report.artifacts["person_profile"]["older_posts"] |
| 136 | assert len(older) == 6 |
| 137 | assert [post["date"] for post in older] == sorted((p["date"] for p in older), reverse=True) |
| 138 | assert all(len(post["text"]) <= 301 for post in older) |
| 139 | assert "Too old to show." not in {post["text"] for post in older} |
| 140 | assert not report.items_by_source.get("linkedin_profile") |
| 141 | |
| 142 | |
| 143 | def test_reshares_carry_the_flag_and_render_as_reshares(): |
| 144 | ctx = _context() |
| 145 | request, _ = _fake_http([ |
| 146 | _element(1, 3, "Northwind Freight opens a new cross-dock in Rotterdam.", reshare=True), |
| 147 | _element(2, 60, "An older reshare about warehouse robotics.", reshare=True), |
| 148 | ]) |
| 149 | report = _run({"DEEPLINE_API_KEY": "test-key", "_person": ctx}, request=request) |
| 150 | |
| 151 | [item] = report.items_by_source["linkedin_profile"] |
| 152 | assert item.metadata["is_reshare"] is True |
| 153 | assert report.artifacts["person_profile"]["older_posts"][0]["is_reshare"] is True |
| 154 | rendered = render.render_compact(report) |
| 155 | assert "Reshared: Northwind Freight opens a new cross-dock" in rendered |
| 156 | |
| 157 | |
| 158 | def test_a_post_another_member_wrote_counts_as_a_reshare(): |
| 159 | ctx = _context() |
| 160 | other = _element(1, 3, "Episode 12 with Dana Okafor is out now.") |
| 161 | other["author"] = {"name": "Lee Marsh", "linkedinUrl": "https://www.linkedin.com/in/lee-marsh", |
| 162 | "publicIdentifier": "lee-marsh"} |
| 163 | own = _element(2, 5, "Our Rotterdam cross-dock is live.") |
| 164 | own["author"]["publicIdentifier"] = "dana-okafor" |
| 165 | request, _ = _fake_http([other, own]) |
| 166 | report = _run({"DEEPLINE_API_KEY": "test-key", "_person": ctx}, request=request) |
| 167 | |
| 168 | flags = {item.url: item.metadata["is_reshare"] for item in report.items_by_source["linkedin_profile"]} |
| 169 | assert flags == { |
| 170 | "https://www.linkedin.com/posts/dana-okafor-1": True, |
| 171 | "https://www.linkedin.com/posts/dana-okafor-2": False, |
| 172 | } |
| 173 | |
| 174 | |
| 175 | def test_posts_read_failure_is_recorded_and_the_run_completes(): |
| 176 | ctx = _context() |
| 177 | request, _ = _fake_http(error=http.HTTPError("server error", status_code=500)) |
| 178 | report = _run({"DEEPLINE_API_KEY": "test-key", "_person": ctx}, request=request) |
| 179 | |
| 180 | status = report.source_status["linkedin_profile"] |
| 181 | assert status.state != "ok" |
| 182 | assert status.items_returned == 0 |
| 183 | assert "linkedin_profile" in report.errors_by_source |
| 184 | assert report.artifacts["person_profile"]["older_posts"] == [] |
| 185 | assert report.artifacts["person_profile"]["posts_read"] is False |
| 186 | |
| 187 | |
| 188 | def test_no_posts_in_window_records_no_results_without_a_keyword_backfill(): |
| 189 | ctx = _context() |
| 190 | request, _ = _fake_http([_element(1, 90, "A quarter-old post about routing.")]) |
| 191 | report = _run({"DEEPLINE_API_KEY": "test-key", "_person": ctx}, request=request) |
| 192 | |
| 193 | assert report.source_status["linkedin_profile"].state == "no-results" |
| 194 | assert not report.items_by_source.get("linkedin_profile") |
| 195 | assert report.artifacts["person_profile"]["posts_read"] is True |
| 196 | assert len(report.artifacts["person_profile"]["older_posts"]) == 1 |
| 197 | |
| 198 | |
| 199 | def test_scrapecreators_profile_posts_feed_the_lane_without_a_paid_read(): |
| 200 | ctx = _context(profile={"source": "scrapecreators", "posts": [ |
| 201 | {"url": "https://www.linkedin.com/posts/dana-okafor-9", "date": _days_ago(4), |
| 202 | "text": "Kicking off the winter peak plan with the dispatch team.", "is_reshare": False}, |
| 203 | {"url": "https://www.linkedin.com/posts/dana-okafor-8", "date": _days_ago(75), |
| 204 | "text": "Summer recap from the freight desk.", "is_reshare": False}, |
| 205 | ]}) |
| 206 | |
| 207 | def no_network(*_args, **_kwargs): |
| 208 | raise AssertionError("no paid call expected") |
| 209 | |
| 210 | report = _run({"SCRAPECREATORS_API_KEY": "sc-key", "_person": ctx}, request=no_network) |
| 211 | assert [i.url for i in report.items_by_source["linkedin_profile"]] == [ |
| 212 | "https://www.linkedin.com/posts/dana-okafor-9", |
| 213 | ] |
| 214 | assert len(report.artifacts["person_profile"]["older_posts"]) == 1 |
| 215 | |
| 216 | |
| 217 | @pytest.mark.parametrize("config", [ |
| 218 | {"DEEPLINE_API_KEY": "test-key"}, |
| 219 | {"DEEPLINE_API_KEY": "test-key", "_person": _context(linkedin_status="no key")}, |
| 220 | {"DEEPLINE_API_KEY": "test-key", "_person": _context(linkedin_url="")}, |
| 221 | {"_person": _context()}, |
| 222 | ]) |
| 223 | def test_source_unavailable_without_a_person_run_an_anchored_profile_and_a_key(config): |
| 224 | assert "linkedin_profile" not in pipeline.available_sources(config) |
| 225 | |
| 226 | |
| 227 | def test_source_available_for_an_anchored_person_run_with_a_key(): |
| 228 | assert "linkedin_profile" in pipeline.available_sources( |
| 229 | {"DEEPLINE_API_KEY": "test-key", "_person": _context()} |
| 230 | ) |
| 231 | |
| 232 | |
| 233 | def test_non_person_run_reads_no_posts_and_carries_no_person_profile(): |
| 234 | def no_network(*_args, **_kwargs): |
| 235 | raise AssertionError("no posts read expected") |
| 236 | |
| 237 | report = _run({"DEEPLINE_API_KEY": "test-key"}, request=no_network) |
| 238 | assert "linkedin_profile" not in report.source_status |
| 239 | assert "person_profile" not in report.artifacts |
| 240 | |
| 241 | |
| 242 | def test_person_run_without_a_linkedin_check_still_carries_the_person_profile(): |
| 243 | ctx = _context(linkedin_status="no key", linkedin_url="", profile={}) |
| 244 | report = _run({"_person": ctx}) |
| 245 | profile = report.artifacts["person_profile"] |
| 246 | assert profile["full_name"] == NAME |
| 247 | assert profile["linkedin_status"] == "no key" |
| 248 | assert profile["in_window_posts"] == 0 |
| 249 | assert "linkedin_profile" not in report.source_status |
| 250 | |
| 251 | |
| 252 | def test_a_failed_second_page_keeps_page_one_and_marks_the_read_incomplete(): |
| 253 | ctx = _context() |
| 254 | calls: list[str] = [] |
| 255 | |
| 256 | def request(method, url, **kwargs): |
| 257 | calls.append(url) |
| 258 | if len(calls) == 1: |
| 259 | page = _posts_response([_element(1, 3, "Kicking off the winter peak plan.")]) |
| 260 | page["result"]["data"]["pagination"] = {"paginationToken": "page-2"} |
| 261 | return page |
| 262 | raise http.HTTPError("server error", status_code=500) |
| 263 | |
| 264 | report = _run({"DEEPLINE_API_KEY": "test-key", "_person": ctx}, request=request) |
| 265 | |
| 266 | assert len(calls) >= 2 |
| 267 | assert len(report.items_by_source["linkedin_profile"]) == 1 |
| 268 | profile = report.artifacts["person_profile"] |
| 269 | assert profile["posts_read"] is False |
| 270 | assert profile["in_window_posts"] == 1 |
| 271 |