1
0

test_statistics.py 18 KB

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