Coverage for app/backend/src/tests/test_search.py: 100%

485 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-10 09:48 +0000

1from datetime import date, timedelta 

2 

3import grpc 

4import pytest 

5from google.protobuf import empty_pb2, wrappers_pb2 

6from psycopg.types.range import TimestamptzRange 

7from sqlalchemy import select, update 

8 

9from couchers.db import session_scope 

10from couchers.materialized_views import refresh_materialized_views, refresh_materialized_views_rapid 

11from couchers.models import ( 

12 EventOccurrence, 

13 HostingStatus, 

14 LanguageAbility, 

15 LanguageFluency, 

16 MeetupStatus, 

17 PassportSex, 

18 StrongVerificationAttempt, 

19 StrongVerificationAttemptStatus, 

20 User, 

21 UserRankingOffset, 

22) 

23from couchers.proto import api_pb2, communities_pb2, events_pb2, search_pb2 

24from couchers.servicers.search import USER_SEARCH_NOISE_PERIOD_DAYS 

25from couchers.utils import Timestamp_from_datetime, create_coordinate, now, today 

26from tests.fixtures.api import events as events_api 

27from tests.fixtures.db import generate_user 

28from tests.fixtures.feature_flags import Flags 

29from tests.fixtures.misc import Moderator 

30from tests.fixtures.sessions import communities_session, search_session 

31from tests.test_communities import create_community, testing_communities # noqa 

32from tests.test_references import create_friend_reference 

33from tests.utils import local_date_time 

34 

35 

36class TestSearchInCommunities: 

37 """The tests that search the whole community tree, grouped so they share one copy of it.""" 

38 

39 @staticmethod 

40 def test_Search(testing_communities): 

41 user, token = generate_user() 

42 with search_session(token) as api: 

43 res = api.Search( 

44 search_pb2.SearchReq( 

45 query="Country 1, Region 1", 

46 include_users=True, 

47 include_communities=True, 

48 include_groups=True, 

49 include_places=True, 

50 include_guides=True, 

51 ) 

52 ) 

53 res = api.Search( 

54 search_pb2.SearchReq( 

55 query="Country 1, Region 1, Attraction", 

56 title_only=True, 

57 include_users=True, 

58 include_communities=True, 

59 include_groups=True, 

60 include_places=True, 

61 include_guides=True, 

62 ) 

63 ) 

64 

65 @staticmethod 

66 def test_UserSearch(testing_communities): 

67 """Test that UserSearch returns all users if no filter is set.""" 

68 user, token = generate_user() 

69 

70 refresh_materialized_views_rapid(empty_pb2.Empty()) 

71 refresh_materialized_views(empty_pb2.Empty()) 

72 

73 with search_session(token) as api: 

74 res = api.UserSearchV2(search_pb2.UserSearchReq()) 

75 assert len(res.results) > 0 

76 assert res.total_items == len(res.results) 

77 

78 @staticmethod 

79 def test_EventSearch_no_filters(testing_communities): 

80 """Test that EventSearch returns all events if no filter is set.""" 

81 user, token = generate_user() 

82 with search_session(token) as api: 

83 res = api.EventSearch(search_pb2.EventSearchReq()) 

84 assert len(res.events) > 0 

85 

86 

87def test_regression_search_in_area(db): 

88 """ 

89 Makes sure search_in_area works. 

90 

91 At the equator/prime meridian intersection (0,0), one degree is roughly 111 km. 

92 """ 

93 

94 # outside 

95 user1, token1 = generate_user(geom=create_coordinate(1, 0), geom_radius=100) 

96 # outside 

97 user2, token2 = generate_user(geom=create_coordinate(0, 1), geom_radius=100) 

98 # inside 

99 user3, token3 = generate_user(geom=create_coordinate(0.1, 0), geom_radius=100) 

100 # inside 

101 user4, token4 = generate_user(geom=create_coordinate(0, 0.1), geom_radius=100) 

102 # outside 

103 user5, token5 = generate_user(geom=create_coordinate(10, 10), geom_radius=100) 

104 

105 refresh_materialized_views_rapid(empty_pb2.Empty()) 

106 refresh_materialized_views(empty_pb2.Empty()) 

107 

108 with search_session(token5) as api: 

109 res = api.UserSearchV2( 

110 search_pb2.UserSearchReq( 

111 search_in_area=search_pb2.Area( 

112 lat=0, 

113 lng=0, 

114 radius=100000, 

115 ) 

116 ) 

117 ) 

118 assert [result.user_id for result in res.results] == [user3.id, user4.id] 

119 

120 

121def test_user_search_in_rectangle(db): 

122 """ 

123 Makes sure search_in_rectangle works as expected. 

124 """ 

125 

126 # outside 

127 user1, token1 = generate_user(geom=create_coordinate(-1, 0), geom_radius=100) 

128 # outside 

129 user2, token2 = generate_user(geom=create_coordinate(0, -1), geom_radius=100) 

130 # inside 

131 user3, token3 = generate_user(geom=create_coordinate(0.1, 0.1), geom_radius=100) 

132 # inside 

133 user4, token4 = generate_user(geom=create_coordinate(1.2, 0.1), geom_radius=100) 

134 # outside (not fully inside) 

135 user5, token5 = generate_user(geom=create_coordinate(0, 0), geom_radius=100) 

136 # outside 

137 user6, token6 = generate_user(geom=create_coordinate(0.1, 1.2), geom_radius=100) 

