File size: 11,834 Bytes
a8fb296
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
"""Unit tests for api/routes/trending.py database resolution, caching, and fallback logic."""
from __future__ import annotations

import asyncio
from contextlib import contextmanager
from typing import Any, List
import pytest
import psycopg2

from api.routes import trending


@pytest.fixture(autouse=True)
def _reset_trending_cache():
    trending.clear_trending_cache()
    yield
    trending.clear_trending_cache()


class _FakeConnection:
    def __init__(self) -> None:
        self.rollbacks = 0
        self.closed = False

    def rollback(self) -> None:
        self.rollbacks += 1

    def close(self) -> None:
        self.closed = True


class _FakeCursor:
    def __init__(self, handler, conn: _FakeConnection) -> None:
        self._handler = handler
        self.connection = conn
        self._rows: List[Any] = []
        self.queries: List[tuple[str, Any]] = []

    def execute(self, sql: str, params: Any = None) -> None:
        self.queries.append((sql, params))
        self._rows = self._handler(sql, params)

    def fetchall(self) -> List[Any]:
        return list(self._rows)

    def fetchone(self) -> Any:
        return self._rows[0] if self._rows else None

    def __enter__(self) -> "_FakeCursor":
        return self

    def __exit__(self, exc_type, exc, tb) -> None:
        return None


def test_resolve_db_url_priority_and_postgres_scheme(monkeypatch: pytest.MonkeyPatch):
    for key in trending._DB_ENV_PRIORITY:
        monkeypatch.delenv(key, raising=False)

    assert trending.resolve_db_url() == trending._DEFAULT_LOCAL_DB_URL

    monkeypatch.setenv("DATABASE_URL", "postgres://user:pass@db.example.com:5432/prod")
    assert trending.resolve_db_url() == "postgresql://user:pass@db.example.com:5432/prod"

    monkeypatch.setenv("OPEN_NAVIGATOR_DATABASE_URL", "postgresql://nav:pass@nav.example.com:5432/nav")
    assert trending.resolve_db_url() == "postgresql://nav:pass@nav.example.com:5432/nav"

    monkeypatch.setenv("NEON_DATABASE_URL", "postgres://neon:pass@neon.example.com:5432/neon")
    assert trending.resolve_db_url() == "postgresql://neon:pass@neon.example.com:5432/neon"

    monkeypatch.setenv("NEON_DATABASE_URL_DEV", "postgresql://dev:pass@localhost:5433/dev")
    assert trending.resolve_db_url() == "postgresql://dev:pass@localhost:5433/dev"


def test_everyorg_causes_linkage_mart_fallback_rolls_back_same_connection(
    monkeypatch: pytest.MonkeyPatch,
):
    conn = _FakeConnection()
    connect_calls = 0

    def handler(sql: str, params: Any):
        if "gold.meeting_cause_link" in sql:
            raise psycopg2.errors.UndefinedTable("relation gold.meeting_cause_link does not exist")
        return [
            ("education", "Education", "Schools and learning", "πŸ“š", "human_services", 1, 0),
            ("housing", "Housing", "Affordable housing", "🏠", "community", 2, 0),
        ]

    @contextmanager
    def fake_cursor():
        nonlocal connect_calls
        connect_calls += 1
        yield _FakeCursor(handler, conn)

    monkeypatch.setattr(trending, "_cursor", fake_cursor)

    items = trending.get_everyorg_causes(limit=5, state="Alabama", city="Tuscaloosa")
    assert connect_calls == 1
    assert conn.rollbacks == 1
    assert len(items) == 2
    assert items[0].cause_id == "education"
    assert items[0].meeting_count == 0
    assert items[0].image_url == "/images/causes/everyorg_education_square.png"


