test_statistics.py 19 KB

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