utils.py 13 KB

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