utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018-2019 New Vector 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 atexit
  16. import os
  17. from typing import Any, Callable, Dict, List, Tuple, Type, TypeVar, Union, overload
  18. import attr
  19. from typing_extensions import Literal, ParamSpec
  20. from synapse.api.constants import EventTypes
  21. from synapse.api.room_versions import RoomVersions
  22. from synapse.config.homeserver import HomeServerConfig
  23. from synapse.config.server import DEFAULT_ROOM_VERSION
  24. from synapse.logging.context import current_context, set_current_context
  25. from synapse.server import HomeServer
  26. from synapse.storage.database import LoggingDatabaseConnection
  27. from synapse.storage.engines import create_engine
  28. from synapse.storage.prepare_database import prepare_database
  29. # set this to True to run the tests against postgres instead of sqlite.
  30. #
  31. # When running under postgres, we first create a base database with the name
  32. # POSTGRES_BASE_DB and update it to the current schema. Then, for each test case, we
  33. # create another unique database, using the base database as a template.
  34. USE_POSTGRES_FOR_TESTS = os.environ.get("SYNAPSE_POSTGRES", False)
  35. LEAVE_DB = os.environ.get("SYNAPSE_LEAVE_DB", False)
  36. POSTGRES_USER = os.environ.get("SYNAPSE_POSTGRES_USER", None)
  37. POSTGRES_HOST = os.environ.get("SYNAPSE_POSTGRES_HOST", None)
  38. POSTGRES_PASSWORD = os.environ.get("SYNAPSE_POSTGRES_PASSWORD", None)
  39. POSTGRES_PORT = (
  40. int(os.environ["SYNAPSE_POSTGRES_PORT"])
  41. if "SYNAPSE_POSTGRES_PORT" in os.environ
  42. else None
  43. )
  44. POSTGRES_BASE_DB = "_synapse_unit_tests_base_%s" % (os.getpid(),)
  45. # When debugging a specific test, it's occasionally useful to write the
  46. # DB to disk and query it with the sqlite CLI.
  47. SQLITE_PERSIST_DB = os.environ.get("SYNAPSE_TEST_PERSIST_SQLITE_DB") is not None
  48. # the dbname we will connect to in order to create the base database.
  49. POSTGRES_DBNAME_FOR_INITIAL_CREATE = "postgres"
  50. def setupdb() -> None:
  51. # If we're using PostgreSQL, set up the db once
  52. if USE_POSTGRES_FOR_TESTS:
  53. # create a PostgresEngine
  54. db_engine = create_engine({"name": "psycopg2", "args": {}})
  55. # connect to postgres to create the base database.
  56. db_conn = db_engine.module.connect(
  57. user=POSTGRES_USER,
  58. host=POSTGRES_HOST,
  59. port=POSTGRES_PORT,
  60. password=POSTGRES_PASSWORD,
  61. dbname=POSTGRES_DBNAME_FOR_INITIAL_CREATE,
  62. )
  63. db_engine.attempt_to_set_autocommit(db_conn, autocommit=True)
  64. cur = db_conn.cursor()
  65. cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
  66. cur.execute(
  67. "CREATE DATABASE %s ENCODING 'UTF8' LC_COLLATE='C' LC_CTYPE='C' "
  68. "template=template0;" % (POSTGRES_BASE_DB,)
  69. )
  70. cur.close()
  71. db_conn.close()
  72. # Set up in the db
  73. db_conn = db_engine.module.connect(
  74. database=POSTGRES_BASE_DB,
  75. user=POSTGRES_USER,
  76. host=POSTGRES_HOST,
  77. port=POSTGRES_PORT,
  78. password=POSTGRES_PASSWORD,
  79. )
  80. logging_conn = LoggingDatabaseConnection(db_conn, db_engine, "tests")
  81. prepare_database(logging_conn, db_engine, None)
  82. logging_conn.close()
  83. def _cleanup() -> None:
  84. db_conn = db_engine.module.connect(
  85. user=POSTGRES_USER,
  86. host=POSTGRES_HOST,
  87. port=POSTGRES_PORT,
  88. password=POSTGRES_PASSWORD,
  89. dbname=POSTGRES_DBNAME_FOR_INITIAL_CREATE,
  90. )
  91. db_engine.attempt_to_set_autocommit(db_conn, autocommit=True)
  92. cur = db_conn.cursor()
  93. cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
  94. cur.close()
  95. db_conn.close()
  96. atexit.register(_cleanup)
  97. @overload
  98. def default_config(name: str, parse: Literal[False] = ...) -> Dict[str, object]:
  99. ...
  100. @overload
  101. def default_config(name: str, parse: Literal[True]) -> HomeServerConfig:
  102. ...
  103. def default_config(
  104. name: str, parse: bool = False
  105. ) -> Union[Dict[str, object], HomeServerConfig]:
  106. """
  107. Create a reasonable test config.
  108. """
  109. config_dict = {
  110. "server_name": name,
  111. # Setting this to an empty list turns off federation sending.
  112. "federation_sender_instances": [],
  113. "media_store_path": "media",
  114. # the test signing key is just an arbitrary ed25519 key to keep the config
  115. # parser happy
  116. "signing_key": "ed25519 a_lPym qvioDNmfExFBRPgdTU+wtFYKq4JfwFRv7sYVgWvmgJg",
  117. # Disable trusted key servers, otherwise unit tests might try to actually
  118. # reach out to matrix.org.
  119. "trusted_key_servers": [],
  120. "event_cache_size": 1,
  121. "enable_registration": True,
  122. "enable_registration_captcha": False,
  123. "macaroon_secret_key": "not even a little secret",
  124. "password_providers": [],
  125. "worker_app": None,
  126. "block_non_admin_invites": False,
  127. "federation_domain_whitelist": None,
  128. "filter_timeline_limit": 5000,
  129. "user_directory_search_all_users": False,
  130. "user_consent_server_notice_content": None,
  131. "block_events_without_consent_error": None,
  132. "user_consent_at_registration": False,
  133. "user_consent_policy_name": "Privacy Policy",
  134. "media_storage_providers": [],
  135. "autocreate_auto_join_rooms": True,
  136. "auto_join_rooms": [],
  137. "limit_usage_by_mau": False,
  138. "hs_disabled": False,
  139. "hs_disabled_message": "",
  140. "max_mau_value": 50,
  141. "mau_trial_days": 0,
  142. "mau_stats_only": False,
  143. "mau_limits_reserved_threepids": [],
  144. "admin_contact": None,
  145. "rc_message": {"per_second": 10000, "burst_count": 10000},
  146. "rc_registration": {"per_second": 10000, "burst_count": 10000},
  147. "rc_login": {
  148. "address": {"per_second": 10000, "burst_count": 10000},
  149. "account": {"per_second": 10000, "burst_count": 10000},
  150. "failed_attempts": {"per_second": 10000, "burst_count": 10000},
  151. },
  152. "rc_joins": {
  153. "local": {"per_second": 10000, "burst_count": 10000},
  154. "remote": {"per_second": 10000, "burst_count": 10000},
  155. },
  156. "rc_joins_per_room": {"per_second": 10000, "burst_count": 10000},
  157. "rc_invites": {
  158. "per_room": {"per_second": 10000, "burst_count": 10000},
  159. "per_user": {"per_second": 10000, "burst_count": 10000},
  160. },
  161. "rc_3pid_validation": {"per_second": 10000, "burst_count": 10000},
  162. "saml2_enabled": False,
  163. "public_baseurl": None,
  164. "default_identity_server": None,
  165. "key_refresh_interval": 24 * 60 * 60 * 1000,
  166. "old_signing_keys": {},
  167. "tls_fingerprints": [],
  168. "use_frozen_dicts": False,
  169. # We need a sane default_room_version, otherwise attempts to create
  170. # rooms will fail.
  171. "default_room_version": DEFAULT_ROOM_VERSION,
  172. # disable user directory updates, because they get done in the
  173. # background, which upsets the test runner. Setting this to an
  174. # (obviously) fake worker name disables updating the user directory.
  175. "update_user_directory_from_worker": "does_not_exist_worker_name",
  176. "caches": {"global_factor": 1, "sync_response_cache_duration": 0},
  177. "listeners": [{"port": 0, "type": "http"}],
  178. }
  179. if parse:
  180. config = HomeServerConfig()
  181. config.parse_config_dict(config_dict, "", "")
  182. return config
  183. return config_dict
  184. def mock_getRawHeaders(headers=None): # type: ignore[no-untyped-def]
  185. headers = headers if headers is not None else {}
  186. def getRawHeaders(name, default=None): # type: ignore[no-untyped-def]
  187. # If the requested header is present, the real twisted function returns
  188. # List[str] if name is a str and List[bytes] if name is a bytes.
  189. # This mock doesn't support that behaviour.
  190. # Fortunately, none of the current callers of mock_getRawHeaders() provide a
  191. # headers dict, so we don't encounter this discrepancy in practice.
  192. return headers.get(name, default)
  193. return getRawHeaders
  194. P = ParamSpec("P")
  195. @attr.s(slots=True, auto_attribs=True)
  196. class Timer:
  197. absolute_time: float
  198. callback: Callable[[], None]
  199. expired: bool
  200. # TODO: Make this generic over a ParamSpec?
  201. @attr.s(slots=True, auto_attribs=True)
  202. class Looper:
  203. func: Callable[..., Any]
  204. interval: float # seconds
  205. last: float
  206. args: Tuple[object, ...]
  207. kwargs: Dict[str, object]
  208. class MockClock:
  209. now = 1000.0
  210. def __init__(self) -> None:
  211. # Timers in no particular order
  212. self.timers: List[Timer] = []
  213. self.loopers: List[Looper] = []
  214. def time(self) -> float:
  215. return self.now
  216. def time_msec(self) -> int:
  217. return int(self.time() * 1000)
  218. def call_later(
  219. self,
  220. delay: float,
  221. callback: Callable[P, object],
  222. *args: P.args,
  223. **kwargs: P.kwargs,
  224. ) -> Timer:
  225. ctx = current_context()
  226. def wrapped_callback() -> None:
  227. set_current_context(ctx)
  228. callback(*args, **kwargs)
  229. t = Timer(self.now + delay, wrapped_callback, False)
  230. self.timers.append(t)
  231. return t
  232. def looping_call(
  233. self,
  234. function: Callable[P, object],
  235. interval: float,
  236. *args: P.args,
  237. **kwargs: P.kwargs,
  238. ) -> None:
  239. self.loopers.append(Looper(function, interval / 1000.0, self.now, args, kwargs))
  240. def cancel_call_later(self, timer: Timer, ignore_errs: bool = False) -> None:
  241. if timer.expired:
  242. if not ignore_errs:
  243. raise Exception("Cannot cancel an expired timer")
  244. timer.expired = True
  245. self.timers = [t for t in self.timers if t != timer]
  246. # For unit testing
  247. def advance_time(self, secs: float) -> None:
  248. self.now += secs
  249. timers = self.timers
  250. self.timers = []
  251. for t in timers:
  252. if t.expired:
  253. raise Exception("Timer already expired")
  254. if self.now >= t.absolute_time:
  255. t.expired = True
  256. t.callback()
  257. else:
  258. self.timers.append(t)
  259. for looped in self.loopers:
  260. if looped.last + looped.interval < self.now:
  261. looped.func(*looped.args, **looped.kwargs)
  262. looped.last = self.now
  263. def advance_time_msec(self, ms: float) -> None:
  264. self.advance_time(ms / 1000.0)
  265. async def create_room(hs: HomeServer, room_id: str, creator_id: str) -> None:
  266. """Creates and persist a creation event for the given room"""
  267. persistence_store = hs.get_storage_controllers().persistence
  268. assert persistence_store is not None
  269. store = hs.get_datastores().main
  270. event_builder_factory = hs.get_event_builder_factory()
  271. event_creation_handler = hs.get_event_creation_handler()
  272. await store.store_room(
  273. room_id=room_id,
  274. room_creator_user_id=creator_id,
  275. is_public=False,
  276. room_version=RoomVersions.V1,
  277. )
  278. builder = event_builder_factory.for_room_version(
  279. RoomVersions.V1,
  280. {
  281. "type": EventTypes.Create,
  282. "state_key": "",
  283. "sender": creator_id,
  284. "room_id": room_id,
  285. "content": {},
  286. },
  287. )
  288. event, unpersisted_context = await event_creation_handler.create_new_client_event(
  289. builder
  290. )
  291. context = await unpersisted_context.persist(event)
  292. await persistence_store.persist_event(event, context)
  293. T = TypeVar("T")
  294. def checked_cast(type: Type[T], x: object) -> T:
  295. """A version of typing.cast that is checked at runtime.
  296. We have our own function for this for two reasons:
  297. 1. typing.cast itself is deliberately a no-op at runtime, see
  298. https://docs.python.org/3/library/typing.html#typing.cast
  299. 2. To help workaround a mypy-zope bug https://github.com/Shoobx/mypy-zope/issues/91
  300. where mypy would erroneously consider `isinstance(x, type)` to be false in all
  301. circumstances.
  302. For this to make sense, `T` needs to be something that `isinstance` can check; see
  303. https://docs.python.org/3/library/functions.html?highlight=isinstance#isinstance
  304. https://docs.python.org/3/glossary.html#term-abstract-base-class
  305. https://docs.python.org/3/library/typing.html#typing.runtime_checkable
  306. for more details.
  307. """
  308. assert isinstance(x, type)
  309. return x