utils.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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(self, room_creator=None, is_public=True, tok=None):
  34. temp_id = self.auth_user_id
  35. self.auth_user_id = room_creator
  36. path = "/_matrix/client/r0/createRoom"
  37. content = {}
  38. if not is_public:
  39. content["visibility"] = "private"
  40. if tok:
  41. path = path + "?access_token=%s" % tok
  42. request, channel = make_request(
  43. self.hs.get_reactor(), "POST", path, json.dumps(content).encode("utf8")
  44. )
  45. render(request, self.resource, self.hs.get_reactor())
  46. assert channel.result["code"] == b"200", channel.result
  47. self.auth_user_id = temp_id
  48. return channel.json_body["room_id"]
  49. def invite(self, room=None, src=None, targ=None, expect_code=200, tok=None):
  50. self.change_membership(
  51. room=room,
  52. src=src,
  53. targ=targ,
  54. tok=tok,
  55. membership=Membership.INVITE,
  56. expect_code=expect_code,
  57. )
  58. def join(self, room=None, user=None, expect_code=200, tok=None):
  59. self.change_membership(
  60. room=room,
  61. src=user,
  62. targ=user,
  63. tok=tok,
  64. membership=Membership.JOIN,
  65. expect_code=expect_code,
  66. )
  67. def leave(self, room=None, user=None, expect_code=200, tok=None):
  68. self.change_membership(
  69. room=room,
  70. src=user,
  71. targ=user,
  72. tok=tok,
  73. membership=Membership.LEAVE,
  74. expect_code=expect_code,
  75. )
  76. def change_membership(self, room, src, targ, membership, tok=None, expect_code=200):
  77. temp_id = self.auth_user_id
  78. self.auth_user_id = src
  79. path = "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % (room, targ)
  80. if tok:
  81. path = path + "?access_token=%s" % tok
  82. data = {"membership": membership}
  83. request, channel = make_request(
  84. self.hs.get_reactor(), "PUT", path, json.dumps(data).encode("utf8")
  85. )
  86. render(request, self.resource, self.hs.get_reactor())
  87. assert int(channel.result["code"]) == expect_code, (
  88. "Expected: %d, got: %d, resp: %r"
  89. % (expect_code, int(channel.result["code"]), channel.result["body"])
  90. )
  91. self.auth_user_id = temp_id
  92. def send(self, room_id, body=None, txn_id=None, tok=None, expect_code=200):
  93. if body is None:
  94. body = "body_text_here"
  95. content = {"msgtype": "m.text", "body": body}
  96. return self.send_event(
  97. room_id, "m.room.message", content, txn_id, tok, expect_code
  98. )
  99. def send_event(
  100. self, room_id, type, content={}, txn_id=None, tok=None, expect_code=200
  101. ):
  102. if txn_id is None:
  103. txn_id = "m%s" % (str(time.time()))
  104. path = "/_matrix/client/r0/rooms/%s/send/%s/%s" % (room_id, type, txn_id)
  105. if tok:
  106. path = path + "?access_token=%s" % tok
  107. request, channel = make_request(
  108. self.hs.get_reactor(), "PUT", path, json.dumps(content).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. return channel.json_body
  116. def _read_write_state(
  117. self,
  118. room_id: str,
  119. event_type: str,
  120. body: Optional[Dict[str, Any]],
  121. tok: str,
  122. expect_code: int = 200,
  123. state_key: str = "",
  124. method: str = "GET",
  125. ) -> Dict:
  126. """Read or write some state from a given room
  127. Args:
  128. room_id:
  129. event_type: The type of state event
  130. body: Body that is sent when making the request. The content of the state event.
  131. If None, the request to the server will have an empty body
  132. tok: The access token to use
  133. expect_code: The HTTP code to expect in the response
  134. state_key:
  135. method: "GET" or "PUT" for reading or writing state, respectively
  136. Returns:
  137. The response body from the server
  138. Raises:
  139. AssertionError: if expect_code doesn't match the HTTP code we received
  140. """
  141. path = "/_matrix/client/r0/rooms/%s/state/%s/%s" % (
  142. room_id,
  143. event_type,
  144. state_key,
  145. )
  146. if tok:
  147. path = path + "?access_token=%s" % tok
  148. # Set request body if provided
  149. content = b""
  150. if body is not None:
  151. content = json.dumps(body).encode("utf8")
  152. request, channel = make_request(self.hs.get_reactor(), method, path, content)
  153. render(request, self.resource, self.hs.get_reactor())
  154. assert int(channel.result["code"]) == expect_code, (
  155. "Expected: %d, got: %d, resp: %r"
  156. % (expect_code, int(channel.result["code"]), channel.result["body"])
  157. )
  158. return channel.json_body
  159. def get_state(
  160. self,
  161. room_id: str,
  162. event_type: str,
  163. tok: str,
  164. expect_code: int = 200,
  165. state_key: str = "",
  166. ):
  167. """Gets some state from a room
  168. Args:
  169. room_id:
  170. event_type: The type of state event
  171. tok: The access token to use
  172. expect_code: The HTTP code to expect in the response
  173. state_key:
  174. Returns:
  175. The response body from the server
  176. Raises:
  177. AssertionError: if expect_code doesn't match the HTTP code we received
  178. """
  179. return self._read_write_state(
  180. room_id, event_type, None, tok, expect_code, state_key, method="GET"
  181. )
  182. def send_state(
  183. self,
  184. room_id: str,
  185. event_type: str,
  186. body: Dict[str, Any],
  187. tok: str,
  188. expect_code: int = 200,
  189. state_key: str = "",
  190. ):
  191. """Set some state in a room
  192. Args:
  193. room_id:
  194. event_type: The type of state event
  195. body: Body that is sent when making the request. The content of the state event.
  196. tok: The access token to use
  197. expect_code: The HTTP code to expect in the response
  198. state_key:
  199. Returns:
  200. The response body from the server
  201. Raises:
  202. AssertionError: if expect_code doesn't match the HTTP code we received
  203. """
  204. return self._read_write_state(
  205. room_id, event_type, body, tok, expect_code, state_key, method="PUT"
  206. )
  207. def upload_media(
  208. self,
  209. resource: Resource,
  210. image_data: bytes,
  211. tok: str,
  212. filename: str = "test.png",
  213. expect_code: int = 200,
  214. ) -> dict:
  215. """Upload a piece of test media to the media repo
  216. Args:
  217. resource: The resource that will handle the upload request
  218. image_data: The image data to upload
  219. tok: The user token to use during the upload
  220. filename: The filename of the media to be uploaded
  221. expect_code: The return code to expect from attempting to upload the media
  222. """
  223. image_length = len(image_data)
  224. path = "/_matrix/media/r0/upload?filename=%s" % (filename,)
  225. request, channel = make_request(
  226. self.hs.get_reactor(), "POST", path, content=image_data, access_token=tok
  227. )
  228. request.requestHeaders.addRawHeader(
  229. b"Content-Length", str(image_length).encode("UTF-8")
  230. )
  231. request.render(resource)
  232. self.hs.get_reactor().pump([100])
  233. assert channel.code == expect_code, "Expected: %d, got: %d, resp: %r" % (
  234. expect_code,
  235. int(channel.result["code"]),
  236. channel.result["body"],
  237. )
  238. return channel.json_body