138 # outside 

139 user7, token7 = generate_user(geom=create_coordinate(10, 10), geom_radius=100) 

140 

141 refresh_materialized_views_rapid(empty_pb2.Empty()) 

142 refresh_materialized_views(empty_pb2.Empty()) 

143 

144 with search_session(token5) as api: 

145 res = api.UserSearchV2( 

146 search_pb2.UserSearchReq( 

147 search_in_rectangle=search_pb2.RectArea( 

148 lat_min=0, 

149 lat_max=2, 

150 lng_min=0, 

151 lng_max=1, 

152 ) 

153 ) 

154 ) 

155 assert [result.user_id for result in res.results] == [user3.id, user4.id] 

156 

157 

158def test_user_filter_complete_profile(db): 

159 """ 

160 Make sure the completed profile flag returns only completed user profile 

161 """ 

162 user_complete_profile, token6 = generate_user(complete_profile=True) 

163 

164 user_incomplete_profile, token7 = generate_user(complete_profile=False) 

165 

166 refresh_materialized_views_rapid(empty_pb2.Empty()) 

167 refresh_materialized_views(empty_pb2.Empty()) 

168 

169 with search_session(token7) as api: 

170 res = api.UserSearchV2(search_pb2.UserSearchReq(profile_completed=wrappers_pb2.BoolValue(value=False))) 

171 assert user_incomplete_profile.id in [result.user_id for result in res.results] 

172 

173 with search_session(token6) as api: 

174 res = api.UserSearchV2(search_pb2.UserSearchReq(profile_completed=wrappers_pb2.BoolValue(value=True))) 

175 assert [result.user_id for result in res.results] == [user_complete_profile.id] 

176 

177 

178def test_user_filter_meetup_status(db): 

179 """ 

180 Make sure the completed profile flag returns only completed user profile 

181 """ 

182 user_wants_to_meetup, token8 = generate_user(meetup_status=MeetupStatus.wants_to_meetup) 

183 

184 user_does_not_want_to_meet, token9 = generate_user(meetup_status=MeetupStatus.does_not_want_to_meetup) 

185 

186 refresh_materialized_views_rapid(empty_pb2.Empty()) 

187 refresh_materialized_views(empty_pb2.Empty()) 

188 

189 with search_session(token8) as api: 

190 res = api.UserSearchV2(search_pb2.UserSearchReq(meetup_status_filter=[api_pb2.MEETUP_STATUS_WANTS_TO_MEETUP])) 

191 assert user_wants_to_meetup.id in [result.user_id for result in res.results] 

192 

193 with search_session(token9) as api: 

194 res = api.UserSearchV2( 

195 search_pb2.UserSearchReq(meetup_status_filter=[api_pb2.MEETUP_STATUS_DOES_NOT_WANT_TO_MEETUP]) 

196 ) 

197 assert [result.user_id for result in res.results] == [user_does_not_want_to_meet.id] 

198 

199 

200def test_user_filter_language(db): 

201 """ 

202 Test filtering users by language ability. 

203 """ 

204 user_with_german_beginner, token11 = generate_user(hosting_status=HostingStatus.can_host) 

205 user_with_japanese_conversational, token12 = generate_user(hosting_status=HostingStatus.can_host) 

206 user_with_german_fluent, token13 = generate_user(hosting_status=HostingStatus.can_host) 

207 

208 with session_scope() as session: 

209 session.add( 

210 LanguageAbility( 

211 user_id=user_with_german_beginner.id, language_code="deu", fluency=LanguageFluency.beginner 

212 ), 

213 ) 

214 session.add( 

215 LanguageAbility( 

216 user_id=user_with_japanese_conversational.id, 

217 language_code="jpn", 

218 fluency=LanguageFluency.fluent, 

219 ) 

220 ) 

221 session.add( 

222 LanguageAbility(user_id=user_with_german_fluent.id, language_code="deu", fluency=LanguageFluency.fluent) 

223 ) 

224 

225 refresh_materialized_views_rapid(empty_pb2.Empty()) 

226 refresh_materialized_views(empty_pb2.Empty()) 

227 

228 with search_session(token11) as api: 

229 res = api.UserSearchV2( 

230 search_pb2.UserSearchReq( 

231 language_ability_filter=[ 

232 api_pb2.LanguageAbility( 

233 code="deu", 

234 fluency=api_pb2.LanguageAbility.Fluency.FLUENCY_FLUENT, 

235 ) 

236 ] 

237 ) 

238 ) 

239 assert [result.user_id for result in res.results] == [user_with_german_fluent.id] 

240 

241 res = api.UserSearchV2( 

242 search_pb2.UserSearchReq( 

243 language_ability_filter=[ 

244 api_pb2.LanguageAbility( 

245 code="jpn", 

246 fluency=api_pb2.LanguageAbility.Fluency.FLUENCY_CONVERSATIONAL, 

247 ) 

248 ] 

249 ) 

250 ) 

251 assert [result.user_id for result in res.results] == [user_with_japanese_conversational.id] 

252 

253 

254def test_user_filter_strong_verification(db): 

255 user1, token1 = generate_user() 

256 user2, _ = generate_user(strong_verification=True) 

257 user3, _ = generate_user() 

258 user4, _ = generate_user(strong_verification=True) 

259 user5, _ = generate_user(strong_verification=True) 

260 

