test_user_directory.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. # Copyright 2018-2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import re
  15. from typing import Any, Dict, List, Optional, Set, Tuple, cast
  16. from unittest import mock
  17. from unittest.mock import Mock, patch
  18. from twisted.test.proto_helpers import MemoryReactor
  19. from synapse.api.constants import EventTypes, Membership, UserTypes
  20. from synapse.appservice import ApplicationService
  21. from synapse.rest import admin
  22. from synapse.rest.client import login, register, room
  23. from synapse.server import HomeServer
  24. from synapse.storage import DataStore
  25. from synapse.storage.background_updates import _BackgroundUpdateHandler
  26. from synapse.storage.databases.main import user_directory
  27. from synapse.storage.databases.main.user_directory import (
  28. _parse_words_with_icu,
  29. _parse_words_with_regex,
  30. )
  31. from synapse.storage.roommember import ProfileInfo
  32. from synapse.util import Clock
  33. from tests.server import ThreadedMemoryReactorClock
  34. from tests.test_utils.event_injection import inject_member_event
  35. from tests.unittest import HomeserverTestCase, override_config
  36. try:
  37. import icu
  38. except ImportError:
  39. icu = None # type: ignore
  40. ALICE = "@alice:a"
  41. BOB = "@bob:b"
  42. BOBBY = "@bobby:a"
  43. # The localpart isn't 'Bela' on purpose so we can test looking up display names.
  44. BELA = "@somenickname:example.org"
  45. class GetUserDirectoryTables:
  46. """Helper functions that we want to reuse in tests/handlers/test_user_directory.py"""
  47. def __init__(self, store: DataStore):
  48. self.store = store
  49. async def get_users_in_public_rooms(self) -> Set[Tuple[str, str]]:
  50. """Fetch the entire `users_in_public_rooms` table.
  51. Returns a list of tuples (user_id, room_id) where room_id is public and
  52. contains the user with the given id.
  53. """
  54. r = cast(
  55. List[Tuple[str, str]],
  56. await self.store.db_pool.simple_select_list(
  57. "users_in_public_rooms", None, ("user_id", "room_id")
  58. ),
  59. )
  60. return set(r)
  61. async def get_users_who_share_private_rooms(self) -> Set[Tuple[str, str, str]]:
  62. """Fetch the entire `users_who_share_private_rooms` table.
  63. Returns a set of tuples (user_id, other_user_id, room_id) corresponding
  64. to the rows of `users_who_share_private_rooms`.
  65. """
  66. rows = cast(
  67. List[Tuple[str, str, str]],
  68. await self.store.db_pool.simple_select_list(
  69. "users_who_share_private_rooms",
  70. None,
  71. ["user_id", "other_user_id", "room_id"],
  72. ),
  73. )
  74. return set(rows)
  75. async def get_users_in_user_directory(self) -> Set[str]:
  76. """Fetch the set of users in the `user_directory` table.
  77. This is useful when checking we've correctly excluded users from the directory.
  78. """
  79. result = cast(
  80. List[Tuple[str]],
  81. await self.store.db_pool.simple_select_list(
  82. "user_directory",
  83. None,
  84. ["user_id"],
  85. ),
  86. )
  87. return {row[0] for row in result}
  88. async def get_profiles_in_user_directory(self) -> Dict[str, ProfileInfo]:
  89. """Fetch users and their profiles from the `user_directory` table.
  90. This is useful when we want to inspect display names and avatars.
  91. It's almost the entire contents of the `user_directory` table: the only
  92. thing missing is an unused room_id column.
  93. """
  94. rows = cast(
  95. List[Tuple[str, Optional[str], Optional[str]]],
  96. await self.store.db_pool.simple_select_list(
  97. "user_directory",
  98. None,
  99. ("user_id", "display_name", "avatar_url"),
  100. ),
  101. )
  102. return {
  103. user_id: ProfileInfo(display_name=display_name, avatar_url=avatar_url)
  104. for user_id, display_name, avatar_url in rows
  105. }
  106. async def get_tables(
  107. self,
  108. ) -> Tuple[Set[str], Set[Tuple[str, str]], Set[Tuple[str, str, str]]]:
  109. """Multiple tests want to inspect these tables, so expose them together."""
  110. return (
  111. await self.get_users_in_user_directory(),
  112. await self.get_users_in_public_rooms(),
  113. await self.get_users_who_share_private_rooms(),
  114. )
  115. class UserDirectoryInitialPopulationTestcase(HomeserverTestCase):
  116. """Ensure that rebuilding the directory writes the correct data to the DB.
  117. See also tests/handlers/test_user_directory.py for similar checks. They
  118. test the incremental updates, rather than the big rebuild.
  119. """
  120. servlets = [
  121. login.register_servlets,
  122. admin.register_servlets,
  123. room.register_servlets,
  124. register.register_servlets,
  125. ]
  126. def make_homeserver(
  127. self, reactor: ThreadedMemoryReactorClock, clock: Clock
  128. ) -> HomeServer:
  129. self.appservice = ApplicationService(
  130. token="i_am_an_app_service",
  131. id="1234",
  132. namespaces={"users": [{"regex": r"@as_user.*", "exclusive": True}]},
  133. sender="@as:test",
  134. )
  135. mock_load_appservices = Mock(return_value=[self.appservice])
  136. with patch(
  137. "synapse.storage.databases.main.appservice.load_appservices",
  138. mock_load_appservices,
  139. ):
  140. hs = super().make_homeserver(reactor, clock)
  141. return hs
  142. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  143. self.store = hs.get_datastores().main
  144. self.user_dir_helper = GetUserDirectoryTables(self.store)
  145. def _purge_and_rebuild_user_dir(self) -> None:
  146. """Nuke the user directory tables, start the background process to
  147. repopulate them, and wait for the process to complete. This allows us
  148. to inspect the outcome of the background process alone, without any of
  149. the other incremental updates.
  150. """
  151. self.get_success(self.store.update_user_directory_stream_pos(None))
  152. self.get_success(self.store.delete_all_from_user_dir())
  153. shares_private = self.get_success(
  154. self.user_dir_helper.get_users_who_share_private_rooms()
  155. )
  156. public_users = self.get_success(
  157. self.user_dir_helper.get_users_in_public_rooms()
  158. )
  159. # Nothing updated yet
  160. self.assertEqual(shares_private, set())
  161. self.assertEqual(public_users, set())
  162. # Ugh, have to reset this flag
  163. self.store.db_pool.updates._all_done = False
  164. self.get_success(
  165. self.store.db_pool.simple_insert(
  166. "background_updates",
  167. {
  168. "update_name": "populate_user_directory_createtables",
  169. "progress_json": "{}",
  170. },
  171. )
  172. )
  173. self.get_success(
  174. self.store.db_pool.simple_insert(
  175. "background_updates",
  176. {
  177. "update_name": "populate_user_directory_process_rooms",
  178. "progress_json": "{}",
  179. "depends_on": "populate_user_directory_createtables",
  180. },
  181. )
  182. )
  183. self.get_success(
  184. self.store.db_pool.simple_insert(
  185. "background_updates",
  186. {
  187. "update_name": "populate_user_directory_process_users",
  188. "progress_json": "{}",
  189. "depends_on": "populate_user_directory_process_rooms",
  190. },
  191. )
  192. )
  193. self.get_success(
  194. self.store.db_pool.simple_insert(
  195. "background_updates",
  196. {
  197. "update_name": "populate_user_directory_cleanup",
  198. "progress_json": "{}",
  199. "depends_on": "populate_user_directory_process_users",
  200. },
  201. )
  202. )
  203. self.wait_for_background_updates()
  204. def test_initial(self) -> None:
  205. """
  206. The user directory's initial handler correctly updates the search tables.
  207. """
  208. u1 = self.register_user("user1", "pass")
  209. u1_token = self.login(u1, "pass")
  210. u2 = self.register_user("user2", "pass")
  211. u2_token = self.login(u2, "pass")
  212. u3 = self.register_user("user3", "pass")
  213. u3_token = self.login(u3, "pass")
  214. room = self.helper.create_room_as(u1, is_public=True, tok=u1_token)
  215. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  216. self.helper.join(room, user=u2, tok=u2_token)
  217. private_room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  218. self.helper.invite(private_room, src=u1, targ=u3, tok=u1_token)
  219. self.helper.join(private_room, user=u3, tok=u3_token)
  220. # Do the initial population of the user directory via the background update
  221. self._purge_and_rebuild_user_dir()
  222. users, in_public, in_private = self.get_success(
  223. self.user_dir_helper.get_tables()
  224. )
  225. # User 1 and User 2 are in the same public room
  226. self.assertEqual(in_public, {(u1, room), (u2, room)})
  227. # User 1 and User 3 share private rooms
  228. self.assertEqual(in_private, {(u1, u3, private_room), (u3, u1, private_room)})
  229. # All three should have entries in the directory
  230. self.assertEqual(users, {u1, u2, u3})
  231. # The next four tests (test_population_excludes_*) all set up
  232. # - A normal user included in the user dir
  233. # - A public and private room created by that user
  234. # - A user excluded from the room dir, belonging to both rooms
  235. # They match similar logic in handlers/test_user_directory.py But that tests
  236. # updating the directory; this tests rebuilding it from scratch.
  237. def _create_rooms_and_inject_memberships(
  238. self, creator: str, token: str, joiner: str
  239. ) -> Tuple[str, str]:
  240. """Create a public and private room as a normal user.
  241. Then get the `joiner` into those rooms.
  242. """
  243. public_room = self.helper.create_room_as(
  244. creator,
  245. is_public=True,
  246. # See https://github.com/matrix-org/synapse/issues/10951
  247. extra_content={"visibility": "public"},
  248. tok=token,
  249. )
  250. private_room = self.helper.create_room_as(creator, is_public=False, tok=token)
  251. # HACK: get the user into these rooms
  252. self.get_success(inject_member_event(self.hs, public_room, joiner, "join"))
  253. self.get_success(inject_member_event(self.hs, private_room, joiner, "join"))
  254. return public_room, private_room
  255. def _check_room_sharing_tables(
  256. self, normal_user: str, public_room: str, private_room: str
  257. ) -> None:
  258. # After rebuilding the directory, we should only see the normal user.
  259. users, in_public, in_private = self.get_success(
  260. self.user_dir_helper.get_tables()
  261. )
  262. self.assertEqual(users, {normal_user})
  263. self.assertEqual(in_public, {(normal_user, public_room)})
  264. self.assertEqual(in_private, set())
  265. def test_population_excludes_support_user(self) -> None:
  266. # Create a normal and support user.
  267. user = self.register_user("user", "pass")
  268. token = self.login(user, "pass")
  269. support = "@support1:test"
  270. self.get_success(
  271. self.store.register_user(
  272. user_id=support, password_hash=None, user_type=UserTypes.SUPPORT
  273. )
  274. )
  275. # Join the support user to rooms owned by the normal user.
  276. public, private = self._create_rooms_and_inject_memberships(
  277. user, token, support
  278. )
  279. # Rebuild the directory.
  280. self._purge_and_rebuild_user_dir()
  281. # Check the support user is not in the directory.
  282. self._check_room_sharing_tables(user, public, private)
  283. def test_population_excludes_deactivated_user(self) -> None:
  284. user = self.register_user("naughty", "pass")
  285. admin = self.register_user("admin", "pass", admin=True)
  286. admin_token = self.login(admin, "pass")
  287. # Deactivate the user.
  288. channel = self.make_request(
  289. "PUT",
  290. f"/_synapse/admin/v2/users/{user}",
  291. access_token=admin_token,
  292. content={"deactivated": True},
  293. )
  294. self.assertEqual(channel.code, 200)
  295. self.assertEqual(channel.json_body["deactivated"], True)
  296. # Join the deactivated user to rooms owned by the admin.
  297. # Is this something that could actually happen outside of a test?
  298. public, private = self._create_rooms_and_inject_memberships(
  299. admin, admin_token, user
  300. )
  301. # Rebuild the user dir. The deactivated user should be missing.
  302. self._purge_and_rebuild_user_dir()
  303. self._check_room_sharing_tables(admin, public, private)
  304. def test_population_excludes_appservice_user(self) -> None:
  305. # Register an AS user.
  306. user = self.register_user("user", "pass")
  307. token = self.login(user, "pass")
  308. as_user, _ = self.register_appservice_user(
  309. "as_user_potato", self.appservice.token
  310. )
  311. # Join the AS user to rooms owned by the normal user.
  312. public, private = self._create_rooms_and_inject_memberships(
  313. user, token, as_user
  314. )
  315. # Rebuild the directory.
  316. self._purge_and_rebuild_user_dir()
  317. # Check the AS user is not in the directory.
  318. self._check_room_sharing_tables(user, public, private)
  319. def test_population_excludes_appservice_sender(self) -> None:
  320. user = self.register_user("user", "pass")
  321. token = self.login(user, "pass")
  322. # Join the AS sender to rooms owned by the normal user.
  323. public, private = self._create_rooms_and_inject_memberships(
  324. user, token, self.appservice.sender
  325. )
  326. # Rebuild the directory.
  327. self._purge_and_rebuild_user_dir()
  328. # Check the AS sender is not in the directory.
  329. self._check_room_sharing_tables(user, public, private)
  330. def test_population_conceals_private_nickname(self) -> None:
  331. # Make a private room, and set a nickname within
  332. user = self.register_user("aaaa", "pass")
  333. user_token = self.login(user, "pass")
  334. private_room = self.helper.create_room_as(user, is_public=False, tok=user_token)
  335. self.helper.send_state(
  336. private_room,
  337. EventTypes.Member,
  338. state_key=user,
  339. body={"membership": Membership.JOIN, "displayname": "BBBB"},
  340. tok=user_token,
  341. )
  342. # Rebuild the user directory. Make the rescan of the `users` table a no-op
  343. # so we only see the effect of scanning the `room_memberships` table.
  344. async def mocked_process_users(*args: Any, **kwargs: Any) -> int:
  345. await self.store.db_pool.updates._end_background_update(
  346. "populate_user_directory_process_users"
  347. )
  348. return 1
  349. with mock.patch.dict(
  350. self.store.db_pool.updates._background_update_handlers,
  351. populate_user_directory_process_users=_BackgroundUpdateHandler(
  352. mocked_process_users,
  353. ),
  354. ):
  355. self._purge_and_rebuild_user_dir()
  356. # Local users are ignored by the scan over rooms
  357. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  358. self.assertEqual(users, {})
  359. # Do a full rebuild including the scan over the `users` table. The local
  360. # user should appear with their profile name.
  361. self._purge_and_rebuild_user_dir()
  362. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  363. self.assertEqual(
  364. users, {user: ProfileInfo(display_name="aaaa", avatar_url=None)}
  365. )
  366. class UserDirectoryStoreTestCase(HomeserverTestCase):
  367. use_icu = False
  368. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  369. self.store = hs.get_datastores().main
  370. # alice and bob are both in !room_id. bobby is not but shares
  371. # a homeserver with alice.
  372. self.get_success(self.store.update_profile_in_user_dir(ALICE, "alice", None))
  373. self.get_success(self.store.update_profile_in_user_dir(BOB, "bob", None))
  374. self.get_success(self.store.update_profile_in_user_dir(BOBBY, "bobby", None))
  375. self.get_success(self.store.update_profile_in_user_dir(BELA, "Bela", None))
  376. self.get_success(self.store.add_users_in_public_rooms("!room:id", (ALICE, BOB)))
  377. self._restore_use_icu = user_directory.USE_ICU
  378. user_directory.USE_ICU = self.use_icu
  379. def tearDown(self) -> None:
  380. user_directory.USE_ICU = self._restore_use_icu
  381. def test_search_user_dir(self) -> None:
  382. # normally when alice searches the directory she should just find
  383. # bob because bobby doesn't share a room with her.
  384. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 10))
  385. self.assertFalse(r["limited"])
  386. self.assertEqual(1, len(r["results"]))
  387. self.assertDictEqual(
  388. r["results"][0], {"user_id": BOB, "display_name": "bob", "avatar_url": None}
  389. )
  390. @override_config({"user_directory": {"search_all_users": True}})
  391. def test_search_user_dir_all_users(self) -> None:
  392. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 10))
  393. self.assertFalse(r["limited"])
  394. self.assertEqual(2, len(r["results"]))
  395. self.assertDictEqual(
  396. r["results"][0],
  397. {"user_id": BOB, "display_name": "bob", "avatar_url": None},
  398. )
  399. self.assertDictEqual(
  400. r["results"][1],
  401. {"user_id": BOBBY, "display_name": "bobby", "avatar_url": None},
  402. )
  403. @override_config({"user_directory": {"search_all_users": True}})
  404. def test_search_user_limit_correct(self) -> None:
  405. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 1))
  406. self.assertTrue(r["limited"])
  407. self.assertEqual(1, len(r["results"]))
  408. @override_config({"user_directory": {"search_all_users": True}})
  409. def test_search_user_dir_stop_words(self) -> None:
  410. """Tests that a user can look up another user by searching for the start if its
  411. display name even if that name happens to be a common English word that would
  412. usually be ignored in full text searches.
  413. """
  414. r = self.get_success(self.store.search_user_dir(ALICE, "be", 10))
  415. self.assertFalse(r["limited"])
  416. self.assertEqual(1, len(r["results"]))
  417. self.assertDictEqual(
  418. r["results"][0],
  419. {"user_id": BELA, "display_name": "Bela", "avatar_url": None},
  420. )
  421. @override_config({"user_directory": {"search_all_users": True}})
  422. def test_search_user_dir_start_of_user_id(self) -> None:
  423. """Tests that a user can look up another user by searching for the start
  424. of their user ID.
  425. """
  426. r = self.get_success(self.store.search_user_dir(ALICE, "somenickname:exa", 10))
  427. self.assertFalse(r["limited"])
  428. self.assertEqual(1, len(r["results"]))
  429. self.assertDictEqual(
  430. r["results"][0],
  431. {"user_id": BELA, "display_name": "Bela", "avatar_url": None},
  432. )
  433. @override_config({"user_directory": {"search_all_users": True}})
  434. def test_search_user_dir_ascii_case_insensitivity(self) -> None:
  435. """Tests that a user can look up another user by searching for their name in a
  436. different case.
  437. """
  438. CHARLIE = "@someuser:example.org"
  439. self.get_success(
  440. self.store.update_profile_in_user_dir(CHARLIE, "Charlie", None)
  441. )
  442. r = self.get_success(self.store.search_user_dir(ALICE, "cHARLIE", 10))
  443. self.assertFalse(r["limited"])
  444. self.assertEqual(1, len(r["results"]))
  445. self.assertDictEqual(
  446. r["results"][0],
  447. {"user_id": CHARLIE, "display_name": "Charlie", "avatar_url": None},
  448. )
  449. @override_config({"user_directory": {"search_all_users": True}})
  450. def test_search_user_dir_unicode_case_insensitivity(self) -> None:
  451. """Tests that a user can look up another user by searching for their name in a
  452. different case.
  453. """
  454. IVAN = "@someuser:example.org"
  455. self.get_success(self.store.update_profile_in_user_dir(IVAN, "Иван", None))
  456. r = self.get_success(self.store.search_user_dir(ALICE, "иВАН", 10))
  457. self.assertFalse(r["limited"])
  458. self.assertEqual(1, len(r["results"]))
  459. self.assertDictEqual(
  460. r["results"][0],
  461. {"user_id": IVAN, "display_name": "Иван", "avatar_url": None},
  462. )
  463. @override_config({"user_directory": {"search_all_users": True}})
  464. def test_search_user_dir_dotted_dotless_i_case_insensitivity(self) -> None:
  465. """Tests that a user can look up another user by searching for their name in a
  466. different case, when their name contains dotted or dotless "i"s.
  467. Some languages have dotted and dotless versions of "i", which are considered to
  468. be different letters: i <-> İ, ı <-> I. To make things difficult, they reuse the
  469. ASCII "i" and "I" code points, despite having different lowercase / uppercase
  470. forms.
  471. """
  472. USER = "@someuser:example.org"
  473. expected_matches = [
  474. # (search_term, display_name)
  475. # A search for "i" should match "İ".
  476. ("iiiii", "İİİİİ"),
  477. # A search for "I" should match "ı".
  478. ("IIIII", "ııııı"),
  479. # A search for "ı" should match "I".
  480. ("ııııı", "IIIII"),
  481. # A search for "İ" should match "i".
  482. ("İİİİİ", "iiiii"),
  483. ]
  484. for search_term, display_name in expected_matches:
  485. self.get_success(
  486. self.store.update_profile_in_user_dir(USER, display_name, None)
  487. )
  488. r = self.get_success(self.store.search_user_dir(ALICE, search_term, 10))
  489. self.assertFalse(r["limited"])
  490. self.assertEqual(
  491. 1,
  492. len(r["results"]),
  493. f"searching for {search_term!r} did not match {display_name!r}",
  494. )
  495. self.assertDictEqual(
  496. r["results"][0],
  497. {"user_id": USER, "display_name": display_name, "avatar_url": None},
  498. )
  499. # We don't test for negative matches, to allow implementations that consider all
  500. # the i variants to be the same.
  501. test_search_user_dir_dotted_dotless_i_case_insensitivity.skip = "not supported" # type: ignore
  502. @override_config({"user_directory": {"search_all_users": True}})
  503. def test_search_user_dir_unicode_normalization(self) -> None:
  504. """Tests that a user can look up another user by searching for their name with
  505. either composed or decomposed accents.
  506. """
  507. AMELIE = "@someuser:example.org"
  508. expected_matches = [
  509. # (search_term, display_name)
  510. ("Ame\u0301lie", "Amélie"),
  511. ("Amélie", "Ame\u0301lie"),
  512. ]
  513. for search_term, display_name in expected_matches:
  514. self.get_success(
  515. self.store.update_profile_in_user_dir(AMELIE, display_name, None)
  516. )
  517. r = self.get_success(self.store.search_user_dir(ALICE, search_term, 10))
  518. self.assertFalse(r["limited"])
  519. self.assertEqual(
  520. 1,
  521. len(r["results"]),
  522. f"searching for {search_term!r} did not match {display_name!r}",
  523. )
  524. self.assertDictEqual(
  525. r["results"][0],
  526. {"user_id": AMELIE, "display_name": display_name, "avatar_url": None},
  527. )
  528. @override_config({"user_directory": {"search_all_users": True}})
  529. def test_search_user_dir_accent_insensitivity(self) -> None:
  530. """Tests that a user can look up another user by searching for their name
  531. without any accents.
  532. """
  533. AMELIE = "@someuser:example.org"
  534. self.get_success(self.store.update_profile_in_user_dir(AMELIE, "Amélie", None))
  535. r = self.get_success(self.store.search_user_dir(ALICE, "amelie", 10))
  536. self.assertFalse(r["limited"])
  537. self.assertEqual(1, len(r["results"]))
  538. self.assertDictEqual(
  539. r["results"][0],
  540. {"user_id": AMELIE, "display_name": "Amélie", "avatar_url": None},
  541. )
  542. # It may be desirable for "é"s in search terms to not match plain "e"s and we
  543. # really don't want "é"s in search terms to match "e"s with different accents.
  544. # But we don't test for this to allow implementations that consider all
  545. # "e"-lookalikes to be the same.
  546. test_search_user_dir_accent_insensitivity.skip = "not supported yet" # type: ignore
  547. class UserDirectoryStoreTestCaseWithIcu(UserDirectoryStoreTestCase):
  548. use_icu = True
  549. if not icu:
  550. skip = "Requires PyICU"
  551. class UserDirectoryICUTestCase(HomeserverTestCase):
  552. if not icu:
  553. skip = "Requires PyICU"
  554. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  555. self.store = hs.get_datastores().main
  556. self.user_dir_helper = GetUserDirectoryTables(self.store)
  557. def test_icu_word_boundary(self) -> None:
  558. """Tests that we correctly detect word boundaries when ICU (International
  559. Components for Unicode) support is available.
  560. """
  561. display_name = "Gáo"
  562. # This word is not broken down correctly by Python's regular expressions,
  563. # likely because á is actually a lowercase a followed by a U+0301 combining
  564. # acute accent. This is specifically something that ICU support fixes.
  565. matches = re.findall(r"([\w\-]+)", display_name, re.UNICODE)
  566. self.assertEqual(len(matches), 2)
  567. self.get_success(
  568. self.store.update_profile_in_user_dir(ALICE, display_name, None)
  569. )
  570. self.get_success(self.store.add_users_in_public_rooms("!room:id", (ALICE,)))
  571. # Check that searching for this user yields the correct result.
  572. r = self.get_success(self.store.search_user_dir(BOB, display_name, 10))
  573. self.assertFalse(r["limited"])
  574. self.assertEqual(len(r["results"]), 1)
  575. self.assertDictEqual(
  576. r["results"][0],
  577. {"user_id": ALICE, "display_name": display_name, "avatar_url": None},
  578. )
  579. def test_icu_word_boundary_punctuation(self) -> None:
  580. """
  581. Tests the behaviour of punctuation with the ICU tokeniser.
  582. Seems to depend on underlying version of ICU.
  583. """
  584. # Note: either tokenisation is fine, because Postgres actually splits
  585. # words itself afterwards.
  586. self.assertIn(
  587. _parse_words_with_icu("lazy'fox jumped:over the.dog"),
  588. (
  589. # ICU 66 on Ubuntu 20.04
  590. ["lazy'fox", "jumped", "over", "the", "dog"],
  591. # ICU 70 on Ubuntu 22.04
  592. ["lazy'fox", "jumped:over", "the.dog"],
  593. # pyicu 2.10.2 on Alpine edge / macOS
  594. ["lazy'fox", "jumped", "over", "the.dog"],
  595. ),
  596. )
  597. def test_regex_word_boundary_punctuation(self) -> None:
  598. """
  599. Tests the behaviour of punctuation with the non-ICU tokeniser
  600. """
  601. self.assertEqual(
  602. _parse_words_with_regex("lazy'fox jumped:over the.dog"),
  603. ["lazy", "fox", "jumped", "over", "the", "dog"],
  604. )