Coverage for app/backend/src/tests/test_community_checks.py: 100%
164 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-23 00:24 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-23 00:24 +0000
1import json
2from dataclasses import dataclass
3from datetime import timedelta
5import grpc
6import pytest
7from google.protobuf import empty_pb2
8from sqlalchemy import func, select, update
10from couchers.db import session_scope
11from couchers.helpers.community_checks import Issue, find_issues
12from couchers.models import Cluster, CommunityCheckRun, CommunityIssue, Node, NodeType, User
13from couchers.proto import communities_pb2, editor_pb2
14from couchers.utils import Timestamp_from_datetime, create_coordinate, now
15from tests.fixtures.db import generate_user
16from tests.fixtures.misc import process_jobs
17from tests.fixtures.rpc_errors import expect_rpc_error
18from tests.fixtures.sessions import real_editor_session
21def box(x0: float, y0: float, x1: float, y1: float) -> str:
22 return f"MULTIPOLYGON((({x0} {y0}, {x1} {y0}, {x1} {y1}, {x0} {y1}, {x0} {y0})))"
25def add_community(
26 parent_id: int | None, node_type: NodeType, name: str, geom: str, *, official_cluster: bool = True
27) -> int:
28 with session_scope() as session:
29 node = Node(parent_node_id=parent_id, node_type=node_type, geom=func.ST_GeomFromText(geom, 4326))
30 session.add(node)
31 session.flush()
32 if official_cluster:
33 session.add(Cluster(parent_node_id=node.id, name=name, description="", is_official_cluster=True))
34 return node.id
37def move_boundary(node_id: int, geom: str) -> None:
38 with session_scope() as session:
39 session.execute(update(Node).where(Node.id == node_id).values(geom=func.ST_GeomFromText(geom, 4326)))
42@dataclass
43class World:
44 world: int
45 continent: int
46 country: int
47 city: int
50@pytest.fixture
51def world(db) -> World:
52 world = add_community(None, NodeType.world, "Global", box(-180, -89, 180, 89))
53 continent = add_community(world, NodeType.macroregion, "Continent", box(0, 0, 40, 40))
54 country = add_community(continent, NodeType.region, "Country", box(0, 0, 10, 10))
55 city = add_community(country, NodeType.locality, "City", box(1, 1, 1.5, 1.5))
56 return World(world, continent, country, city)
59def find() -> list[Issue]:
60 with session_scope() as session:
61 return sorted(find_issues(session), key=lambda issue: str(issue.key))
64def key(issue: Issue) -> tuple[str, int, int | None]:
65 return (issue.rule, issue.community.id, issue.other.id if issue.other else None)
68def found() -> list[tuple[str, int, int | None]]:
69 return [key(issue) for issue in find()]
72def test_clean_hierarchy_passes(world: World):
73 assert found() == []
76def test_city_reaching_outside_its_country(world: World):
77 town = add_community(world.country, NodeType.locality, "Border town", box(9.8, 1, 10.3, 1.5))
79 [issue] = find()
81 assert found() == [("outside_parent", town, world.country)]
82 assert issue.share == pytest.approx(0.6, abs=0.01)
83 assert issue.priority.name == "medium"
86def test_overlapping_cities(world: World):
87 neighbour = add_community(world.country, NodeType.locality, "Neighbour", box(1.2, 1, 1.65, 1.5))
89 [issue] = find()
91 assert found() == [("overlap", neighbour, world.city)]
92 assert issue.share == pytest.approx(0.67, abs=0.01)
93 assert issue.priority.name == "high"
94 assert issue.area_geojson is not None
95 assert json.loads(issue.area_geojson)["type"] == "Polygon"
98def test_a_community_inside_another_below_it_is_not_an_overlap(world: World):
99 add_community(world.city, NodeType.sublocality, "Old town", box(1.1, 1.1, 1.2, 1.2))
101 assert found() == []
104def test_countries_along_borders_are_low_priority(world: World):
105 neighbour = add_community(world.continent, NodeType.region, "Neighbouring country", box(9.5, -1, 12, 2))
106 town = add_community(neighbour, NodeType.locality, "Town across the border", box(9.8, 0.5, 10.4, 1))
108 assert {key(issue): issue.priority.name for issue in find()} == {
109 ("outside_parent", neighbour, world.continent): "low",
110 ("overlap", neighbour, world.country): "low",
111 ("overlap", town, world.country): "medium",
112 }
115def test_types(world: World):
116 city = add_community(world.continent, NodeType.locality, "City under a continent", box(20, 20, 20.5, 20.5))
117 state = add_community(world.country, NodeType.region, "State as big as its country", box(5, 5, 5.5, 5.5))
119 assert found() == [("type_by_level", city, world.continent), ("type_not_below_parent", state, world.country)]
122def test_parent_loop(world: World):
123 a = add_community(None, NodeType.locality, "A", box(2, 2, 2.5, 2.5))
124 b = add_community(a, NodeType.locality, "B", box(3, 3, 3.5, 3.5))
125 with session_scope() as session:
126 session.execute(update(Node).where(Node.id == a).values(parent_node_id=b))
127 add_community(b, NodeType.sublocality, "Below the loop", box(3.1, 3.1, 3.2, 3.2))
129 loops = [issue for issue in find() if issue.rule == "parent_loop"]
131 assert [issue.community.id for issue in loops] == sorted([a, b], key=str)
132 assert loops[0].details in (
133 f"The parent links go round in a loop: A ({a}) → B ({b}) → A ({a}).",
134 f"The parent links go round in a loop: B ({b}) → A ({a}) → B ({b}).",
135 )
138def test_missing_parent_and_official_cluster(world: World):
139 floating = add_community(None, NodeType.locality, "Floating", box(100, 50, 100.5, 50.5))
140 nameless = add_community(world.country, NodeType.locality, "Nameless", box(3, 3, 3.5, 3.5), official_cluster=False)
142 assert found() == [("missing_parent", floating, None), ("official_cluster", nameless, None)]
145def test_duplicate_and_invalid_boundaries(world: World):
146 copy = add_community(world.country, NodeType.locality, "City", box(1, 1, 1.5, 1.5))
147 bowtie = add_community(
148 world.country, NodeType.locality, "Bowtie", "MULTIPOLYGON(((5 5, 5.5 5.5, 5.5 5, 5 5.5, 5 5)))"
149 )
151 assert found() == [("duplicate_boundary", copy, world.city), ("invalid_boundary", bowtie, None)]
154def test_oversized_city(world: World):
155 sprawl = add_community(world.country, NodeType.locality, "Sprawl", box(5, 5, 7, 7))
156 add_community(world.country, NodeType.subregion, "Large island", box(2, 5, 4, 7))
158 assert found() == [("oversized_city", sprawl, None)]
159 assert [issue.priority.name for issue in find()] == ["low"]
162def test_a_city_across_the_date_line_is_measured_where_it_is(world: World):
163 nation = add_community(world.continent, NodeType.region, "Island nation", box(179, 0, 180.5, 1))
164 add_community(nation, NodeType.locality, "Island town", box(179.9, 0.2, 180.2, 0.5))
166 assert [issue for issue in find() if issue.rule == "oversized_city"] == []
169def test_issues_stay_open_until_fixed_and_are_served(world: World):
170 editor, editor_token = generate_user(is_editor=True)
171 neighbour = add_community(world.country, NodeType.locality, "Neighbour", box(1.2, 1, 1.65, 1.5))
173 with real_editor_session(editor_token) as api:
174 res = api.ListCommunityIssues(editor_pb2.ListCommunityIssuesReq())
175 assert not res.HasField("last_run")
176 assert list(res.open_issues) == []
178 api.RunCommunityChecks(empty_pb2.Empty())
179 process_jobs()
180 with session_scope() as session:
181 first_seen = session.execute(select(CommunityIssue.first_seen)).scalar_one()
183 api.RunCommunityChecks(empty_pb2.Empty())
184 process_jobs()
185 with session_scope() as session:
186 issue = session.execute(select(CommunityIssue)).scalar_one()
187 assert issue.first_seen == first_seen
188 assert issue.last_seen > first_seen
189 assert issue.resolved is None
191 res = api.ListCommunityIssues(editor_pb2.ListCommunityIssuesReq())
192 [served] = res.open_issues
193 assert served.rule == "overlap"
194 assert served.priority == editor_pb2.COMMUNITY_ISSUE_PRIORITY_HIGH
195 assert served.community.community_id == neighbour
196 assert served.community.name == "Neighbour"
197 assert served.community.node_type == communities_pb2.NODE_TYPE_LOCALITY
198 assert served.other.community_id == world.city
199 assert served.other.slug == "city"
200 assert served.share.value == pytest.approx(0.67, abs=0.01)
201 assert json.loads(served.area_geojson)["type"] == "Polygon"
202 assert not served.HasField("resolved")
204 move_boundary(neighbour, box(2, 1, 2.5, 1.5))
205 api.RunCommunityChecks(empty_pb2.Empty())
206 process_jobs()
208 res = api.ListCommunityIssues(editor_pb2.ListCommunityIssuesReq())
209 assert list(res.open_issues) == []
210 assert list(res.resolved_issues) == []
211 assert res.last_run.open_issues == 0
213 res = api.ListCommunityIssues(
214 editor_pb2.ListCommunityIssuesReq(resolved_since=Timestamp_from_datetime(now() - timedelta(hours=1)))
215 )
216 assert [issue.community.community_id for issue in res.resolved_issues] == [neighbour]
217 assert res.resolved_issues[0].HasField("resolved")
219 res = api.ListCommunityIssues(editor_pb2.ListCommunityIssuesReq(resolved_since=Timestamp_from_datetime(now())))
220 assert list(res.resolved_issues) == []
222 with session_scope() as session:
223 assert session.execute(
224 select(CommunityCheckRun.open_issues).order_by(CommunityCheckRun.id)
225 ).scalars().all() == [
226 1,
227 1,
228 0,
229 ]
232def test_active_users_outside_localities(world: World):
233 generate_user(geom=create_coordinate(1.2, 1.2))
234 generate_user(geom=create_coordinate(5, 5))
235 inactive, _ = generate_user(geom=create_coordinate(5, 5))
236 banned, _ = generate_user(geom=create_coordinate(5, 5))
237 with session_scope() as session:
238 session.execute(update(User).where(User.id == inactive.id).values(last_active=now() - timedelta(days=100)))
239 session.execute(update(User).where(User.id == banned.id).values(banned_at=now()))
241 editor, editor_token = generate_user(is_editor=True, geom=create_coordinate(1.3, 1.3))
242 with real_editor_session(editor_token) as api:
243 api.RunCommunityChecks(empty_pb2.Empty())
244 process_jobs()
245 res = api.ListCommunityIssues(editor_pb2.ListCommunityIssuesReq())
247 assert res.last_run.active_users == 3
248 assert res.last_run.active_users_outside_localities == 1
251def test_normal_users_cannot_see_community_issues(db):
252 _, token = generate_user()
254 with real_editor_session(token) as api:
255 with expect_rpc_error(grpc.StatusCode.PERMISSION_DENIED, "Permission denied"):
256 api.ListCommunityIssues(editor_pb2.ListCommunityIssuesReq())
257 with expect_rpc_error(grpc.StatusCode.PERMISSION_DENIED, "Permission denied"):
258 api.RunCommunityChecks(empty_pb2.Empty())