261 refresh_materialized_views_rapid(empty_pb2.Empty()) 

262 refresh_materialized_views(empty_pb2.Empty()) 

263 

264 with search_session(token1) as api: 

265 res = api.UserSearchV2(search_pb2.UserSearchReq(only_with_strong_verification=False)) 

266 assert [result.user_id for result in res.results] == [user1.id, user2.id, user3.id, user4.id, user5.id] 

267 

268 res = api.UserSearchV2(search_pb2.UserSearchReq(only_with_strong_verification=True)) 

269 assert [result.user_id for result in res.results] == [user2.id, user4.id, user5.id] 

270 

271 

272def test_user_search_no_duplicates_from_multiple_matching_rows(db): 

273 """ 

274 A user matching several requested languages, or with several valid strong verifications, is returned once. 

275 """ 

276 languages = [("deu", LanguageFluency.fluent), ("jpn", LanguageFluency.fluent)] 

277 user1, token1 = generate_user() 

278 user2, _ = generate_user(strong_verification=True, language_abilities=languages) 

279 user3, _ = generate_user(strong_verification=True, language_abilities=languages) 

280 

281 with session_scope() as session: 

282 session.add( 

283 StrongVerificationAttempt( 

284 verification_attempt_token=f"second_verification_attempt_token_{user2.id}", 

285 user_id=user2.id, 

286 status=StrongVerificationAttemptStatus.succeeded, 

287 has_full_data=True, 

288 passport_encrypted_data=b"not real", 

289 passport_date_of_birth=user2.birthdate, 

290 passport_sex=PassportSex.unspecified, 

291 has_minimal_data=True, 

292 passport_expiry_date=date.today() + timedelta(days=20), 

293 passport_nationality="UTO", 

294 passport_last_three_document_chars="xyz", 

295 iris_token=f"second_iris_token_{user2.id}", 

296 iris_session_id=1000 + user2.id, 

297 ) 

298 ) 

299 

300 refresh_materialized_views_rapid(empty_pb2.Empty()) 

301 refresh_materialized_views(empty_pb2.Empty()) 

302 

303 language_filter = [ 

304 api_pb2.LanguageAbility(code="deu", fluency=api_pb2.LanguageAbility.Fluency.FLUENCY_CONVERSATIONAL), 

305 api_pb2.LanguageAbility(code="jpn", fluency=api_pb2.LanguageAbility.Fluency.FLUENCY_CONVERSATIONAL), 

306 ] 

307 with search_session(token1) as api: 

308 for req in [ 

309 search_pb2.UserSearchReq(language_ability_filter=language_filter), 

310 search_pb2.UserSearchReq(only_with_strong_verification=True), 

311 ]: 

312 res = api.UserSearchV2(req) 

313 assert sorted(result.user_id for result in res.results) == [user2.id, user3.id] 

314 assert res.total_items == 2 

315 

316 

317def test_regression_search_only_with_references(db): 

318 user1, token1 = generate_user() 

319 user2, _ = generate_user() 

320 user3, _ = generate_user() 

321 user4, _ = generate_user(delete_user=True) 

322 

323 refresh_materialized_views_rapid(empty_pb2.Empty()) 

324 refresh_materialized_views(empty_pb2.Empty()) 

325 

326 with session_scope() as session: 

327 # user 2 has references 

328 create_friend_reference(session, user1.id, user2.id, timedelta(days=1)) 

329 create_friend_reference(session, user3.id, user2.id, timedelta(days=1)) 

330 create_friend_reference(session, user4.id, user2.id, timedelta(days=1)) 

331 

332 # user 3 only has reference from a deleted user 

333 create_friend_reference(session, user4.id, user3.id, timedelta(days=1)) 

334 

335 with search_session(token1) as api: 

336 res = api.UserSearchV2(search_pb2.UserSearchReq(only_with_references=False)) 

337 assert [result.user_id for result in res.results] == [user1.id, user2.id, user3.id] 

338 

339 res = api.UserSearchV2(search_pb2.UserSearchReq(only_with_references=True)) 

340 assert [result.user_id for result in res.results] == [user2.id] 

341 

342 

343def test_user_search_exactly_user_ids(db): 

344 """ 

345 Test that UserSearch with exactly_user_ids returns only those users and ignores other filters. 

346 """ 

347 # Create users with different properties 

348 user1, token1 = generate_user() 

349 user2, _ = generate_user(strong_verification=True) 

350 user3, _ = generate_user(complete_profile=True) 

351 user4, _ = generate_user(meetup_status=MeetupStatus.wants_to_meetup) 

352 user5, _ = generate_user(delete_user=True) # Deleted user 

353 

354 refresh_materialized_views_rapid(empty_pb2.Empty()) 

355 refresh_materialized_views(empty_pb2.Empty()) 

356 

357 with search_session(token1) as api: 

358 # Test that exactly_user_ids returns only the specified users 

359 res = api.UserSearchV2(search_pb2.UserSearchReq(exactly_user_ids=[user2.id, user3.id, user4.id])) 

360 assert sorted([result.user_id for result in res.results]) == sorted([user2.id, user3.id, user4.id]) 

361 

362 # Test that exactly_user_ids ignores other filters 

363 res = api.UserSearchV2( 

364 search_pb2.UserSearchReq( 

365 exactly_user_ids=[user2.id, user3.id, user4.id], 

366 only_with_strong_verification=True, # This would normally filter out user3 and user4 

367 ) 

368 ) 

