utils.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  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. import time
  17. import attr
  18. from twisted.internet import defer
  19. from synapse.api.constants import Membership
  20. from tests import unittest
  21. from tests.server import make_request, render
  22. class RestTestCase(unittest.TestCase):
  23. """Contains extra helper functions to quickly and clearly perform a given
  24. REST action, which isn't the focus of the test.
  25. This subclass assumes there are mock_resource and auth_user_id attributes.
  26. """
  27. def __init__(self, *args, **kwargs):
  28. super(RestTestCase, self).__init__(*args, **kwargs)
  29. self.mock_resource = None
  30. self.auth_user_id = None
  31. @defer.inlineCallbacks
  32. def create_room_as(self, room_creator, is_public=True, tok=None):
  33. temp_id = self.auth_user_id
  34. self.auth_user_id = room_creator
  35. path = "/createRoom"
  36. content = "{}"
  37. if not is_public:
  38. content = '{"visibility":"private"}'
  39. if tok:
  40. path = path + "?access_token=%s" % tok
  41. (code, response) = yield self.mock_resource.trigger("POST", path, content)
  42. self.assertEquals(200, code, msg=str(response))
  43. self.auth_user_id = temp_id
  44. defer.returnValue(response["room_id"])
  45. @defer.inlineCallbacks
  46. def invite(self, room=None, src=None, targ=None, expect_code=200, tok=None):
  47. yield self.change_membership(
  48. room=room,
  49. src=src,
  50. targ=targ,
  51. tok=tok,
  52. membership=Membership.INVITE,
  53. expect_code=expect_code,
  54. )
  55. @defer.inlineCallbacks
  56. def join(self, room=None, user=None, expect_code=200, tok=None):
  57. yield self.change_membership(
  58. room=room,
  59. src=user,
  60. targ=user,
  61. tok=tok,
  62. membership=Membership.JOIN,
  63. expect_code=expect_code,
  64. )
  65. @defer.inlineCallbacks
  66. def leave(self, room=None, user=None, expect_code=200, tok=None):
  67. yield self.change_membership(
  68. room=room,
  69. src=user,
  70. targ=user,
  71. tok=tok,
  72. membership=Membership.LEAVE,
  73. expect_code=expect_code,
  74. )
  75. @defer.inlineCallbacks
  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 = "/rooms/%s/state/m.room.member/%s" % (room, targ)
  80. if tok:
  81. path = path + "?access_token=%s" % tok
  82. data = {"membership": membership}
  83. (code, response) = yield self.mock_resource.trigger(
  84. "PUT", path, json.dumps(data)
  85. )
  86. self.assertEquals(
  87. expect_code,
  88. code,
  89. msg="Expected: %d, got: %d, resp: %r" % (expect_code, code, response),
  90. )
  91. self.auth_user_id = temp_id
  92. @defer.inlineCallbacks
  93. def register(self, user_id):
  94. (code, response) = yield self.mock_resource.trigger(
  95. "POST",
  96. "/register",
  97. json.dumps(
  98. {"user": user_id, "password": "test", "type": "m.login.password"}
  99. ),
  100. )
  101. self.assertEquals(200, code, msg=response)
  102. defer.returnValue(response)
  103. @defer.inlineCallbacks
  104. def send(self, room_id, body=None, txn_id=None, tok=None, expect_code=200):
  105. if txn_id is None:
  106. txn_id = "m%s" % (str(time.time()))
  107. if body is None:
  108. body = "body_text_here"
  109. path = "/rooms/%s/send/m.room.message/%s" % (room_id, txn_id)
  110. content = '{"msgtype":"m.text","body":"%s"}' % body
  111. if tok:
  112. path = path + "?access_token=%s" % tok
  113. (code, response) = yield self.mock_resource.trigger("PUT", path, content)
  114. self.assertEquals(expect_code, code, msg=str(response))
  115. def assert_dict(self, required, actual):
  116. """Does a partial assert of a dict.
  117. Args:
  118. required (dict): The keys and value which MUST be in 'actual'.
  119. actual (dict): The test result. Extra keys will not be checked.
  120. """
  121. for key in required:
  122. self.assertEquals(
  123. required[key], actual[key], msg="%s mismatch. %s" % (key, actual)
  124. )
  125. @attr.s
  126. class RestHelper(object):
  127. """Contains extra helper functions to quickly and clearly perform a given
  128. REST action, which isn't the focus of the test.
  129. """
  130. hs = attr.ib()
  131. resource = attr.ib()
  132. auth_user_id = attr.ib()
  133. def create_room_as(self, room_creator, is_public=True, tok=None):
  134. temp_id = self.auth_user_id
  135. self.auth_user_id = room_creator
  136. path = "/_matrix/client/r0/createRoom"
  137. content = {}
  138. if not is_public:
  139. content["visibility"] = "private"
  140. if tok:
  141. path = path + "?access_token=%s" % tok
  142. request, channel = make_request(
  143. "POST", path, json.dumps(content).encode('utf8')
  144. )
  145. render(request, self.resource, self.hs.get_reactor())
  146. assert channel.result["code"] == b"200", channel.result
  147. self.auth_user_id = temp_id
  148. return channel.json_body["room_id"]
  149. def invite(self, room=None, src=None, targ=None, expect_code=200, tok=None):
  150. self.change_membership(
  151. room=room,
  152. src=src,
  153. targ=targ,
  154. tok=tok,
  155. membership=Membership.INVITE,
  156. expect_code=expect_code,
  157. )
  158. def join(self, room=None, user=None, expect_code=200, tok=None):
  159. self.change_membership(
  160. room=room,
  161. src=user,
  162. targ=user,
  163. tok=tok,
  164. membership=Membership.JOIN,
  165. expect_code=expect_code,
  166. )
  167. def leave(self, room=None, user=None, expect_code=200, tok=None):
  168. self.change_membership(
  169. room=room,
  170. src=user,
  171. targ=user,
  172. tok=tok,
  173. membership=Membership.LEAVE,
  174. expect_code=expect_code,
  175. )
  176. def change_membership(self, room, src, targ, membership, tok=None, expect_code=200):
  177. temp_id = self.auth_user_id
  178. self.auth_user_id = src
  179. path = "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % (room, targ)
  180. if tok:
  181. path = path + "?access_token=%s" % tok
  182. data = {"membership": membership}
  183. request, channel = make_request("PUT", path, json.dumps(data).encode('utf8'))
  184. render(request, self.resource, self.hs.get_reactor())
  185. assert int(channel.result["code"]) == expect_code, (
  186. "Expected: %d, got: %d, resp: %r"
  187. % (expect_code, int(channel.result["code"]), channel.result["body"])
  188. )
  189. self.auth_user_id = temp_id
  190. @defer.inlineCallbacks
  191. def register(self, user_id):
  192. (code, response) = yield self.mock_resource.trigger(
  193. "POST",
  194. "/_matrix/client/r0/register",
  195. json.dumps(
  196. {"user": user_id, "password": "test", "type": "m.login.password"}
  197. ),
  198. )
  199. self.assertEquals(200, code)
  200. defer.returnValue(response)
  201. def send(self, room_id, body=None, txn_id=None, tok=None, expect_code=200):
  202. if txn_id is None:
  203. txn_id = "m%s" % (str(time.time()))
  204. if body is None:
  205. body = "body_text_here"
  206. path = "/_matrix/client/r0/rooms/%s/send/m.room.message/%s" % (room_id, txn_id)
  207. content = {"msgtype": "m.text", "body": body}
  208. if tok:
  209. path = path + "?access_token=%s" % tok
  210. request, channel = make_request("PUT", path, json.dumps(content).encode('utf8'))
  211. render(request, self.resource, self.hs.get_reactor())
  212. assert int(channel.result["code"]) == expect_code, (
  213. "Expected: %d, got: %d, resp: %r"
  214. % (expect_code, int(channel.result["code"]), channel.result["body"])
  215. )
  216. return channel.json_body