def test_ntee_causes_populates_cause_id_and_uses_single_connection_on_fallback(
    monkeypatch: pytest.MonkeyPatch,
):
    conn = _FakeConnection()
    connect_calls = 0

    def handler(sql: str, params: Any):
        if "bronze.bronze_ntee_codes" in sql:
            raise psycopg2.errors.UndefinedTable("bronze.bronze_ntee_codes missing")
        assert "FROM public.tag" in sql
        return [
            ("A", "Arts, Culture & Humanities", "Cultural organizations", "ntee"),
            ("B", "Education", "Educational institutions", "ntee"),
        ]

    @contextmanager
    def fake_cursor():
        nonlocal connect_calls
        connect_calls += 1
        yield _FakeCursor(handler, conn)

    monkeypatch.setattr(trending, "_cursor", fake_cursor)

    items = trending.get_ntee_causes(limit=5, level=1)
    assert connect_calls == 1
    assert conn.rollbacks == 1
    assert len(items) == 2
    assert items[0].cause_id == "A"
    assert items[0].icon == "🎨"
    assert items[1].cause_id == "B"
    assert items[1].icon == "πŸ“š"


@pytest.mark.asyncio
async def test_get_trending_causes_mixed_handles_limit_one_and_odd_limits(
    monkeypatch: pytest.MonkeyPatch,
):
    monkeypatch.setattr(
        trending,
        "get_everyorg_causes",
        lambda limit=20, state=None, city=None: [
            trending.CauseItem(
                cause_id=f"eo-{i}",
                name=f"EveryOrg {i}",
                icon="πŸ“Œ",
                category="general",
            )
            for i in range(limit)
        ],
    )
    monkeypatch.setattr(
        trending,
        "get_ntee_causes",
        lambda limit=20, level=None: [
            trending.CauseItem(
                cause_id=f"ntee-{i}",
                name=f"NTEE {i}",
                icon="πŸ“š",
                category="ntee",
            )
            for i in range(limit)
        ],
    )

    res_one = await trending.get_trending_causes(source="mixed", limit=1, level=None, state=None, city=None)
    assert res_one.total == 1
    assert len(res_one.causes) == 1
    assert res_one.causes[0].cause_id == "eo-0"

    res_three = await trending.get_trending_causes(source="mixed", limit=3, level=1, state=None, city=None)
    assert res_three.total == 3
    assert [c.cause_id for c in res_three.causes] == ["eo-0", "ntee-0", "eo-1"]


@pytest.mark.asyncio
async def test_get_trending_causes_inflight_deduplication_and_cache(
    monkeypatch: pytest.MonkeyPatch,
):
    call_count = 0

    def slow_everyorg(limit=20, state=None, city=None):
        nonlocal call_count
        call_count += 1
        return [
            trending.CauseItem(
                cause_id="environment",
                name="Environment",
                icon="🌍",
                category="environment",
                meeting_count=7,
            )
        ]

    monkeypatch.setattr(trending, "get_everyorg_causes", slow_everyorg)

    results = await asyncio.gather(
        *[
            trending.get_trending_causes(
                source="everyorg", limit=6, level=None, state="Georgia", city="Atlanta"
            )
            for _ in range(5)
        ]
    )

    assert call_count == 1
    for res in results:
        assert res.total == 1
        assert res.causes[0].cause_id == "environment"
        assert res.causes[0].meeting_count == 7


@pytest.mark.asyncio
async def test_get_trending_topics_state_and_missing_table_fallback(
    monkeypatch: pytest.MonkeyPatch,
):
    conn = _FakeConnection()
    should_fail = False

    def handler(sql: str, params: Any):
        if should_fail:
            raise psycopg2.errors.UndefinedTable("public.rpt_bill_map_aggregate missing")
        assert params == ("AL", 5)
        return [("Education", 42, 9, "AL"), ("Health", 18, 4, "AL")]

    @contextmanager
    def fake_cursor():
        yield _FakeCursor(handler, conn)

    monkeypatch.setattr(trending, "_cursor", fake_cursor)

    should_fail = True
    empty_res = await trending.get_trending_topics(state="Alabama", limit=5)
    assert empty_res.total == 0
    assert empty_res.topics == []

    # Empty fallback should not poison the cache; subsequent call after table creation succeeds.
    should_fail = False
    ok_res = await trending.get_trending_topics(state="Alabama", limit=5)
    assert ok_res.total == 2
    assert ok_res.topics[0].name == "Education"
    assert ok_res.topics[0].recent_bill_count == 9
    assert ok_res.topics[0].state_code == "AL"