369 assert sorted([result.user_id for result in res.results]) == sorted([user2.id, user3.id, user4.id]) 

370 

371 # Test with non-existent user IDs (should be ignored) 

372 res = api.UserSearchV2(search_pb2.UserSearchReq(exactly_user_ids=[user1.id, 99999])) 

373 assert [result.user_id for result in res.results] == [user1.id] 

374 

375 # Test with deleted user ID (should be ignored due to visibility filter) 

376 res = api.UserSearchV2(search_pb2.UserSearchReq(exactly_user_ids=[user1.id, user5.id])) 

377 assert [result.user_id for result in res.results] == [user1.id] 

378 

379 

380def test_user_search_pagination_with_tied_scores(db, flags: Flags): 

381 """ 

382 Paging through tied recommendation scores, including a tie block larger than the page size, returns every user 

383 exactly once in a stable order. 

384 """ 

385 flags.set_float("user_search_noise_scale", 0.0) 

386 users = [generate_user()[0] for _ in range(7)] 

387 token = generate_user()[1] 

388 scores = [10.0, 5.0, 5.0, 5.0, 5.0, 5.0, -1.0] 

389 

390 with session_scope() as session: 

391 for user, score in zip(users, scores): 

392 session.execute(update(User).where(User.id == user.id).values(recommendation_score=score)) 

393 session.execute(update(User).where(User.id.not_in([u.id for u in users])).values(recommendation_score=0.0)) 

394 

395 refresh_materialized_views_rapid(empty_pb2.Empty()) 

396 refresh_materialized_views(empty_pb2.Empty()) 

397 

398 with session_scope() as session: 

399 expected = list( 

400 session.execute(select(User.id).order_by(User.recommendation_score.desc(), User.id.desc())).scalars() 

401 ) 

402 

403 with search_session(token) as api: 

404 seen = [] 

405 page_token = "" 

406 while True: 

407 res = api.UserSearchV2(search_pb2.UserSearchReq(page_size=2, page_token=page_token)) 

408 seen += [result.user_id for result in res.results] 

409 assert len(seen) <= len(expected) 

410 page_token = res.next_page_token 

411 if not page_token: 

412 break 

413 

414 assert seen == expected 

415 

416 

417def _user_search_order(token: str, page_size: int = 100) -> list[int]: 

418 order: list[int] = [] 

419 page_token = "" 

420 with search_session(token) as api: 

421 while True: 

422 res = api.UserSearchV2(search_pb2.UserSearchReq(page_size=page_size, page_token=page_token)) 

423 order += [result.user_id for result in res.results] 

424 page_token = res.next_page_token 

425 if not page_token: 

426 return order 

427 

428 

429def test_user_search_noise_is_per_viewer_and_stable_within_period(db, frozen_timewarp): 

430 viewer1, token1 = generate_user() 

431 _, token2 = generate_user() 

432 candidate_ids = {generate_user()[0].id for _ in range(20)} 

433 

434 with session_scope() as session: 

435 session.execute(update(User).values(recommendation_score=0)) 

436 

437 refresh_materialized_views_rapid(empty_pb2.Empty()) 

438 

439 order1 = _user_search_order(token1) 

440 assert candidate_ids <= set(order1) 

441 assert _user_search_order(token1) == order1 

442 assert _user_search_order(token2) != order1 

443 

444 # step a day at a time, which also keeps the short-lived session alive, until this viewer's period rolls over 

445 days_left = USER_SEARCH_NOISE_PERIOD_DAYS - (today().toordinal() + viewer1.id) % USER_SEARCH_NOISE_PERIOD_DAYS 

446 for _ in range(days_left - 1): 

447 frozen_timewarp.advance(timedelta(days=1)) 

448 assert _user_search_order(token1) == order1 

449 frozen_timewarp.advance(timedelta(days=1)) 

450 assert _user_search_order(token1) != order1 

451 

452 

453def test_user_search_pagination_with_noise(db): 

454 _, token = generate_user() 

455 for _ in range(10): 

456 generate_user() 

457 

458 with session_scope() as session: 

459 session.execute(update(User).values(recommendation_score=0)) 

460 

461 refresh_materialized_views_rapid(empty_pb2.Empty()) 

462 

463 full_order = _user_search_order(token) 

464 assert len(full_order) == 11 

465 assert _user_search_order(token, page_size=3) == full_order 

466 

467 

468def test_user_search_noise_scale_flag(db, flags: Flags): 

469 _, token = generate_user() 

470 user_ids = [generate_user()[0].id for _ in range(10)] 

471 

472 with session_scope() as session: 

473 session.execute(update(User).values(recommendation_score=-User.id)) 

474 

475 refresh_materialized_views_rapid(empty_pb2.Empty()) 

476 

477 def order() -> list[int]: 

478 return [user_id for user_id in _user_search_order(token) if user_id in user_ids] 

479 

480 assert sorted(order()) == user_ids 

481 assert order() != user_ids 

482 

483 flags.set_float("user_search_noise_scale", 0.0) 

484 assert order() == user_ids 

485 

486 

487def test_user_search_ranking_offsets_variant(db, flags: Flags): 

488 flags.set_float("user_search_noise_scale", 0.0) 

489 _, token = generate_user() 

490 user_ids = [generate_user()[0].id for _ in range(5)] 

491 

492 with session_scope() as session: 

