File size: 5,943 Bytes
d15f07c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""GET /api/data-centers/agenda-items (#250, DC-4.2): data center items on agendas.

The DB layer is mocked: ``get_db_pool`` returns a fake pool that records SQL and
params and returns canned rows (counts for the count query, items otherwise).
"""

from __future__ import annotations

import asyncio
from datetime import date
from typing import Any

import asyncpg
import httpx
import pytest
from fastapi import FastAPI

from api.routes import data_centers

PATH = "/api/data-centers/agenda-items"


class _Conn:
    def __init__(self, rows=None, counts=None, error: Exception | None = None):
        self.rows = rows or []
        self.counts = counts or []
        self.error = error
        self.calls: list[tuple[str, tuple[Any, ...]]] = []

    async def fetch(self, sql: str, *params: Any):
        self.calls.append((sql, params))
        if self.error:
            raise self.error
        return self.counts if "AS upcoming" in sql and "FROM data_center_agenda_item a WHERE" in sql and "LIMIT" not in sql else self.rows


class _Acquire:
    def __init__(self, conn):
        self.conn = conn

    async def __aenter__(self):
        return self.conn

    async def __aexit__(self, *_):
        return None


class _Pool:
    def __init__(self, conn):
        self.conn = conn

    def acquire(self):
        return _Acquire(self.conn)


@pytest.fixture
def get(monkeypatch):
    def _get(conn: _Conn, params: dict[str, Any] | None = None) -> httpx.Response:
        async def pool():
            return _Pool(conn)

        monkeypatch.setattr(data_centers, "get_db_pool", pool)
        app = FastAPI()
        app.include_router(data_centers.router, prefix="/api")

        async def go():
            async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
                return await c.get(PATH, params=params)

        return asyncio.run(go())

    return _get


def _item(**kw) -> dict[str, Any]:
    base = dict(
        data_center_agenda_item_id="d1", event_meeting_document_id="d1", jurisdiction_id="tuscaloosa_0177256",
        jurisdiction_name="Tuscaloosa", state_code="AL", state="Alabama", body_name="council",
        meeting_title="Regular Council Meeting", doc_date=date(2026, 12, 1), document_url="https://example.org/a.pdf",
        mentions_zoning_or_utility=True,
        evidence="request to rezone 400 acres for a proposed <mark>data</mark> <mark>center</mark>",
        data_center_site_id=None, site_name=None, is_upcoming=True,
    )
    base.update(kw)
    return base


def test_city_scope_counts_and_evidence(get) -> None:
    conn = _Conn(rows=[_item()], counts=[{"upcoming": 1, "past": 3}])
    resp = get(conn, {"state": "Alabama", "city": "Tuscaloosa"})
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["scope"]["level"] == "city" and body["scope"]["state_code"] == "AL" and body["scope"]["city"] == "Tuscaloosa"
    assert body["counts"] == {"upcoming": 1, "past": 3}
    (item,) = body["items"]
    assert "<mark>data</mark>" in item["evidence"] and item["is_upcoming"] is True
    assert item["doc_date"] == "2026-12-01" and item["mentions_zoning_or_utility"] is True
    items_sql, params = conn.calls[0]
    assert "a.state_code = $1" in items_sql and "a.jurisdiction_name ILIKE $2" in items_sql
    assert params == ("AL", "%Tuscaloosa%", 100)
    counts_sql, counts_params = conn.calls[1]
    assert counts_params == ("AL", "%Tuscaloosa%") and "current_date" in counts_sql


def test_when_filters_items_only() -> None:
    scope = data_centers.build_scope(None, None, None)
    up, p, cnt, cp = data_centers.build_agenda_queries(scope, "upcoming", 5)
    outer = lambda sql: sql.split(") c ON TRUE ")[1].split("ORDER BY")[0]  # noqa: E731 - the outer WHERE
    assert "a.doc_date >= current_date" in outer(up) and p == [5] and cp == []
    past, _, _, _ = data_centers.build_agenda_queries(scope, "past", 5)
    assert "a.doc_date < current_date" in outer(past)
    everything, _, _, _ = data_centers.build_agenda_queries(scope, "all", 5)
    assert "current_date" not in outer(everything)


def test_upcoming_sorts_first_soonest_first() -> None:
    sql, _, _, _ = data_centers.build_agenda_queries(data_centers.build_scope(None, None, None), "all", 5)
    order = sql.split("ORDER BY (a.doc_date", 1)[1]
    order = "(a.doc_date" + order
    assert order.index("(a.doc_date >= current_date) DESC") < order.index("THEN a.doc_date END ASC") < order.index("a.doc_date DESC")


def test_bad_when_is_422(get) -> None:
    assert get(_Conn(), {"when": "soon"}).status_code == 422


def test_missing_mart_is_an_empty_list(get) -> None:
    resp = get(_Conn(error=asyncpg.exceptions.UndefinedTableError("no relation")))
    assert resp.status_code == 200 and resp.json()["items"] == []


def test_other_errors_are_500(get) -> None:
    assert get(_Conn(error=RuntimeError("boom"))).status_code == 500


def test_local_concern_ranks_within_upcoming_and_past() -> None:
    """DC-4.3 (#251): an item naming the area's dominant concern ranks above one that doesn't."""
    sql, _, _, _ = data_centers.build_agenda_queries(data_centers.build_scope(None, None, None), "all", 5)
    order = "(a.doc_date" + sql.split("ORDER BY (a.doc_date", 1)[1]
    upcoming = order.index("(a.doc_date >= current_date) DESC")
    concern = order.index("coalesce(c.concern = ANY(a.concerns), false) DESC")
    by_date = order.index("THEN a.doc_date END ASC")
    assert upcoming < concern < by_date
    assert "ac.is_dominant" in sql and "ac.area_level = 'jurisdiction'" in sql


def test_items_carry_concern_fields(get) -> None:
    conn = _Conn(
        rows=[_item(concerns=["water"], local_concern="water", matches_local_concern=True)],
        counts=[{"upcoming": 1, "past": 0}],
    )
    (item,) = get(conn).json()["items"]
    assert item["concerns"] == ["water"] and item["local_concern"] == "water" and item["matches_local_concern"]