@pytest.mark.asyncio
async def test_get_trending_stats_reuses_single_connection_with_tag_fallback(
    monkeypatch: pytest.MonkeyPatch,
):
    conn = _FakeConnection()
    connect_calls = 0

    def handler(sql: str, params: Any):
        if "bronze.bronze_everyorg_causes" in sql:
            return [(38,)]
        if "bronze.bronze_ntee_codes" in sql:
            raise psycopg2.errors.UndefinedTable("bronze.bronze_ntee_codes not found")
        if "public.tag" in sql:
            return [(26,)]
        raise AssertionError(f"Unexpected SQL: {sql}")

    @contextmanager
    def fake_cursor():
        nonlocal connect_calls
        connect_calls += 1
        yield _FakeCursor(handler, conn)

    monkeypatch.setattr(trending, "_cursor", fake_cursor)

    stats = await trending.get_trending_stats()
    assert connect_calls == 1
    assert conn.rollbacks == 1
    assert stats["everyorg_causes"] == 38
    assert stats["ntee_causes"] == 26
    assert stats["total_causes"] == 64


def test_bounded_cache_evicts_oldest_when_full(monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setattr(trending, "_MAX_CACHE_ENTRIES", 3)
    trending._set_cached("k1", "v1")
    trending._set_cached("k2", "v2")
    trending._set_cached("k3", "v3")
    trending._set_cached("k4", "v4")

    assert len(trending._trending_cache) == 3
    assert trending._get_cached("k1") is None
    assert trending._get_cached("k2") == "v2"
    assert trending._get_cached("k4") == "v4"


@pytest.mark.asyncio
async def test_inflight_locks_do_not_grow_across_distinct_cities(monkeypatch: pytest.MonkeyPatch):
    """#447: one lock per free-text ?city= value used to stay in the map for the life of the process."""
    monkeypatch.setattr(
        trending,
        "get_everyorg_causes",
        lambda limit=20, state=None, city=None: [
            trending.CauseItem(cause_id="environment", name="Environment", icon="🌍", category="environment")
        ],
    )
    for i in range(200):
        await trending.get_trending_causes(source="everyorg", limit=6, level=None, state="Georgia", city=f"City {i}")
    assert trending._inflight_locks == {}
    assert trending._inflight_users == {}


@pytest.mark.asyncio
async def test_inflight_lock_is_removed_even_when_the_fill_fails(monkeypatch: pytest.MonkeyPatch):
    def boom(limit=20, state=None, city=None):
        raise RuntimeError("database down")

    monkeypatch.setattr(trending, "get_everyorg_causes", boom)
    with pytest.raises(RuntimeError):
        await trending.get_trending_causes(source="everyorg", limit=6, level=None, state=None, city="Atlanta")
    assert trending._inflight_locks == {} and trending._inflight_users == {}


@pytest.mark.asyncio
async def test_inflight_lock_is_kept_while_a_waiter_needs_it_and_never_removes_a_newer_lock():
    key = "causes:test"
    first_in, release_first = asyncio.Event(), asyncio.Event()

    async def first():
        async with trending._inflight(key):
            first_in.set()
            await release_first.wait()

    async def second():
        async with trending._inflight(key):
            pass

    t1 = asyncio.create_task(first())
    await asyncio.wait_for(first_in.wait(), timeout=5)   # fail, don't hang, if the first holder never starts
    t2 = asyncio.create_task(second())
    await asyncio.sleep(0)                 # second is now waiting on the same lock
    assert trending._inflight_users[key] == 2
    held = trending._inflight_locks[key]
    release_first.set()
    await asyncio.wait_for(asyncio.gather(t1, t2), timeout=5)
    assert trending._inflight_locks == {} and trending._inflight_users == {}

    # a lock another request put in the map is never removed by a request that held an older one
    stale = asyncio.Lock()
    trending._inflight_locks[key] = stale
    trending._inflight_users[key] = 1
    async with trending._inflight("other"):
        pass
    assert trending._inflight_locks[key] is stale and held is not stale