493 session.execute(update(User).values(recommendation_score=-User.id)) 

494 # in variant "a", offsets reverse the order; variant "b" bumps only the last user to the top 

495 for i, user_id in enumerate(user_ids): 

496 session.add(UserRankingOffset(variant="a", user_id=user_id, offset=2.0 * i)) 

497 session.add(UserRankingOffset(variant="b", user_id=user_ids[-1], offset=100.0)) 

498 

499 refresh_materialized_views_rapid(empty_pb2.Empty()) 

500 

501 def order() -> list[int]: 

502 return [user_id for user_id in _user_search_order(token, page_size=2) if user_id in user_ids] 

503 

504 assert order() == user_ids 

505 

506 flags.set_string("search_ranking_offsets_variant", "a") 

507 assert order() == user_ids[::-1] 

508 

509 flags.set_string("search_ranking_offsets_variant", "b") 

510 assert order() == user_ids[-1:] + user_ids[:-1] 

511 

512 flags.set_string("search_ranking_offsets_variant", "nonexistent") 

513 assert order() == user_ids 

514 

515 

516@pytest.fixture 

517def sample_community(db) -> int: 

518 """Create large community spanning from (-50, 0) to (50, 2) as events can only be created within communities.""" 

519 user, _ = generate_user() 

520 with session_scope() as session: 

521 return create_community(session, -50, 50, "Community", [user], [], None).id 

522 

523 

524def test_event_search_by_query(sample_community): 

525 """Test that EventSearch finds events by title (and content if query_title_only=False).""" 

526 user, token = generate_user() 

527 

528 event1 = events_api.create_event(token=token, title="Lorem Ipsum") 

529 event2 = events_api.create_event(token=token, content="Lorem Ipsum") 

530 events_api.create_event(token=token) 

531 

532 with search_session(token) as api: 

533 res = api.EventSearch(search_pb2.EventSearchReq(query=wrappers_pb2.StringValue(value="Ipsum"))) 

534 assert len(res.events) == 2 

535 assert {result.event_id for result in res.events} == {event1.event_id, event2.event_id} 

536 

537 res = api.EventSearch( 

538 search_pb2.EventSearchReq(query=wrappers_pb2.StringValue(value="Ipsum"), query_title_only=True) 

539 ) 

540 assert len(res.events) == 1 

541 assert res.events[0].event_id == event1.event_id 

542 

543 

544def test_event_search_by_time(sample_community): 

545 """Test that EventSearch filters with the given time range.""" 

546 user, token = generate_user() 

547 

548 event1 = events_api.create_event( 

549 token=token, 

550 start_date_time=local_date_time(now() + timedelta(hours=1)), 

551 end_date_time=local_date_time(now() + timedelta(hours=2)), 

552 ) 

553 event2 = events_api.create_event( 

554 token=token, 

555 start_date_time=local_date_time(now() + timedelta(hours=4)), 

556 end_date_time=local_date_time(now() + timedelta(hours=5)), 

557 ) 

558 event3 = events_api.create_event( 

559 token=token, 

560 start_date_time=local_date_time(now() + timedelta(hours=7)), 

561 end_date_time=local_date_time(now() + timedelta(hours=8)), 

562 ) 

563 

564 with search_session(token) as api: 

565 res = api.EventSearch(search_pb2.EventSearchReq(before=Timestamp_from_datetime(now() + timedelta(hours=6)))) 

566 assert len(res.events) == 2 

567 assert {result.event_id for result in res.events} == {event1.event_id, event2.event_id} 

568 

569 res = api.EventSearch(search_pb2.EventSearchReq(after=Timestamp_from_datetime(now() + timedelta(hours=3)))) 

570 assert len(res.events) == 2 

571 assert {result.event_id for result in res.events} == {event2.event_id, event3.event_id} 

572 

573 res = api.EventSearch( 

574 search_pb2.EventSearchReq( 

575 before=Timestamp_from_datetime(now() + timedelta(hours=6)), 

576 after=Timestamp_from_datetime(now() + timedelta(hours=3)), 

577 ) 

578 ) 

579 assert len(res.events) == 1 

580 assert res.events[0].event_id == event2.event_id 

581 

582 

583def test_event_search_by_circle(sample_community): 

584 """Test that EventSearch only returns events within the given circle.""" 

585 user, token = generate_user() 

586 

587 inside_pts = [(0.1, 0.01), (0.01, 0.1)] 

588 for i, (lat, lng) in enumerate(inside_pts): 

589 events_api.create_event( 

590 token=token, 

591 title=f"Inside area {i}", 

592 location=events_pb2.EventLocation(lat=lat, lng=lng, address=f"Inside area {i}"), 

593 ) 

594 

595 outside_pts = [(1, 0.1), (0.1, 1), (10, 1)] 

596 for i, (lat, lng) in enumerate(outside_pts): 

597 events_api.create_event( 

598 token=token, 

599 title=f"Outside area {i}", 

600 location=events_pb2.EventLocation(lat=lat, lng=lng, address=f"Outside area {i}"), 

601 ) 

602 

603 with search_session(token) as api: 

604 res = api.EventSearch(search_pb2.EventSearchReq(search_in_area=search_pb2.Area(lat=0, lng=0, radius=100000))) 

605 assert len(res.events) == len(inside_pts) 

606 assert all(event.title.startswith("Inside area") for event in res.events) 

607 

608 

