test_statistics.py 17 KB

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