Coverage for app/backend/src/tests/test_public.py: 100%
314 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-10 09:48 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-10 09:48 +0000
1import json
2from datetime import UTC, date, datetime, timedelta
3from math import sqrt
4from unittest.mock import patch
6import grpc
7import pytest
8from google.protobuf import empty_pb2
9from sqlalchemy import func, select, update
11from couchers.db import session_scope
12from couchers.jobs.enqueue import queue_job
13from couchers.jobs.handlers import update_randomized_locations
14from couchers.materialized_views import refresh_materialized_views_rapid
15from couchers.models import (
16 Invoice,
17 InvoiceType,
18 ModerationObjectType,
19 ModerationState,
20 ModerationVisibility,
21 ProfilePublicVisibility,
22 Reference,
23 ReferenceType,
24 User,
25)
26from couchers.proto import api_pb2, public_pb2
27from couchers.servicers.public import _get_donation_stats, _get_public_users, _get_signup_page_info, _get_volunteers
28from couchers.utils import now
29from tests.fixtures.db import generate_user, make_friends, make_volunteer
30from tests.fixtures.feature_flags import FeatureFlags
31from tests.fixtures.misc import process_jobs
32from tests.fixtures.sessions import public_session
33from tests.test_references import create_friend_reference, create_host_reference
36def test_GetPublicMapLayer(db):
37 user1, _ = generate_user()
38 user2, _ = generate_user(username="user2", public_visibility=ProfilePublicVisibility.nothing)
39 user3, _ = generate_user()
40 user4, _ = generate_user(username="user4", public_visibility=ProfilePublicVisibility.limited)
41 user5, _ = generate_user()
43 # these are hardcoded in test_fixtures
44 test_user_coordinates = [-73.9740, 40.7108]
46 with session_scope() as session:
47 queue_job(session, job=update_randomized_locations, payload=empty_pb2.Empty())
49 process_jobs()
51 with public_session() as public:
52 http_body = public.GetPublicUsers(empty_pb2.Empty())
53 assert http_body.content_type == "application/json"
54 data = json.loads(http_body.data)
55 # Sort to ensure a deterministic order
56 data["features"].sort(key=lambda f: f["geometry"]["coordinates"][0])
57 assert data == {
58 "type": "FeatureCollection",
59 "features": [
60 {
61 "type": "Feature",
62 "geometry": {"type": "Point", "coordinates": [-74.042643848, 40.706241098]},
63 "properties": {"username": None},
64 },
65 {
66 "type": "Feature",
67 "geometry": {"type": "Point", "coordinates": [-73.974, 40.7108]},
68 "properties": {"username": "user4"},
69 },
70 {
71 "type": "Feature",
72 "geometry": {"type": "Point", "coordinates": [-73.955417734, 40.691831306]},
73 "properties": {"username": None},
74 },
75 {
76 "type": "Feature",
77 "geometry": {"type": "Point", "coordinates": [-73.928380198, 40.729706144]},
78 "properties": {"username": None},
79 },
80 ],
81 }
83 for user in data["features"]:
84 coords = user["geometry"]["coordinates"]
85 if user["properties"]["username"]:
86 assert coords == test_user_coordinates
87 else:
88 xdiff = coords[0] - test_user_coordinates[0]
89 ydiff = coords[1] - test_user_coordinates[1]
90 dist = sqrt(xdiff**2 + ydiff**2)
91 assert dist > 0.02 and dist < 0.1
94def test_GetPublicMapLayer_excludes_shadowed(db):
95 """Test GetPublicUsers excludes shadowed users from the public map"""
97 _get_public_users.cache_clear()
99 generate_user(username="visible", public_visibility=ProfilePublicVisibility.limited)
100 shadowed_user, _ = generate_user(username="shadowed", public_visibility=ProfilePublicVisibility.limited)
102 with session_scope() as session:
103 session.execute(select(User).where(User.id == shadowed_user.id)).scalar_one().shadowed_at = now()
105 with public_session() as public:
106 data = json.loads(public.GetPublicUsers(empty_pb2.Empty()).data)
108 assert {feature["properties"]["username"] for feature in data["features"]} == {"visible"}
111def test_GetDonationStats_empty(db, feature_flags: FeatureFlags):
112 """Test GetDonationStats with no donations returns zero and goal"""
113 _get_donation_stats.cache_clear()
115 feature_flags.set("donation_goal_usd", 2500)
116 feature_flags.set("donation_offset_usd", 700)
117 with public_session() as public:
118 res = public.GetDonationStats(empty_pb2.Empty())
119 assert res.total_donated_ytd == 0
120 assert res.goal == 2500
123def test_GetDonationStats_with_donations(db, feature_flags: FeatureFlags):
124 """Test GetDonationStats sums on_platform donations correctly"""
125 _get_donation_stats.cache_clear()
126 user, _ = generate_user()
128 with session_scope() as session:
129 # Add some on_platform donations (should be counted)
130 session.add(
131 Invoice(
132 user_id=user.id,
133 amount=100,
134 stripe_payment_intent_id="pi_test_1",
135 stripe_receipt_url="https://example.com/receipt/1",
136 invoice_type=InvoiceType.on_platform,
137 )
138 )
139 session.add(
140 Invoice(
141 user_id=user.id,
142 amount=250,
143 stripe_payment_intent_id="pi_test_2",
144 stripe_receipt_url="https://example.com/receipt/2",
145 invoice_type=InvoiceType.on_platform,
146 )
147 )
148 session.add(
149 Invoice(
150 user_id=user.id,
151 amount=500,
152 stripe_payment_intent_id="pi_test_3",
153 stripe_receipt_url="https://example.com/receipt/3",
154 invoice_type=InvoiceType.on_platform,
155 )
156 )
158 feature_flags.set("donation_goal_usd", 5000)
159 feature_flags.set("donation_offset_usd", 0)
160 with public_session() as public:
161 res = public.GetDonationStats(empty_pb2.Empty())
162 assert res.total_donated_ytd == 850
163 assert res.goal == 5000
166def test_GetDonationStats_excludes_merch(db, feature_flags: FeatureFlags):
167 """Test GetDonationStats excludes external_shop (merch) invoices"""
168 _get_donation_stats.cache_clear()
169 user, _ = generate_user()
171 with session_scope() as session:
172 # Add on_platform donation (should be counted)
173 session.add(
174 Invoice(
175 user_id=user.id,
176 amount=200,
177 stripe_payment_intent_id="pi_test_donation",
178 stripe_receipt_url="https://example.com/receipt/donation",
179 invoice_type=InvoiceType.on_platform,
180 )
181 )
182 # Add external_shop/merch purchase (should NOT be counted)
183 session.add(
184 Invoice(
185 user_id=user.id,
186 amount=50,
187 stripe_payment_intent_id="pi_test_merch",
188 stripe_receipt_url="https://example.com/receipt/merch",
189 invoice_type=InvoiceType.external_shop,
190 )
191 )
193 feature_flags.set("donation_goal_usd", 5000)
194 feature_flags.set("donation_offset_usd", 0)
195 with public_session() as public:
196 res = public.GetDonationStats(empty_pb2.Empty())
197 # Should only count the on_platform donation, not the merch
198 assert res.total_donated_ytd == 200
199 assert res.goal == 5000
202def test_GetDonationStats_excludes_previous_years(db, feature_flags: FeatureFlags):
203 """Test GetDonationStats only counts current year donations"""
204 _get_donation_stats.cache_clear()
205 user, _ = generate_user()
207 with session_scope() as session:
208 # Add donation from this year (should be counted)
209 session.add(
210 Invoice(
211 user_id=user.id,
212 amount=300,
213 stripe_payment_intent_id="pi_test_this_year",
214 stripe_receipt_url="https://example.com/receipt/this_year",
215 invoice_type=InvoiceType.on_platform,
216 )
217 )
218 # Add donation from last year (should NOT be counted)
219 last_year = datetime(datetime.now(UTC).year - 1, 6, 15, tzinfo=UTC)
220 invoice = Invoice(
221 user_id=user.id,
222 amount=1000,
223 stripe_payment_intent_id="pi_test_last_year",
224 stripe_receipt_url="https://example.com/receipt/last_year",
225 invoice_type=InvoiceType.on_platform,
226 )
227 session.add(invoice)
228 session.flush()
229 # Manually set the created date to last year
230 invoice.created = last_year
232 feature_flags.set("donation_goal_usd", 5000)
233 feature_flags.set("donation_offset_usd", 0)
234 with public_session() as public:
235 res = public.GetDonationStats(empty_pb2.Empty())
236 # Should only count this year's donation
237 assert res.total_donated_ytd == 300
238 assert res.goal == 5000
241def test_GetDonationStats_uses_flags(db, feature_flags: FeatureFlags):
242 """Goal and offset come from the donation_goal_usd / donation_offset_usd flags when configured"""
243 _get_donation_stats.cache_clear()
244 user, _ = generate_user()
246 with session_scope() as session:
247 session.add(
248 Invoice(
249 user_id=user.id,
250 amount=1000,
251 stripe_payment_intent_id="pi_test_flag",
252 stripe_receipt_url="https://example.com/receipt/flag",
253 invoice_type=InvoiceType.on_platform,
254 )
255 )
257 feature_flags.set("donation_goal_usd", 12000)
258 feature_flags.set("donation_offset_usd", 300)
260 with public_session() as public:
261 res = public.GetDonationStats(empty_pb2.Empty())
262 assert res.goal == 12000
263 assert res.total_donated_ytd == 700 # 1000 donated minus the 300 offset
265 _get_donation_stats.cache_clear()
268def test_GetVolunteers_mixed_current_and_past(db):
269 """Test GetVolunteers with both current and past volunteers"""
271 _get_volunteers.cache_clear()
273 current1, _ = generate_user(username="current1")
274 current2, _ = generate_user(username="current2")
275 past1, _ = generate_user(username="past1")
276 past2, _ = generate_user(username="past2")
278 with session_scope() as session:
279 session.add(
280 make_volunteer(
281 user_id=current1.id,
282 role="Current Role 1",
283 started_volunteering=date(2023, 1, 1),
284 )
285 )
286 session.add(
287 make_volunteer(
288 user_id=current2.id,
289 role="Current Role 2",
290 started_volunteering=date(2024, 1, 1),
291 )
292 )
293 session.add(
294 make_volunteer(
295 user_id=past1.id,
296 role="Past Role 1",
297 started_volunteering=date(2020, 1, 1),
298 stopped_volunteering=date(2022, 6, 1),
299 )
300 )
301 session.add(
302 make_volunteer(
303 user_id=past2.id,
304 role="Past Role 2",
305 started_volunteering=date(2021, 1, 1),
306 stopped_volunteering=date(2023, 12, 31),
307 )
308 )
310 refresh_materialized_views_rapid(empty_pb2.Empty())
312 with public_session() as public:
313 res = public.GetVolunteers(empty_pb2.Empty())
314 assert len(res.current_volunteers) == 2
315 assert len(res.past_volunteers) == 2
317 # Past volunteers are sorted by stopped_volunteering descending
318 assert res.past_volunteers[0].username == "past2"
319 assert res.past_volunteers[1].username == "past1"
322def test_GetVolunteers_custom_sort_key(db):
323 """Test GetVolunteers respects custom sort_key"""
325 _get_volunteers.cache_clear()
327 user1, _ = generate_user(username="user1")
328 user2, _ = generate_user(username="user2")
329 user3, _ = generate_user(username="user3")
331 with session_scope() as session:
332 # user2 should be first (lowest sort_key)
333 session.add(
334 make_volunteer(
335 user_id=user2.id,
336 role="Role 2",
337 started_volunteering=date(2023, 3, 1),
338 sort_key=1.0,
339 )
340 )
341 # user3 should be second
342 session.add(
343 make_volunteer(
344 user_id=user3.id,
345 role="Role 3",
346 started_volunteering=date(2023, 1, 1),
347 sort_key=2.0,
348 )
349 )
350 # user1 should be last (no sort_key, falls back to started_volunteering)
351 session.add(
352 make_volunteer(
353 user_id=user1.id,
354 role="Role 1",
355 started_volunteering=date(2023, 2, 1),
356 )
357 )
359 refresh_materialized_views_rapid(empty_pb2.Empty())
361 with public_session() as public:
362 res = public.GetVolunteers(empty_pb2.Empty())
363 assert len(res.current_volunteers) == 3
364 assert res.current_volunteers[0].username == "user2"
365 assert res.current_volunteers[1].username == "user3"
366 assert res.current_volunteers[2].username == "user1"
369def test_GetVolunteers_excludes_hidden(db):
370 """Test GetVolunteers excludes volunteers with show_on_team_page=False"""
372 _get_volunteers.cache_clear()
374 user1, _ = generate_user(username="visible")
375 user2, _ = generate_user(username="hidden")
377 with session_scope() as session:
378 session.add(
379 make_volunteer(
380 user_id=user1.id,
381 role="Visible Role",
382 started_volunteering=date(2023, 1, 1),
383 )
384 )
385 session.add(
386 make_volunteer(
387 user_id=user2.id,
388 role="Hidden Role",
389 started_volunteering=date(2023, 1, 1),
390 show_on_team_page=False,
391 )
392 )
394 refresh_materialized_views_rapid(empty_pb2.Empty())
396 with public_session() as public:
397 res = public.GetVolunteers(empty_pb2.Empty())
398 assert len(res.current_volunteers) == 1
399 assert res.current_volunteers[0].username == "visible"
402def test_GetVolunteers_link_types(db):
403 """Test GetVolunteers handles different link types"""
405 _get_volunteers.cache_clear()
407 user_default, _ = generate_user(username="default_link")
408 user_custom, _ = generate_user(username="custom_link")
410 with session_scope() as session:
411 # Volunteer with default couchers link
412 session.add(
413 make_volunteer(
414 user_id=user_default.id,
415 role="Default Link",
416 started_volunteering=date(2023, 1, 1),
417 )
418 )
419 # Volunteer with custom link
420 session.add(
421 make_volunteer(
422 user_id=user_custom.id,
423 role="Custom Link",
424 started_volunteering=date(2023, 1, 1),
425 link_type="email",
426 link_text="contact@example.com",
427 link_url="mailto:contact@example.com",
428 )
429 )
431 refresh_materialized_views_rapid(empty_pb2.Empty())
433 with public_session() as public:
434 res = public.GetVolunteers(empty_pb2.Empty())
435 assert len(res.current_volunteers) == 2
437 # Check default link
438 default_vol = next(v for v in res.current_volunteers if v.username == "default_link")
439 assert default_vol.link_type == "couchers"
440 assert default_vol.link_text == "@default_link"
441 assert "default_link" in default_vol.link_url
443 # Check custom link
444 custom_vol = next(v for v in res.current_volunteers if v.username == "custom_link")
445 assert custom_vol.link_type == "email"
446 assert custom_vol.link_text == "contact@example.com"
447 assert custom_vol.link_url == "mailto:contact@example.com"
450def test_GetVolunteers_board_member_flag(db):
451 """Test GetVolunteers correctly identifies board members"""
453 _get_volunteers.cache_clear()
455 board_member, _ = generate_user(username="board_member")
456 regular_volunteer, _ = generate_user(username="regular")
458 with session_scope() as session:
459 session.add(
460 make_volunteer(
461 user_id=board_member.id,
462 role="Board Member Role",
463 started_volunteering=date(2023, 1, 1),
464 )
465 )
466 session.add(
467 make_volunteer(
468 user_id=regular_volunteer.id,
469 role="Regular Role",
470 started_volunteering=date(2023, 1, 1),
471 )
472 )
474 refresh_materialized_views_rapid(empty_pb2.Empty())
476 # Mock the static badge dict to include board_member
477 with patch("couchers.servicers.public.get_static_badge_dict", return_value={"board_member": [board_member.id]}):
478 with public_session() as public:
479 res = public.GetVolunteers(empty_pb2.Empty())
480 assert len(res.current_volunteers) == 2
482 board_vol = next(v for v in res.current_volunteers if v.username == "board_member")
483 assert board_vol.is_board_member is True
485 regular_vol = next(v for v in res.current_volunteers if v.username == "regular")
486 assert regular_vol.is_board_member is False
489def test_GetSignupPageInfo(db):
490 """Test GetSignupPageInfo returns a correct user count and last signup info"""
492 _get_signup_page_info.cache_clear()
494 user1, _ = generate_user(username="user1")
495 user2, _ = generate_user(username="user2")
496 user3, _ = generate_user(username="user3")
498 refresh_materialized_views_rapid(empty_pb2.Empty())
500 with public_session() as public:
501 res = public.GetSignupPageInfo(empty_pb2.Empty())
502 # user3 should be the last signup (highest id)
503 assert res.user_count >= 3
504 assert res.last_location # Should have some location
505 assert res.last_signup # Should have a timestamp
508def test_GetSignupPageInfo_excludes_invisible_users(db):
509 """Test GetSignupPageInfo excludes deleted/banned users from count"""
510 _get_signup_page_info.cache_clear()
512 visible_user, _ = generate_user(username="visible")
513 deleted_user, _ = generate_user(username="deleted", delete_user=True)
515 with public_session() as public:
516 res = public.GetSignupPageInfo(empty_pb2.Empty())
517 # Deleted user should not be counted or be the last signup
518 assert res.user_count >= 1
521def test_GetPublicUser_not_found(db):
522 """Test GetPublicUser returns NOT_FOUND for nonexistent user"""
523 with public_session() as public:
524 with pytest.raises(grpc.RpcError) as exc:
525 public.GetPublicUser(public_pb2.GetPublicUserReq(user="nonexistent_user"))
526 assert exc.value.code() == grpc.StatusCode.NOT_FOUND
529def test_GetPublicUser_invisible_user(db):
530 """Test GetPublicUser returns NOT_FOUND for deleted/banned user"""
531 deleted_user, _ = generate_user(username="deleted", delete_user=True)
533 with public_session() as public:
534 with pytest.raises(grpc.RpcError) as exc:
535 public.GetPublicUser(public_pb2.GetPublicUserReq(user="deleted"))
536 assert exc.value.code() == grpc.StatusCode.NOT_FOUND
539def test_GetPublicUser_shadowed_user(db):
540 """Test GetPublicUser returns NOT_FOUND for a shadowed user"""
541 shadowed_user, _ = generate_user(username="shadowed", public_visibility=ProfilePublicVisibility.full)
543 with session_scope() as session:
544 session.execute(select(User).where(User.id == shadowed_user.id)).scalar_one().shadowed_at = now()
546 with public_session() as public:
547 with pytest.raises(grpc.RpcError) as exc:
548 public.GetPublicUser(public_pb2.GetPublicUserReq(user="shadowed"))
549 assert exc.value.code() == grpc.StatusCode.NOT_FOUND
552def test_GetPublicUser_limited_visibility(db):
553 """Test GetPublicUser returns limited_user for user with limited visibility"""
555 user, _ = generate_user(
556 username="limited_user",
557 name="Limited User",
558 public_visibility=ProfilePublicVisibility.limited,
559 )
561 # Add a reference to test reference counting
562 referrer, _ = generate_user(username="referrer")
563 with session_scope() as session:
564 moderation_state = ModerationState(
565 object_type=ModerationObjectType.reference,
566 object_id=0,
567 visibility=ModerationVisibility.visible,
568 )
569 session.add(moderation_state)
570 session.flush()
571 reference = Reference(
572 from_user_id=referrer.id,
573 to_user_id=user.id,
574 reference_type=ReferenceType.friend,
575 text="Great host!",
576 rating=0.8,
577 was_appropriate=True,
578 moderation_state_id=moderation_state.id,
579 )
580 session.add(reference)
581 session.flush()
582 moderation_state.object_id = reference.id
584 with public_session() as public:
585 res = public.GetPublicUser(public_pb2.GetPublicUserReq(user="limited_user"))
586 assert res.HasField("limited_user")
587 assert res.limited_user.username == "limited_user"
588 assert res.limited_user.name == "Limited User"
589 assert res.limited_user.city == "Testing city"
590 assert res.limited_user.hometown == "Test hometown"
591 assert res.limited_user.num_references == 1
592 assert res.limited_user.hosting_status == api_pb2.HOSTING_STATUS_CANT_HOST
593 assert len(res.limited_user.badges) == 0
596def test_GetPublicUser_most_visibility(db):
597 """Test GetPublicUser returns most_user for user with most visibility"""
598 user, _ = generate_user(
599 username="most_user",
600 name="Most User",
601 public_visibility=ProfilePublicVisibility.most,
602 )
604 with public_session() as public:
605 res = public.GetPublicUser(public_pb2.GetPublicUserReq(user="most_user"))
606 assert res.HasField("most_user")
607 assert res.most_user.username == "most_user"
608 assert res.most_user.name == "Most User"
609 assert res.most_user.city == "Testing city"
610 assert res.most_user.hosting_status == api_pb2.HOSTING_STATUS_CANT_HOST
613def test_GetPublicUser_full_visibility(db):
614 """Test GetPublicUser returns full_user for user with full visibility"""
615 _get_public_users.cache_clear()
617 user, _ = generate_user(
618 username="full_user",
619 name="Full User",
620 public_visibility=ProfilePublicVisibility.full,
621 )
623 with public_session() as public:
624 res = public.GetPublicUser(public_pb2.GetPublicUserReq(user="full_user"))
625 assert res.HasField("full_user")
626 assert res.full_user.username == "full_user"
627 assert res.full_user.name == "Full User"
628 assert res.full_user.city == "Testing city"
629 # Full user should have all the fields from the complete user profile
630 assert res.full_user.hosting_status == api_pb2.HOSTING_STATUS_CANT_HOST
633def test_GetPublicUser_num_references_visibility_rules(db):
634 """The public reference count follows the same visibility rules as the reference list"""
635 user, _ = generate_user(public_visibility=ProfilePublicVisibility.limited)
636 friend_referrer, _ = generate_user()
637 recent_host, _ = generate_user()
638 deleted_referrer1, _ = generate_user()
639 deleted_referrer2, _ = generate_user()
640 shadowed_referrer, _ = generate_user()
642 with session_scope() as session:
643 # counted: a normal friend reference
644 create_friend_reference(session, friend_referrer.id, user.id, timedelta(days=15))
645 # not counted: a recent stay where the reciprocal reference hasn't been written yet
646 create_host_reference(session, recent_host.id, user.id, timedelta(days=3), surfing=False)
647 # counted: references from deleted users remain visible (two of them, so that miscounting
648 # deleted authors can't coincidentally cancel out against the hidden recent stay above)
649 create_friend_reference(session, deleted_referrer1.id, user.id, timedelta(days=16))
650 create_host_reference(session, deleted_referrer2.id, user.id, timedelta(days=30), surfing=False)
651 # not counted: references from shadowed users are hidden from others
652 create_friend_reference(session, shadowed_referrer.id, user.id, timedelta(days=17))
653 for deleted in (deleted_referrer1, deleted_referrer2):
654 session.execute(update(User).where(User.username == deleted.username).values(deleted_at=func.now()))
655 session.execute(update(User).where(User.username == shadowed_referrer.username).values(shadowed_at=func.now()))
657 with public_session() as public:
658 res = public.GetPublicUser(public_pb2.GetPublicUserReq(user=user.username))
659 assert res.limited_user.num_references == 3
662def test_GetPublicUser_full_visibility_uses_callers_context(db):
663 """A logged-in caller sees the profile as it looks to them, not the anonymous view"""
664 user, _ = generate_user(public_visibility=ProfilePublicVisibility.full)
665 viewer, viewer_token = generate_user()
666 make_friends(user, viewer)
668 with public_session() as public:
669 res = public.GetPublicUser(public_pb2.GetPublicUserReq(user=user.username))
670 assert res.full_user.friends == api_pb2.User.FriendshipStatus.NA
672 with public_session(viewer_token) as public:
673 res = public.GetPublicUser(public_pb2.GetPublicUserReq(user=user.username))
674 assert res.full_user.friends == api_pb2.User.FriendshipStatus.FRIENDS
677def test_GetPublicUser_num_references_uses_callers_context(db):
678 """A shadowed author still sees their own reference counted, so the shadow ban isn't leaked"""
679 user, _ = generate_user(public_visibility=ProfilePublicVisibility.limited)
680 shadowed_referrer, shadowed_token = generate_user()
682 with session_scope() as session:
683 create_friend_reference(session, shadowed_referrer.id, user.id, timedelta(days=15))
684 session.execute(update(User).where(User.username == shadowed_referrer.username).values(shadowed_at=func.now()))
686 with public_session() as public:
687 res = public.GetPublicUser(public_pb2.GetPublicUserReq(user=user.username))
688 assert res.limited_user.num_references == 0
690 with public_session(shadowed_token) as public:
691 res = public.GetPublicUser(public_pb2.GetPublicUserReq(user=user.username))
692 assert res.limited_user.num_references == 1