609def test_event_search_by_rectangle(sample_community): 

610 """Test that EventSearch only returns events within the given rectangular area.""" 

611 user, token = generate_user() 

612 

613 inside_pts = [(0.1, 0.2), (1.2, 0.2)] 

614 for i, (lat, lng) in enumerate(inside_pts): 

615 events_api.create_event( 

616 token=token, 

617 title=f"Inside area {i}", 

618 location=events_pb2.EventLocation(lat=lat, lng=lng, address=f"Inside area {i}"), 

619 ) 

620 

621 outside_pts = [(-1, 0.1), (0.1, 0.01), (-0.01, 0.01), (0.1, 1.2), (10, 1)] 

622 for i, (lat, lng) in enumerate(outside_pts): 

623 events_api.create_event( 

624 token=token, 

625 title=f"Outside area {i}", 

626 location=events_pb2.EventLocation(lat=lat, lng=lng, address=f"Outside area {i}"), 

627 ) 

628 

629 with search_session(token) as api: 

630 res = api.EventSearch( 

631 search_pb2.EventSearchReq( 

632 search_in_rectangle=search_pb2.RectArea(lat_min=0, lat_max=2, lng_min=0.1, lng_max=1) 

633 ) 

634 ) 

635 assert len(res.events) == len(inside_pts) 

636 assert all(event.title.startswith("Inside area") for event in res.events) 

637 

638 

639def test_event_search_pagination(sample_community): 

640 """Test that EventSearch paginates correctly. 

641 

642 Check that 

643 - <page_size> events are returned, if available 

644 - sort order is applied (default: past=False) 

645 - the next page token continues where the previous page left off 

646 """ 

647 user, token = generate_user() 

648 

649 anchor_time = now().replace(second=0, microsecond=0) # Events are created at minute granularity 

650 for i in range(5): 

651 events_api.create_event( 

652 token=token, 

653 title=f"Event {i + 1}", 

654 start_date_time=local_date_time(anchor_time + timedelta(hours=i + 1)), 

655 end_date_time=local_date_time(anchor_time + timedelta(hours=i + 1, minutes=30)), 

656 ) 

657 

658 with search_session(token) as api: 

659 res = api.EventSearch(search_pb2.EventSearchReq(past=False, page_size=4)) 

660 assert len(res.events) == 4 

661 assert [event.title for event in res.events] == ["Event 1", "Event 2", "Event 3", "Event 4"] 

662 assert res.next_page_token 

663 

664 res = api.EventSearch(search_pb2.EventSearchReq(page_size=4, page_token=res.next_page_token)) 

665 assert len(res.events) == 1 

666 assert res.events[0].title == "Event 5" 

667 assert res.next_page_token == "" 

668 

669 # move all the events into the past to test past pagination 

670 with session_scope() as session: 

671 for occurrence in session.execute(select(EventOccurrence)).scalars().all(): 

672 occurrence.during = TimestamptzRange( 

673 occurrence.start_time - timedelta(days=30), occurrence.end_time - timedelta(days=30) 

674 ) 

675 

676 with search_session(token) as api: 

677 res = api.EventSearch(search_pb2.EventSearchReq(past=True, page_size=2)) 

678 assert [event.title for event in res.events] == ["Event 5", "Event 4"] 

679 assert res.next_page_token 

680 

681 res = api.EventSearch(search_pb2.EventSearchReq(past=True, page_size=2, page_token=res.next_page_token)) 

682 assert [event.title for event in res.events] == ["Event 3", "Event 2"] 

683 assert res.next_page_token 

684 

685 res = api.EventSearch(search_pb2.EventSearchReq(past=True, page_size=2, page_token=res.next_page_token)) 

686 assert [event.title for event in res.events] == ["Event 1"] 

687 assert res.next_page_token == "" 

688 

689 

690def test_event_search_pagination_with_page_number(sample_community): 

691 """Test that EventSearch paginates correctly with page number. 

692 

693 Check that 

694 - <page_size> events are returned, if available 

695 - sort order is applied (default: past=False) 

696 - <page_number> is respected 

697 - <total_items> is correct 

698 """ 

699 user, token = generate_user() 

700 

701 anchor_time = now() 

702 for i in range(5): 

703 events_api.create_event( 

704 token=token, 

705 title=f"Event {i + 1}", 

706 start_date_time=local_date_time(anchor_time + timedelta(hours=i + 1)), 

707 end_date_time=local_date_time(anchor_time + timedelta(hours=i + 1, minutes=30)), 

708 ) 

709 

710 with search_session(token) as api: 

711 res = api.EventSearch(search_pb2.EventSearchReq(page_size=2, page_number=1)) 

712 assert len(res.events) == 2 

713 assert [event.title for event in res.events] == ["Event 1", "Event 2"] 

714 assert res.total_items == 5 

715 

716 res = api.EventSearch(search_pb2.EventSearchReq(page_size=2, page_number=2)) 

717 assert len(res.events) == 2 

718 assert [event.title for event in res.events] == ["Event 3", "Event 4"] 

719 assert res.total_items == 5 

720 

721 res = api.EventSearch(search_pb2.EventSearchReq(page_size=2, page_number=3)) 

722 assert len(res.events) == 1 

723 assert [event.title for event in res.events] == ["Event 5"] 

724 assert res.total_items == 5 

725 

726 # Verify no more pages 

727 res = api.EventSearch(search_pb2.EventSearchReq(page_size=2, page_number=4)) 

