event_injector.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015 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. from tests import unittest
  16. from twisted.internet import defer
  17. from synapse.api.constants import EventTypes, Membership
  18. from synapse.types import UserID, RoomID
  19. from tests.utils import setup_test_homeserver
  20. from mock import Mock
  21. class EventInjector:
  22. def __init__(self, hs):
  23. self.hs = hs
  24. self.store = hs.get_datastore()
  25. self.message_handler = hs.get_handlers().message_handler
  26. self.event_builder_factory = hs.get_event_builder_factory()
  27. @defer.inlineCallbacks
  28. def create_room(self, room):
  29. builder = self.event_builder_factory.new({
  30. "type": EventTypes.Create,
  31. "room_id": room.to_string(),
  32. "content": {},
  33. })
  34. event, context = yield self.message_handler._create_new_client_event(
  35. builder
  36. )
  37. yield self.store.persist_event(event, context)
  38. @defer.inlineCallbacks
  39. def inject_room_member(self, room, user, membership):
  40. builder = self.event_builder_factory.new({
  41. "type": EventTypes.Member,
  42. "sender": user.to_string(),
  43. "state_key": user.to_string(),
  44. "room_id": room.to_string(),
  45. "content": {"membership": membership},
  46. })
  47. event, context = yield self.message_handler._create_new_client_event(
  48. builder
  49. )
  50. yield self.store.persist_event(event, context)
  51. defer.returnValue(event)
  52. @defer.inlineCallbacks
  53. def inject_message(self, room, user, body):
  54. builder = self.event_builder_factory.new({
  55. "type": EventTypes.Message,
  56. "sender": user.to_string(),
  57. "state_key": user.to_string(),
  58. "room_id": room.to_string(),
  59. "content": {"body": body, "msgtype": u"message"},
  60. })
  61. event, context = yield self.message_handler._create_new_client_event(
  62. builder
  63. )
  64. yield self.store.persist_event(event, context)