utils.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017 Vector Creations Ltd
  4. # Copyright 2018-2019 New Vector Ltd
  5. # Copyright 2019 The Matrix.org Foundation C.I.C.
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import json
  19. import time
  20. from typing import Any, Dict, Optional
  21. import attr
  22. from twisted.web.resource import Resource
  23. from synapse.api.constants import Membership
  24. from tests.server import make_request, render
  25. @attr.s
  26. class RestHelper(object):
  27. """Contains extra helper functions to quickly and clearly perform a given
  28. REST action, which isn't the focus of the test.
  29. """
  30. hs = attr.ib()
  31. resource = attr.ib()
  32. auth_user_id = attr.ib()
  33. def create_room_as(
  34. self, room_creator=None, is_public=True, tok=None, expect_code=200,
  35. ):
  36. temp_id = self.auth_user_id
  37. self.auth_user_id = room_creator
  38. path = "/_matrix/client/r0/createRoom"
  39. content = {}
  40. if not is_public:
  41. content["visibility"] = "private"
  42. if tok:
  43. path = path + "?access_token=%s" % tok
  44. request, channel = make_request(
  45. self.hs.get_reactor(), "POST", path, json.dumps(content).encode("utf8")
  46. )
  47. render(request, self.resource, self.hs.get_reactor())
  48. assert channel.result["code"] == b"%d" % expect_code, channel.result
  49. self.auth_user_id = temp_id
  50. if expect_code == 200:
  51. return channel.json_body["room_id"]
  52. def invite(self, room=None, src=None, targ=None, expect_code=200, tok=None):
  53. self.change_membership(
  54. room=room,
  55. src=src,
  56. targ=targ,
  57. tok=tok,
  58. membership=Membership.INVITE,
  59. expect_code=expect_code,
  60. )
  61. def join(self, room=None, user=None, expect_code=200, tok=None):
  62. self.change_membership(
  63. room=room,
  64. src=user,
  65. targ=user,
  66. tok=tok,
  67. membership=Membership.JOIN,
  68. expect_code=expect_code,
  69. )
  70. def leave(self, room=None, user=None, expect_code=200, tok=None):
  71. self.change_membership(
  72. room=room,
  73. src=user,
  74. targ=user,
  75. tok=tok,
  76. membership=Membership.LEAVE,
  77. expect_code=expect_code,
  78. )
  79. def change_membership(
  80. self,
  81. room: str,
  82. src: str,
  83. targ: str,
  84. membership: str,
  85. extra_data: dict = {},
  86. tok: Optional[str] = None,
  87. expect_code: int = 200,
  88. ) -> None:
  89. """
  90. Send a membership state event into a room.
  91. Args:
  92. room: The ID of the room to send to
  93. src: The mxid of the event sender
  94. targ: The mxid of the event's target. The state key
  95. membership: The type of membership event
  96. extra_data: Extra information to include in the content of the event
  97. tok: The user access token to use
  98. expect_code: The expected HTTP response code
  99. """
  100. temp_id = self.auth_user_id
  101. self.auth_user_id = src
  102. path = "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % (room, targ)
  103. if tok:
  104. path = path + "?access_token=%s" % tok
  105. data = {"membership": membership}
  106. data.update(extra_data)
  107. request, channel = make_request(
  108. self.hs.get_reactor(), "PUT", path, json.dumps(data).encode("utf8")
  109. )
  110. render(request, self.resource, self.hs.get_reactor())
  111. assert int(channel.result["code"]) == expect_code, (
  112. "Expected: %d, got: %d, resp: %r"
  113. % (expect_code, int(channel.result["code"]), channel.result["body"])
  114. )
  115. self.auth_user_id = temp_id
  116. def send(self, room_id, body=None, txn_id=None, tok=None, expect_code=200):
  117. if body is None:
  118. body = "body_text_here"
  119. content = {"msgtype": "m.text", "body": body}
  120. return self.send_event(
  121. room_id, "m.room.message", content, txn_id, tok, expect_code
  122. )
  123. def send_event(
  124. self, room_id, type, content={}, txn_id=None, tok=None, expect_code=200
  125. ):
  126. if txn_id is None:
  127. txn_id = "m%s" % (str(time.time()))
  128. path = "/_matrix/client/r0/rooms/%s/send/%s/%s" % (room_id, type, txn_id)
  129. if tok:
  130. path = path + "?access_token=%s" % tok
  131. request, channel = make_request(
  132. self.hs.get_reactor(), "PUT", path, json.dumps(content).encode("utf8")
  133. )
  134. render(request, self.resource, self.hs.get_reactor())
  135. assert int(channel.result["code"]) == expect_code, (
  136. "Expected: %d, got: %d, resp: %r"
  137. % (expect_code, int(channel.result["code"]), channel.result["body"])
  138. )
  139. return channel.json_body
  140. def _read_write_state(
  141. self,
  142. room_id: str,
  143. event_type: str,
  144. body: Optional[Dict[str, Any]],
  145. tok: str,
  146. expect_code: int = 200,
  147. state_key: str = "",
  148. method: str = "GET",
  149. ) -> Dict:
  150. """Read or write some state from a given room
  151. Args:
  152. room_id:
  153. event_type: The type of state event
  154. body: Body that is sent when making the request. The content of the state event.
  155. If None, the request to the server will have an empty body
  156. tok: The access token to use
  157. expect_code: The HTTP code to expect in the response
  158. state_key:
  159. method: "GET" or "PUT" for reading or writing state, respectively
  160. Returns:
  161. The response body from the server
  162. Raises:
  163. AssertionError: if expect_code doesn't match the HTTP code we received
  164. """
  165. path = "/_matrix/client/r0/rooms/%s/state/%s/%s" % (
  166. room_id,
  167. event_type,
  168. state_key,
  169. )
  170. if tok:
  171. path = path + "?access_token=%s" % tok
  172. # Set request body if provided
  173. content = b""
  174. if body is not None:
  175. content = json.dumps(body).encode("utf8")
  176. request, channel = make_request(self.hs.get_reactor(), method, path, content)
  177. render(request, self.resource, self.hs.get_reactor())
  178. assert int(channel.result["code"]) == expect_code, (
  179. "Expected: %d, got: %d, resp: %r"
  180. % (expect_code, int(channel.result["code"]), channel.result["body"])
  181. )
  182. return channel.json_body
  183. def get_state(
  184. self,
  185. room_id: str,
  186. event_type: str,
  187. tok: str,
  188. expect_code: int = 200,
  189. state_key: str = "",
  190. ):
  191. """Gets some state from a room
  192. Args:
  193. room_id:
  194. event_type: The type of state event
  195. tok: The access token to use
  196. expect_code: The HTTP code to expect in the response
  197. state_key:
  198. Returns:
  199. The response body from the server
  200. Raises:
  201. AssertionError: if expect_code doesn't match the HTTP code we received
  202. """
  203. return self._read_write_state(
  204. room_id, event_type, None, tok, expect_code, state_key, method="GET"
  205. )
  206. def send_state(
  207. self,
  208. room_id: str,
  209. event_type: str,
  210. body: Dict[str, Any],
  211. tok: str,
  212. expect_code: int = 200,
  213. state_key: str = "",
  214. ):
  215. """Set some state in a room
  216. Args:
  217. room_id:
  218. event_type: The type of state event
  219. body: Body that is sent when making the request. The content of the state event.
  220. tok: The access token to use
  221. expect_code: The HTTP code to expect in the response
  222. state_key:
  223. Returns:
  224. The response body from the server
  225. Raises:
  226. AssertionError: if expect_code doesn't match the HTTP code we received
  227. """
  228. return self._read_write_state(
  229. room_id, event_type, body, tok, expect_code, state_key, method="PUT"
  230. )
  231. def upload_media(
  232. self,
  233. resource: Resource,
  234. image_data: bytes,
  235. tok: str,
  236. filename: str = "test.png",
  237. expect_code: int = 200,
  238. ) -> dict:
  239. """Upload a piece of test media to the media repo
  240. Args:
  241. resource: The resource that will handle the upload request
  242. image_data: The image data to upload
  243. tok: The user token to use during the upload
  244. filename: The filename of the media to be uploaded
  245. expect_code: The return code to expect from attempting to upload the media
  246. """
  247. image_length = len(image_data)
  248. path = "/_matrix/media/r0/upload?filename=%s" % (filename,)
  249. request, channel = make_request(
  250. self.hs.get_reactor(), "POST", path, content=image_data, access_token=tok
  251. )
  252. request.requestHeaders.addRawHeader(
  253. b"Content-Length", str(image_length).encode("UTF-8")
  254. )
  255. request.render(resource)
  256. self.hs.get_reactor().pump([100])
  257. assert channel.code == expect_code, "Expected: %d, got: %d, resp: %r" % (
  258. expect_code,
  259. int(channel.result["code"]),
  260. channel.result["body"],
  261. )
  262. return channel.json_body