728 assert not res.events 

729 assert res.total_items == 5 

730 

731 

732def test_event_search_filter_subscription_attendance_organizing_my_communities(sample_community, moderator: Moderator): 

733 """Test that EventSearch respects subscribed, attending, organizing and my_communities filters and by default 

734 returns all events. 

735 """ 

736 _, token = generate_user() 

737 other_user, other_token = generate_user() 

738 

739 with communities_session(token) as api: 

740 api.JoinCommunity(communities_pb2.JoinCommunityReq(community_id=sample_community)) 

741 

742 with session_scope() as session: 

743 create_community(session, 55, 60, "Other community", [other_user], [], None) 

744 

745 e_subscribed = events_api.create_event(token=other_token, title="Subscribed event") 

746 e_attending = events_api.create_event(token=other_token, title="Attending event") 

747 events_api.create_event(token=other_token, title="Community event") 

748 events_api.create_event( 

749 token=other_token, 

750 title="Other community event", 

751 location=events_pb2.EventLocation(lat=58, lng=1, address="Somewhere"), 

752 ) 

753 

754 # Approve all events so they're visible to other users 

755 with session_scope() as session: 

756 occurrence_ids = session.execute(select(EventOccurrence.id)).scalars().all() 

757 for oid in occurrence_ids: 

758 moderator.approve_event_occurrence(oid) 

759 

760 events_api.create_event(token=token, title="Organized event") 

761 events_api.set_event_subscription(token=token, event_id=e_subscribed.event_id, subscribe=True) 

762 events_api.set_event_attendance( 

763 token=token, event_id=e_attending.event_id, attendance_state=events_pb2.ATTENDANCE_STATE_GOING 

764 ) 

765 

766 with search_session(token) as api: 

767 res = api.EventSearch(search_pb2.EventSearchReq()) 

768 assert {event.title for event in res.events} == { 

769 "Subscribed event", 

770 "Attending event", 

771 "Community event", 

772 "Other community event", 

773 "Organized event", 

774 } 

775 

776 res = api.EventSearch(search_pb2.EventSearchReq(subscribed=True)) 

777 assert {event.title for event in res.events} == {"Subscribed event", "Organized event"} 

778 

779 res = api.EventSearch(search_pb2.EventSearchReq(attending=True)) 

780 assert {event.title for event in res.events} == {"Attending event", "Organized event"} 

781 

782 res = api.EventSearch(search_pb2.EventSearchReq(organizing=True)) 

783 assert {event.title for event in res.events} == {"Organized event"} 

784 

785 res = api.EventSearch(search_pb2.EventSearchReq(my_communities=True)) 

786 assert {event.title for event in res.events} == { 

787 "Subscribed event", 

788 "Attending event", 

789 "Community event", 

790 "Organized event", 

791 } 

792 

793 res = api.EventSearch(search_pb2.EventSearchReq(subscribed=True, attending=True)) 

794 assert {event.title for event in res.events} == {"Subscribed event", "Attending event", "Organized event"} 

795 

796 

797def test_event_search_exclude_attending(sample_community, moderator: Moderator): 

798 """Test that exclude_attending removes events the user is attending or organizing.""" 

799 user, token = generate_user() 

800 other_user, other_token = generate_user() 

801 

802 with communities_session(token) as api: 

803 api.JoinCommunity(communities_pb2.JoinCommunityReq(community_id=sample_community)) 

804 

805 with session_scope() as session: 

806 create_community(session, 55, 60, "Other community", [other_user], [], None) 

807 

808 e_attending = events_api.create_event(token=other_token, title="Attending event") 

809 e_community_only = events_api.create_event(token=other_token, title="Community only event") 

810 events_api.create_event( 

811 token=other_token, 

812 title="Other community event", 

813 location=events_pb2.EventLocation(lat=58, lng=1, address="Somewhere"), 

814 ) 

815 

816 with session_scope() as session: 

817 occurrence_ids = session.execute(select(EventOccurrence.id)).scalars().all() 

818 for oid in occurrence_ids: 

819 moderator.approve_event_occurrence(oid) 

820 

821 e_organized = events_api.create_event(token=token, title="Organized event") 

822 events_api.set_event_attendance( 

823 token=token, event_id=e_attending.event_id, attendance_state=events_pb2.ATTENDANCE_STATE_GOING 

824 ) 

825 

826 with search_session(token) as api: 

827 # baseline: my_communities returns all community events including attended/organized 

828 res = api.EventSearch(search_pb2.EventSearchReq(my_communities=True)) 

829 assert {event.title for event in res.events} == { 

830 "Attending event", 

831 "Community only event", 

832 "Organized event", 

833 } 

834 

835 # my_communities + exclude_attending: drops attended and organized events 

836 res = api.EventSearch(search_pb2.EventSearchReq(my_communities=True, exclude_attending=True)) 

837 assert {event.title for event in res.events} == {"Community only event"} 

838 

839 # exclude_attending alone (no other filter = all events): drops attended and organized 

840 res = api.EventSearch(search_pb2.EventSearchReq(exclude_attending=True)) 

841 assert {event.title for event in res.events} == {"Community only event", "Other community event"} 

842 

843 # attending + exclude_attending is invalid 

844 with pytest.raises(grpc.RpcError) as e: 

845 api.EventSearch(search_pb2.EventSearchReq(attending=True, exclude_attending=True)) 

