1
0

test_statistics.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. # Copyright 2020 Dirk Klimpel
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from typing import List, Optional
  16. from twisted.test.proto_helpers import MemoryReactor
  17. import synapse.rest.admin
  18. from synapse.api.errors import Codes
  19. from synapse.rest.client import login
  20. from synapse.server import HomeServer
  21. from synapse.types import JsonDict
  22. from synapse.util import Clock
  23. from tests import unittest
  24. from tests.test_utils import SMALL_PNG
  25. class UserMediaStatisticsTestCase(unittest.HomeserverTestCase):
  26. servlets = [
  27. synapse.rest.admin.register_servlets,
  28. login.register_servlets,
  29. ]
  30. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  31. self.media_repo = hs.get_media_repository_resource()
  32. self.admin_user = self.register_user("admin", "pass", admin=True)
  33. self.admin_user_tok = self.login("admin", "pass")
  34. self.other_user = self.register_user("user", "pass")
  35. self.other_user_tok = self.login("user", "pass")
  36. self.url = "/_synapse/admin/v1/statistics/users/media"
  37. def test_no_auth(self) -> None:
  38. """
  39. Try to list users without authentication.
  40. """
  41. channel = self.make_request("GET", self.url, b"{}")
  42. self.assertEqual(401, channel.code, msg=channel.json_body)
  43. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  44. def test_requester_is_no_admin(self) -> None:
  45. """
  46. If the user is not a server admin, an error 403 is returned.
  47. """
  48. channel = self.make_request(
  49. "GET",
  50. self.url,
  51. {},
  52. access_token=self.other_user_tok,
  53. )
  54. self.assertEqual(403, channel.code, msg=channel.json_body)
  55. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  56. def test_invalid_parameter(self) -> None:
  57. """
  58. If parameters are invalid, an error is returned.
  59. """
  60. # unkown order_by
  61. channel = self.make_request(
  62. "GET",
  63. self.url + "?order_by=bar",
  64. access_token=self.admin_user_tok,
  65. )
  66. self.assertEqual(400, channel.code, msg=channel.json_body)
  67. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  68. # negative from
  69. channel = self.make_request(
  70. "GET",
  71. self.url + "?from=-5",
  72. access_token=self.admin_user_tok,
  73. )
  74. self.assertEqual(400, channel.code, msg=channel.json_body)
  75. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  76. # negative limit
  77. channel = self.make_request(
  78. "GET",
  79. self.url + "?limit=-5",
  80. access_token=self.admin_user_tok,
  81. )
  82. self.assertEqual(400, channel.code, msg=channel.json_body)
  83. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  84. # negative from_ts
  85. channel = self.make_request(
  86. "GET",
  87. self.url + "?from_ts=-1234",
  88. access_token=self.admin_user_tok,
  89. )
  90. self.assertEqual(400, channel.code, msg=channel.json_body)
  91. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  92. # negative until_ts
  93. channel = self.make_request(
  94. "GET",
  95. self.url + "?until_ts=-1234",
  96. access_token=self.admin_user_tok,
  97. )
  98. self.assertEqual(400, channel.code, msg=channel.json_body)
  99. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  100. # until_ts smaller from_ts
  101. channel = self.make_request(
  102. "GET",
  103. self.url + "?from_ts=10&until_ts=5",
  104. access_token=self.admin_user_tok,
  105. )
  106. self.assertEqual(400, channel.code, msg=channel.json_body)
  107. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  108. # empty search term
  109. channel = self.make_request(
  110. "GET",
  111. self.url + "?search_term=",
  112. access_token=self.admin_user_tok,
  113. )
  114. self.assertEqual(400, channel.code, msg=channel.json_body)
  115. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  116. # invalid search order
  117. channel = self.make_request(
  118. "GET",
  119. self.url + "?dir=bar",
  120. access_token=self.admin_user_tok,
  121. )
  122. self.assertEqual(400, channel.code, msg=channel.json_body)
  123. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  124. def test_limit(self) -> None:
  125. """
  126. Testing list of media with limit
  127. """
  128. self._create_users_with_media(10, 2)
  129. channel = self.make_request(
  130. "GET",
  131. self.url + "?limit=5",
  132. access_token=self.admin_user_tok,
  133. )
  134. self.assertEqual(200, channel.code, msg=channel.json_body)
  135. self.assertEqual(channel.json_body["total"], 10)
  136. self.assertEqual(len(channel.json_body["users"]), 5)
  137. self.assertEqual(channel.json_body["next_token"], 5)
  138. self._check_fields(channel.json_body["users"])
  139. def test_from(self) -> None:
  140. """
  141. Testing list of media with a defined starting point (from)
  142. """
  143. self._create_users_with_media(20, 2)
  144. channel = self.make_request(
  145. "GET",
  146. self.url + "?from=5",
  147. access_token=self.admin_user_tok,
  148. )
  149. self.assertEqual(200, channel.code, msg=channel.json_body)
  150. self.assertEqual(channel.json_body["total"], 20)
  151. self.assertEqual(len(channel.json_body["users"]), 15)
  152. self.assertNotIn("next_token", channel.json_body)
  153. self._check_fields(channel.json_body["users"])
  154. def test_limit_and_from(self) -> None:
  155. """
  156. Testing list of media with a defined starting point and limit
  157. """
  158. self._create_users_with_media(20, 2)
  159. channel = self.make_request(
  160. "GET",
  161. self.url + "?from=5&limit=10",
  162. access_token=self.admin_user_tok,
  163. )
  164. self.assertEqual(200, channel.code, msg=channel.json_body)
  165. self.assertEqual(channel.json_body["total"], 20)
  166. self.assertEqual(channel.json_body["next_token"], 15)
  167. self.assertEqual(len(channel.json_body["users"]), 10)
  168. self._check_fields(channel.json_body["users"])
  169. def test_next_token(self) -> None:
  170. """
  171. Testing that `next_token` appears at the right place
  172. """
  173. number_users = 20
  174. self._create_users_with_media(number_users, 3)
  175. # `next_token` does not appear
  176. # Number of results is the number of entries
  177. channel = self.make_request(
  178. "GET",
  179. self.url + "?limit=20",
  180. access_token=self.admin_user_tok,
  181. )
  182. self.assertEqual(200, channel.code, msg=channel.json_body)
  183. self.assertEqual(channel.json_body["total"], number_users)
  184. self.assertEqual(len(channel.json_body["users"]), number_users)
  185. self.assertNotIn("next_token", channel.json_body)
  186. # `next_token` does not appear
  187. # Number of max results is larger than the number of entries
  188. channel = self.make_request(
  189. "GET",
  190. self.url + "?limit=21",
  191. access_token=self.admin_user_tok,
  192. )
  193. self.assertEqual(200, channel.code, msg=channel.json_body)
  194. self.assertEqual(channel.json_body["total"], number_users)
  195. self.assertEqual(len(channel.json_body["users"]), number_users)
  196. self.assertNotIn("next_token", channel.json_body)
  197. # `next_token` does appear
  198. # Number of max results is smaller than the number of entries
  199. channel = self.make_request(
  200. "GET",
  201. self.url + "?limit=19",
  202. access_token=self.admin_user_tok,
  203. )
  204. self.assertEqual(200, channel.code, msg=channel.json_body)
  205. self.assertEqual(channel.json_body["total"], number_users)
  206. self.assertEqual(len(channel.json_body["users"]), 19)
  207. self.assertEqual(channel.json_body["next_token"], 19)
  208. # Set `from` to value of `next_token` for request remaining entries
  209. # Check `next_token` does not appear
  210. channel = self.make_request(
  211. "GET",
  212. self.url + "?from=19",
  213. access_token=self.admin_user_tok,
  214. )
  215. self.assertEqual(200, channel.code, msg=channel.json_body)
  216. self.assertEqual(channel.json_body["total"], number_users)
  217. self.assertEqual(len(channel.json_body["users"]), 1)
  218. self.assertNotIn("next_token", channel.json_body)
  219. def test_no_media(self) -> None:
  220. """
  221. Tests that a normal lookup for statistics is successfully
  222. if users have no media created
  223. """
  224. channel = self.make_request(
  225. "GET",
  226. self.url,
  227. access_token=self.admin_user_tok,
  228. )
  229. self.assertEqual(200, channel.code, msg=channel.json_body)
  230. self.assertEqual(0, channel.json_body["total"])
  231. self.assertEqual(0, len(channel.json_body["users"]))
  232. def test_order_by(self) -> None:
  233. """
  234. Testing order list with parameter `order_by`
  235. """
  236. # create users
  237. self.register_user("user_a", "pass", displayname="UserZ")
  238. userA_tok = self.login("user_a", "pass")
  239. self._create_media(userA_tok, 1)
  240. self.register_user("user_b", "pass", displayname="UserY")
  241. userB_tok = self.login("user_b", "pass")
  242. self._create_media(userB_tok, 3)
  243. self.register_user("user_c", "pass", displayname="UserX")
  244. userC_tok = self.login("user_c", "pass")
  245. self._create_media(userC_tok, 2)
  246. # order by user_id
  247. self._order_test("user_id", ["@user_a:test", "@user_b:test", "@user_c:test"])
  248. self._order_test(
  249. "user_id",
  250. ["@user_a:test", "@user_b:test", "@user_c:test"],
  251. "f",
  252. )
  253. self._order_test(
  254. "user_id",
  255. ["@user_c:test", "@user_b:test", "@user_a:test"],
  256. "b",
  257. )
  258. # order by displayname
  259. self._order_test(
  260. "displayname", ["@user_c:test", "@user_b:test", "@user_a:test"]
  261. )
  262. self._order_test(
  263. "displayname",
  264. ["@user_c:test", "@user_b:test", "@user_a:test"],
  265. "f",
  266. )
  267. self._order_test(
  268. "displayname",
  269. ["@user_a:test", "@user_b:test", "@user_c:test"],
  270. "b",
  271. )
  272. # order by media_length
  273. self._order_test(
  274. "media_length",
  275. ["@user_a:test", "@user_c:test", "@user_b:test"],
  276. )
  277. self._order_test(
  278. "media_length",
  279. ["@user_a:test", "@user_c:test", "@user_b:test"],
  280. "f",
  281. )
  282. self._order_test(
  283. "media_length",
  284. ["@user_b:test", "@user_c:test", "@user_a:test"],
  285. "b",
  286. )
  287. # order by media_count
  288. self._order_test(
  289. "media_count",
  290. ["@user_a:test", "@user_c:test", "@user_b:test"],
  291. )
  292. self._order_test(
  293. "media_count",
  294. ["@user_a:test", "@user_c:test", "@user_b:test"],
  295. "f",
  296. )
  297. self._order_test(
  298. "media_count",
  299. ["@user_b:test", "@user_c:test", "@user_a:test"],
  300. "b",
  301. )
  302. def test_from_until_ts(self) -> None:
  303. """
  304. Testing filter by time with parameters `from_ts` and `until_ts`
  305. """
  306. # create media earlier than `ts1` to ensure that `from_ts` is working
  307. self._create_media(self.other_user_tok, 3)
  308. self.pump(1)
  309. ts1 = self.clock.time_msec()
  310. # list all media when filter is not set
  311. channel = self.make_request(
  312. "GET",
  313. self.url,
  314. access_token=self.admin_user_tok,
  315. )
  316. self.assertEqual(200, channel.code, msg=channel.json_body)
  317. self.assertEqual(channel.json_body["users"][0]["media_count"], 3)
  318. # filter media starting at `ts1` after creating first media
  319. # result is 0
  320. channel = self.make_request(
  321. "GET",
  322. self.url + "?from_ts=%s" % (ts1,),
  323. access_token=self.admin_user_tok,
  324. )
  325. self.assertEqual(200, channel.code, msg=channel.json_body)
  326. self.assertEqual(channel.json_body["total"], 0)
  327. self._create_media(self.other_user_tok, 3)
  328. self.pump(1)
  329. ts2 = self.clock.time_msec()
  330. # create media after `ts2` to ensure that `until_ts` is working
  331. self._create_media(self.other_user_tok, 3)
  332. # filter media between `ts1` and `ts2`
  333. channel = self.make_request(
  334. "GET",
  335. self.url + "?from_ts=%s&until_ts=%s" % (ts1, ts2),
  336. access_token=self.admin_user_tok,
  337. )
  338. self.assertEqual(200, channel.code, msg=channel.json_body)
  339. self.assertEqual(channel.json_body["users"][0]["media_count"], 3)
  340. # filter media until `ts2` and earlier
  341. channel = self.make_request(
  342. "GET",
  343. self.url + "?until_ts=%s" % (ts2,),
  344. access_token=self.admin_user_tok,
  345. )
  346. self.assertEqual(200, channel.code, msg=channel.json_body)
  347. self.assertEqual(channel.json_body["users"][0]["media_count"], 6)
  348. def test_search_term(self) -> None:
  349. self._create_users_with_media(20, 1)
  350. # check without filter get all users
  351. channel = self.make_request(
  352. "GET",
  353. self.url,
  354. access_token=self.admin_user_tok,
  355. )
  356. self.assertEqual(200, channel.code, msg=channel.json_body)
  357. self.assertEqual(channel.json_body["total"], 20)
  358. # filter user 1 and 10-19 by `user_id`
  359. channel = self.make_request(
  360. "GET",
  361. self.url + "?search_term=foo_user_1",
  362. access_token=self.admin_user_tok,
  363. )
  364. self.assertEqual(200, channel.code, msg=channel.json_body)
  365. self.assertEqual(channel.json_body["total"], 11)
  366. # filter on this user in `displayname`
  367. channel = self.make_request(
  368. "GET",
  369. self.url + "?search_term=bar_user_10",
  370. access_token=self.admin_user_tok,
  371. )
  372. self.assertEqual(200, channel.code, msg=channel.json_body)
  373. self.assertEqual(channel.json_body["users"][0]["displayname"], "bar_user_10")
  374. self.assertEqual(channel.json_body["total"], 1)
  375. # filter and get empty result
  376. channel = self.make_request(
  377. "GET",
  378. self.url + "?search_term=foobar",
  379. access_token=self.admin_user_tok,
  380. )
  381. self.assertEqual(200, channel.code, msg=channel.json_body)
  382. self.assertEqual(channel.json_body["total"], 0)
  383. def _create_users_with_media(self, number_users: int, media_per_user: int) -> None:
  384. """
  385. Create a number of users with a number of media
  386. Args:
  387. number_users: Number of users to be created
  388. media_per_user: Number of media to be created for each user
  389. """
  390. for i in range(number_users):
  391. self.register_user("foo_user_%s" % i, "pass", displayname="bar_user_%s" % i)
  392. user_tok = self.login("foo_user_%s" % i, "pass")
  393. self._create_media(user_tok, media_per_user)
  394. def _create_media(self, user_token: str, number_media: int) -> None:
  395. """
  396. Create a number of media for a specific user
  397. Args:
  398. user_token: Access token of the user
  399. number_media: Number of media to be created for the user
  400. """
  401. upload_resource = self.media_repo.children[b"upload"]
  402. for _ in range(number_media):
  403. # Upload some media into the room
  404. self.helper.upload_media(
  405. upload_resource, SMALL_PNG, tok=user_token, expect_code=200
  406. )
  407. def _check_fields(self, content: List[JsonDict]) -> None:
  408. """Checks that all attributes are present in content
  409. Args:
  410. content: List that is checked for content
  411. """
  412. for c in content:
  413. self.assertIn("user_id", c)
  414. self.assertIn("displayname", c)
  415. self.assertIn("media_count", c)
  416. self.assertIn("media_length", c)
  417. def _order_test(
  418. self, order_type: str, expected_user_list: List[str], dir: Optional[str] = None
  419. ) -> None:
  420. """Request the list of users in a certain order. Assert that order is what
  421. we expect
  422. Args:
  423. order_type: The type of ordering to give the server
  424. expected_user_list: The list of user_ids in the order we expect to get
  425. back from the server
  426. dir: The direction of ordering to give the server
  427. """
  428. url = self.url + "?order_by=%s" % (order_type,)
  429. if dir is not None and dir in ("b", "f"):
  430. url += "&dir=%s" % (dir,)
  431. channel = self.make_request(
  432. "GET",
  433. url.encode("ascii"),
  434. access_token=self.admin_user_tok,
  435. )
  436. self.assertEqual(200, channel.code, msg=channel.json_body)
  437. self.assertEqual(channel.json_body["total"], len(expected_user_list))
  438. returned_order = [row["user_id"] for row in channel.json_body["users"]]
  439. self.assertListEqual(expected_user_list, returned_order)
  440. self._check_fields(channel.json_body["users"])