846 assert e.value.code() == grpc.StatusCode.INVALID_ARGUMENT 

847 

848 

849def test_regression_search_multiple_pages(db): 

850 """ 

851 There was a bug when there are multiple pages of results 

852 """ 

853 user, token = generate_user() 

854 user_ids = [user.id] 

855 for _ in range(10): 

856 other_user, _ = generate_user() 

857 user_ids.append(other_user.id) 

858 

859 refresh_materialized_views_rapid(empty_pb2.Empty()) 

860 refresh_materialized_views(empty_pb2.Empty()) 

861 

862 with search_session(token) as api: 

863 res = api.UserSearchV2(search_pb2.UserSearchReq(page_size=5)) 

864 assert [result.user_id for result in res.results] == user_ids[:5] 

865 assert res.next_page_token 

866 

867 

868def test_regression_search_no_results(db): 

869 """ 

870 There was a bug when there were no results 

871 """ 

872 # put us far away 

873 user, token = generate_user() 

874 

875 refresh_materialized_views_rapid(empty_pb2.Empty()) 

876 refresh_materialized_views(empty_pb2.Empty()) 

877 

878 with search_session(token) as api: 

879 res = api.UserSearchV2(search_pb2.UserSearchReq(only_with_references=True)) 

880 assert len(res.results) == 0 

881 

882 

883def test_user_filter_same_gender_only(db): 

884 """Test that same_gender_only filter works correctly""" 

885 # Create users with different genders and strong verification status 

886 woman_with_sv, token_woman_with_sv = generate_user(strong_verification=True, gender="Woman") 

887 woman_without_sv, token_woman_without_sv = generate_user(strong_verification=False, gender="Woman") 

888 man_with_sv, token_man_with_sv = generate_user(strong_verification=True, gender="Man") 

889 man_without_sv, _ = generate_user(strong_verification=False, gender="Man") 

890 other_woman_with_sv, _ = generate_user(strong_verification=True, gender="Woman") 

891 

892 refresh_materialized_views_rapid(empty_pb2.Empty()) 

893 refresh_materialized_views(empty_pb2.Empty()) 

894 

895 # Test 1: Woman with strong verification should see only women when same_gender_only=True 

896 with search_session(token_woman_with_sv) as api: 

897 res = api.UserSearchV2(search_pb2.UserSearchReq(same_gender_only=True)) 

898 result_ids = [result.user_id for result in res.results] 

899 assert woman_with_sv.id in result_ids 

900 assert woman_without_sv.id in result_ids 

901 assert other_woman_with_sv.id in result_ids 

902 assert man_with_sv.id not in result_ids 

903 assert man_without_sv.id not in result_ids 

904 

905 # Test 2: Man with strong verification should see only men when same_gender_only=True 

906 with search_session(token_man_with_sv) as api: 

907 res = api.UserSearchV2(search_pb2.UserSearchReq(same_gender_only=True)) 

908 result_ids = [result.user_id for result in res.results] 

909 assert man_with_sv.id in result_ids 

910 assert man_without_sv.id in result_ids 

911 assert woman_with_sv.id not in result_ids 

912 assert woman_without_sv.id not in result_ids 

913 assert other_woman_with_sv.id not in result_ids 

914 

915 # Test 3: Woman without strong verification should get an error 

916 with search_session(token_woman_without_sv) as api: 

917 with pytest.raises(Exception) as e: 

918 api.UserSearchV2(search_pb2.UserSearchReq(same_gender_only=True)) 

919 assert "NEED_STRONG_VERIFICATION" in str(e.value) or "FAILED_PRECONDITION" in str(e.value) 

920 

921 # Test 4: When same_gender_only=False, should see all users 

922 with search_session(token_woman_with_sv) as api: 

923 res = api.UserSearchV2(search_pb2.UserSearchReq(same_gender_only=False)) 

924 result_ids = [result.user_id for result in res.results] 

925 assert woman_with_sv.id in result_ids 

926 assert woman_without_sv.id in result_ids 

927 assert other_woman_with_sv.id in result_ids 

928 assert man_with_sv.id in result_ids 

929 assert man_without_sv.id in result_ids 

930 

931 

932def test_user_filter_same_gender_only_with_other_filters(db): 

933 """Test that same_gender_only filter works correctly combined with other filters""" 

934 # Create users with different properties 

935 woman_host, token_woman = generate_user( 

936 strong_verification=True, gender="Woman", hosting_status=HostingStatus.can_host 

937 ) 

938 woman_cant_host, _ = generate_user(strong_verification=True, gender="Woman", hosting_status=HostingStatus.cant_host) 

939 man_host, _ = generate_user(strong_verification=True, gender="Man", hosting_status=HostingStatus.can_host) 

940 

941 refresh_materialized_views_rapid(empty_pb2.Empty()) 

942 refresh_materialized_views(empty_pb2.Empty()) 

943 

944 # Test: Combine same_gender_only with hosting_status filter 

945 with search_session(token_woman) as api: 

946 res = api.UserSearchV2( 

947 search_pb2.UserSearchReq(same_gender_only=True, hosting_status_filter=[api_pb2.HOSTING_STATUS_CAN_HOST]) 

948 ) 

949 result_ids = [result.user_id for result in res.results] 

950 assert woman_host.id in result_ids 

951 assert woman_cant_host.id not in result_ids 

952 assert man_host.id not in result_ids