test_utils.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the 'License');
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an 'AS IS' BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import unittest as stdlib_unittest
  15. from typing import Any, List, Mapping, Optional
  16. import attr
  17. from parameterized import parameterized
  18. from synapse.api.constants import EventContentFields
  19. from synapse.api.room_versions import RoomVersions
  20. from synapse.events import EventBase, make_event_from_dict
  21. from synapse.events.utils import (
  22. PowerLevelsContent,
  23. SerializeEventConfig,
  24. _split_field,
  25. copy_and_fixup_power_levels_contents,
  26. maybe_upsert_event_field,
  27. prune_event,
  28. serialize_event,
  29. )
  30. from synapse.types import JsonDict
  31. from synapse.util.frozenutils import freeze
  32. def MockEvent(**kwargs: Any) -> EventBase:
  33. if "event_id" not in kwargs:
  34. kwargs["event_id"] = "fake_event_id"
  35. if "type" not in kwargs:
  36. kwargs["type"] = "fake_type"
  37. if "content" not in kwargs:
  38. kwargs["content"] = {}
  39. return make_event_from_dict(kwargs)
  40. class TestMaybeUpsertEventField(stdlib_unittest.TestCase):
  41. def test_update_okay(self) -> None:
  42. event = make_event_from_dict({"event_id": "$1234"})
  43. success = maybe_upsert_event_field(event, event.unsigned, "key", "value")
  44. self.assertTrue(success)
  45. self.assertEqual(event.unsigned["key"], "value")
  46. def test_update_not_okay(self) -> None:
  47. event = make_event_from_dict({"event_id": "$1234"})
  48. LARGE_STRING = "a" * 100_000
  49. success = maybe_upsert_event_field(event, event.unsigned, "key", LARGE_STRING)
  50. self.assertFalse(success)
  51. self.assertNotIn("key", event.unsigned)
  52. def test_update_not_okay_leaves_original_value(self) -> None:
  53. event = make_event_from_dict(
  54. {"event_id": "$1234", "unsigned": {"key": "value"}}
  55. )
  56. LARGE_STRING = "a" * 100_000
  57. success = maybe_upsert_event_field(event, event.unsigned, "key", LARGE_STRING)
  58. self.assertFalse(success)
  59. self.assertEqual(event.unsigned["key"], "value")
  60. class PruneEventTestCase(stdlib_unittest.TestCase):
  61. def run_test(self, evdict: JsonDict, matchdict: JsonDict, **kwargs: Any) -> None:
  62. """
  63. Asserts that a new event constructed with `evdict` will look like
  64. `matchdict` when it is redacted.
  65. Args:
  66. evdict: The dictionary to build the event from.
  67. matchdict: The expected resulting dictionary.
  68. kwargs: Additional keyword arguments used to create the event.
  69. """
  70. self.assertEqual(
  71. prune_event(make_event_from_dict(evdict, **kwargs)).get_dict(), matchdict
  72. )
  73. def test_minimal(self) -> None:
  74. self.run_test(
  75. {"type": "A", "event_id": "$test:domain"},
  76. {
  77. "type": "A",
  78. "event_id": "$test:domain",
  79. "content": {},
  80. "signatures": {},
  81. "unsigned": {},
  82. },
  83. )
  84. def test_basic_keys(self) -> None:
  85. """Ensure that the keys that should be untouched are kept."""
  86. # Note that some of the values below don't really make sense, but the
  87. # pruning of events doesn't worry about the values of any fields (with
  88. # the exception of the content field).
  89. self.run_test(
  90. {
  91. "event_id": "$3:domain",
  92. "type": "A",
  93. "room_id": "!1:domain",
  94. "sender": "@2:domain",
  95. "state_key": "B",
  96. "content": {"other_key": "foo"},
  97. "hashes": "hashes",
  98. "signatures": {"domain": {"algo:1": "sigs"}},
  99. "depth": 4,
  100. "prev_events": "prev_events",
  101. "prev_state": "prev_state",
  102. "auth_events": "auth_events",
  103. "origin": "domain",
  104. "origin_server_ts": 1234,
  105. "membership": "join",
  106. # Also include a key that should be removed.
  107. "other_key": "foo",
  108. },
  109. {
  110. "event_id": "$3:domain",
  111. "type": "A",
  112. "room_id": "!1:domain",
  113. "sender": "@2:domain",
  114. "state_key": "B",
  115. "hashes": "hashes",
  116. "depth": 4,
  117. "prev_events": "prev_events",
  118. "prev_state": "prev_state",
  119. "auth_events": "auth_events",
  120. "origin": "domain",
  121. "origin_server_ts": 1234,
  122. "membership": "join",
  123. "content": {},
  124. "signatures": {"domain": {"algo:1": "sigs"}},
  125. "unsigned": {},
  126. },
  127. )
  128. # As of MSC2176 we now redact the membership and prev_states keys.
  129. self.run_test(
  130. {"type": "A", "prev_state": "prev_state", "membership": "join"},
  131. {"type": "A", "content": {}, "signatures": {}, "unsigned": {}},
  132. room_version=RoomVersions.MSC2176,
  133. )
  134. # As of MSC3989 we now redact the origin key.
  135. self.run_test(
  136. {"type": "A", "origin": "example.com"},
  137. {"type": "A", "content": {}, "signatures": {}, "unsigned": {}},
  138. room_version=RoomVersions.MSC3989,
  139. )
  140. def test_unsigned(self) -> None:
  141. """Ensure that unsigned properties get stripped (except age_ts and replaces_state)."""
  142. self.run_test(
  143. {
  144. "type": "B",
  145. "event_id": "$test:domain",
  146. "unsigned": {
  147. "age_ts": 20,
  148. "replaces_state": "$test2:domain",
  149. "other_key": "foo",
  150. },
  151. },
  152. {
  153. "type": "B",
  154. "event_id": "$test:domain",
  155. "content": {},
  156. "signatures": {},
  157. "unsigned": {"age_ts": 20, "replaces_state": "$test2:domain"},
  158. },
  159. )
  160. def test_content(self) -> None:
  161. """The content dictionary should be stripped in most cases."""
  162. self.run_test(
  163. {"type": "C", "event_id": "$test:domain", "content": {"things": "here"}},
  164. {
  165. "type": "C",
  166. "event_id": "$test:domain",
  167. "content": {},
  168. "signatures": {},
  169. "unsigned": {},
  170. },
  171. )
  172. # Some events keep a single content key/value.
  173. EVENT_KEEP_CONTENT_KEYS = [
  174. ("member", "membership", "join"),
  175. ("join_rules", "join_rule", "invite"),
  176. ("history_visibility", "history_visibility", "shared"),
  177. ]
  178. for event_type, key, value in EVENT_KEEP_CONTENT_KEYS:
  179. self.run_test(
  180. {
  181. "type": "m.room." + event_type,
  182. "event_id": "$test:domain",
  183. "content": {key: value, "other_key": "foo"},
  184. },
  185. {
  186. "type": "m.room." + event_type,
  187. "event_id": "$test:domain",
  188. "content": {key: value},
  189. "signatures": {},
  190. "unsigned": {},
  191. },
  192. )
  193. def test_create(self) -> None:
  194. """Create events are partially redacted until MSC2176."""
  195. self.run_test(
  196. {
  197. "type": "m.room.create",
  198. "event_id": "$test:domain",
  199. "content": {"creator": "@2:domain", "other_key": "foo"},
  200. },
  201. {
  202. "type": "m.room.create",
  203. "event_id": "$test:domain",
  204. "content": {"creator": "@2:domain"},
  205. "signatures": {},
  206. "unsigned": {},
  207. },
  208. )
  209. # After MSC2176, create events get nothing redacted.
  210. self.run_test(
  211. {"type": "m.room.create", "content": {"not_a_real_key": True}},
  212. {
  213. "type": "m.room.create",
  214. "content": {"not_a_real_key": True},
  215. "signatures": {},
  216. "unsigned": {},
  217. },
  218. room_version=RoomVersions.MSC2176,
  219. )
  220. def test_power_levels(self) -> None:
  221. """Power level events keep a variety of content keys."""
  222. self.run_test(
  223. {
  224. "type": "m.room.power_levels",
  225. "event_id": "$test:domain",
  226. "content": {
  227. "ban": 1,
  228. "events": {"m.room.name": 100},
  229. "events_default": 2,
  230. "invite": 3,
  231. "kick": 4,
  232. "redact": 5,
  233. "state_default": 6,
  234. "users": {"@admin:domain": 100},
  235. "users_default": 7,
  236. "other_key": 8,
  237. },
  238. },
  239. {
  240. "type": "m.room.power_levels",
  241. "event_id": "$test:domain",
  242. "content": {
  243. "ban": 1,
  244. "events": {"m.room.name": 100},
  245. "events_default": 2,
  246. # Note that invite is not here.
  247. "kick": 4,
  248. "redact": 5,
  249. "state_default": 6,
  250. "users": {"@admin:domain": 100},
  251. "users_default": 7,
  252. },
  253. "signatures": {},
  254. "unsigned": {},
  255. },
  256. )
  257. # After MSC2176, power levels events keep the invite key.
  258. self.run_test(
  259. {"type": "m.room.power_levels", "content": {"invite": 75}},
  260. {
  261. "type": "m.room.power_levels",
  262. "content": {"invite": 75},
  263. "signatures": {},
  264. "unsigned": {},
  265. },
  266. room_version=RoomVersions.MSC2176,
  267. )
  268. def test_alias_event(self) -> None:
  269. """Alias events have special behavior up through room version 6."""
  270. self.run_test(
  271. {
  272. "type": "m.room.aliases",
  273. "event_id": "$test:domain",
  274. "content": {"aliases": ["test"]},
  275. },
  276. {
  277. "type": "m.room.aliases",
  278. "event_id": "$test:domain",
  279. "content": {"aliases": ["test"]},
  280. "signatures": {},
  281. "unsigned": {},
  282. },
  283. )
  284. # After MSC2432, alias events have no special behavior.
  285. self.run_test(
  286. {"type": "m.room.aliases", "content": {"aliases": ["test"]}},
  287. {
  288. "type": "m.room.aliases",
  289. "content": {},
  290. "signatures": {},
  291. "unsigned": {},
  292. },
  293. room_version=RoomVersions.V6,
  294. )
  295. def test_redacts(self) -> None:
  296. """Redaction events have no special behaviour until MSC2174/MSC2176."""
  297. self.run_test(
  298. {
  299. "type": "m.room.redaction",
  300. "content": {"redacts": "$test2:domain"},
  301. "redacts": "$test2:domain",
  302. },
  303. {
  304. "type": "m.room.redaction",
  305. "content": {},
  306. "signatures": {},
  307. "unsigned": {},
  308. },
  309. room_version=RoomVersions.V6,
  310. )
  311. # After MSC2174, redaction events keep the redacts content key.
  312. self.run_test(
  313. {
  314. "type": "m.room.redaction",
  315. "content": {"redacts": "$test2:domain"},
  316. "redacts": "$test2:domain",
  317. },
  318. {
  319. "type": "m.room.redaction",
  320. "content": {"redacts": "$test2:domain"},
  321. "signatures": {},
  322. "unsigned": {},
  323. },
  324. room_version=RoomVersions.MSC2176,
  325. )
  326. def test_join_rules(self) -> None:
  327. """Join rules events have changed behavior starting with MSC3083."""
  328. self.run_test(
  329. {
  330. "type": "m.room.join_rules",
  331. "event_id": "$test:domain",
  332. "content": {
  333. "join_rule": "invite",
  334. "allow": [],
  335. "other_key": "stripped",
  336. },
  337. },
  338. {
  339. "type": "m.room.join_rules",
  340. "event_id": "$test:domain",
  341. "content": {"join_rule": "invite"},
  342. "signatures": {},
  343. "unsigned": {},
  344. },
  345. )
  346. # After MSC3083, the allow key is protected from redaction.
  347. self.run_test(
  348. {
  349. "type": "m.room.join_rules",
  350. "content": {
  351. "join_rule": "invite",
  352. "allow": [],
  353. "other_key": "stripped",
  354. },
  355. },
  356. {
  357. "type": "m.room.join_rules",
  358. "content": {
  359. "join_rule": "invite",
  360. "allow": [],
  361. },
  362. "signatures": {},
  363. "unsigned": {},
  364. },
  365. room_version=RoomVersions.V8,
  366. )
  367. def test_member(self) -> None:
  368. """Member events have changed behavior in MSC3375 and MSC3821."""
  369. self.run_test(
  370. {
  371. "type": "m.room.member",
  372. "event_id": "$test:domain",
  373. "content": {
  374. "membership": "join",
  375. EventContentFields.AUTHORISING_USER: "@user:domain",
  376. "other_key": "stripped",
  377. },
  378. },
  379. {
  380. "type": "m.room.member",
  381. "event_id": "$test:domain",
  382. "content": {"membership": "join"},
  383. "signatures": {},
  384. "unsigned": {},
  385. },
  386. )
  387. # After MSC3375, the join_authorised_via_users_server key is protected
  388. # from redaction.
  389. self.run_test(
  390. {
  391. "type": "m.room.member",
  392. "content": {
  393. "membership": "join",
  394. EventContentFields.AUTHORISING_USER: "@user:domain",
  395. "other_key": "stripped",
  396. },
  397. },
  398. {
  399. "type": "m.room.member",
  400. "content": {
  401. "membership": "join",
  402. EventContentFields.AUTHORISING_USER: "@user:domain",
  403. },
  404. "signatures": {},
  405. "unsigned": {},
  406. },
  407. room_version=RoomVersions.V9,
  408. )
  409. # After MSC3821, the signed key under third_party_invite is protected
  410. # from redaction.
  411. THIRD_PARTY_INVITE = {
  412. "display_name": "alice",
  413. "signed": {
  414. "mxid": "@alice:example.org",
  415. "signatures": {
  416. "magic.forest": {
  417. "ed25519:3": "fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg"
  418. }
  419. },
  420. "token": "abc123",
  421. },
  422. }
  423. self.run_test(
  424. {
  425. "type": "m.room.member",
  426. "content": {
  427. "membership": "invite",
  428. "third_party_invite": THIRD_PARTY_INVITE,
  429. "other_key": "stripped",
  430. },
  431. },
  432. {
  433. "type": "m.room.member",
  434. "content": {
  435. "membership": "invite",
  436. "third_party_invite": {"signed": THIRD_PARTY_INVITE["signed"]},
  437. },
  438. "signatures": {},
  439. "unsigned": {},
  440. },
  441. room_version=RoomVersions.MSC3821,
  442. )
  443. # Ensure this doesn't break if an invalid field is sent.
  444. self.run_test(
  445. {
  446. "type": "m.room.member",
  447. "content": {
  448. "membership": "invite",
  449. "third_party_invite": {},
  450. "other_key": "stripped",
  451. },
  452. },
  453. {
  454. "type": "m.room.member",
  455. "content": {"membership": "invite", "third_party_invite": {}},
  456. "signatures": {},
  457. "unsigned": {},
  458. },
  459. room_version=RoomVersions.MSC3821,
  460. )
  461. self.run_test(
  462. {
  463. "type": "m.room.member",
  464. "content": {
  465. "membership": "invite",
  466. "third_party_invite": "stripped",
  467. "other_key": "stripped",
  468. },
  469. },
  470. {
  471. "type": "m.room.member",
  472. "content": {"membership": "invite"},
  473. "signatures": {},
  474. "unsigned": {},
  475. },
  476. room_version=RoomVersions.MSC3821,
  477. )
  478. def test_relations(self) -> None:
  479. """Event relations get redacted until MSC3389."""
  480. # Normally the m._relates_to field is redacted.
  481. self.run_test(
  482. {
  483. "type": "m.room.message",
  484. "content": {
  485. "body": "foo",
  486. "m.relates_to": {
  487. "rel_type": "rel_type",
  488. "event_id": "$parent:domain",
  489. "other": "stripped",
  490. },
  491. },
  492. },
  493. {
  494. "type": "m.room.message",
  495. "content": {},
  496. "signatures": {},
  497. "unsigned": {},
  498. },
  499. room_version=RoomVersions.V10,
  500. )
  501. # Create a new room version.
  502. msc3389_room_ver = attr.evolve(
  503. RoomVersions.V10, msc3389_relation_redactions=True
  504. )
  505. self.run_test(
  506. {
  507. "type": "m.room.message",
  508. "content": {
  509. "body": "foo",
  510. "m.relates_to": {
  511. "rel_type": "rel_type",
  512. "event_id": "$parent:domain",
  513. "other": "stripped",
  514. },
  515. },
  516. },
  517. {
  518. "type": "m.room.message",
  519. "content": {
  520. "m.relates_to": {
  521. "rel_type": "rel_type",
  522. "event_id": "$parent:domain",
  523. },
  524. },
  525. "signatures": {},
  526. "unsigned": {},
  527. },
  528. room_version=msc3389_room_ver,
  529. )
  530. # If the field is not an object, redact it.
  531. self.run_test(
  532. {
  533. "type": "m.room.message",
  534. "content": {
  535. "body": "foo",
  536. "m.relates_to": "stripped",
  537. },
  538. },
  539. {
  540. "type": "m.room.message",
  541. "content": {},
  542. "signatures": {},
  543. "unsigned": {},
  544. },
  545. room_version=msc3389_room_ver,
  546. )
  547. # If the m.relates_to property would be empty, redact it.
  548. self.run_test(
  549. {
  550. "type": "m.room.message",
  551. "content": {"body": "foo", "m.relates_to": {"foo": "stripped"}},
  552. },
  553. {
  554. "type": "m.room.message",
  555. "content": {},
  556. "signatures": {},
  557. "unsigned": {},
  558. },
  559. room_version=msc3389_room_ver,
  560. )
  561. class SerializeEventTestCase(stdlib_unittest.TestCase):
  562. def serialize(self, ev: EventBase, fields: Optional[List[str]]) -> JsonDict:
  563. return serialize_event(
  564. ev, 1479807801915, config=SerializeEventConfig(only_event_fields=fields)
  565. )
  566. def test_event_fields_works_with_keys(self) -> None:
  567. self.assertEqual(
  568. self.serialize(
  569. MockEvent(sender="@alice:localhost", room_id="!foo:bar"), ["room_id"]
  570. ),
  571. {"room_id": "!foo:bar"},
  572. )
  573. def test_event_fields_works_with_nested_keys(self) -> None:
  574. self.assertEqual(
  575. self.serialize(
  576. MockEvent(
  577. sender="@alice:localhost",
  578. room_id="!foo:bar",
  579. content={"body": "A message"},
  580. ),
  581. ["content.body"],
  582. ),
  583. {"content": {"body": "A message"}},
  584. )
  585. def test_event_fields_works_with_dot_keys(self) -> None:
  586. self.assertEqual(
  587. self.serialize(
  588. MockEvent(
  589. sender="@alice:localhost",
  590. room_id="!foo:bar",
  591. content={"key.with.dots": {}},
  592. ),
  593. [r"content.key\.with\.dots"],
  594. ),
  595. {"content": {"key.with.dots": {}}},
  596. )
  597. def test_event_fields_works_with_nested_dot_keys(self) -> None:
  598. self.assertEqual(
  599. self.serialize(
  600. MockEvent(
  601. sender="@alice:localhost",
  602. room_id="!foo:bar",
  603. content={
  604. "not_me": 1,
  605. "nested.dot.key": {"leaf.key": 42, "not_me_either": 1},
  606. },
  607. ),
  608. [r"content.nested\.dot\.key.leaf\.key"],
  609. ),
  610. {"content": {"nested.dot.key": {"leaf.key": 42}}},
  611. )
  612. def test_event_fields_nops_with_unknown_keys(self) -> None:
  613. self.assertEqual(
  614. self.serialize(
  615. MockEvent(
  616. sender="@alice:localhost",
  617. room_id="!foo:bar",
  618. content={"foo": "bar"},
  619. ),
  620. ["content.foo", "content.notexists"],
  621. ),
  622. {"content": {"foo": "bar"}},
  623. )
  624. def test_event_fields_nops_with_non_dict_keys(self) -> None:
  625. self.assertEqual(
  626. self.serialize(
  627. MockEvent(
  628. sender="@alice:localhost",
  629. room_id="!foo:bar",
  630. content={"foo": ["I", "am", "an", "array"]},
  631. ),
  632. ["content.foo.am"],
  633. ),
  634. {},
  635. )
  636. def test_event_fields_nops_with_array_keys(self) -> None:
  637. self.assertEqual(
  638. self.serialize(
  639. MockEvent(
  640. sender="@alice:localhost",
  641. room_id="!foo:bar",
  642. content={"foo": ["I", "am", "an", "array"]},
  643. ),
  644. ["content.foo.1"],
  645. ),
  646. {},
  647. )
  648. def test_event_fields_all_fields_if_empty(self) -> None:
  649. self.assertEqual(
  650. self.serialize(
  651. MockEvent(
  652. type="foo",
  653. event_id="test",
  654. room_id="!foo:bar",
  655. content={"foo": "bar"},
  656. ),
  657. [],
  658. ),
  659. {
  660. "type": "foo",
  661. "event_id": "test",
  662. "room_id": "!foo:bar",
  663. "content": {"foo": "bar"},
  664. "unsigned": {},
  665. },
  666. )
  667. def test_event_fields_fail_if_fields_not_str(self) -> None:
  668. with self.assertRaises(TypeError):
  669. self.serialize(
  670. MockEvent(room_id="!foo:bar", content={"foo": "bar"}), ["room_id", 4] # type: ignore[list-item]
  671. )
  672. class CopyPowerLevelsContentTestCase(stdlib_unittest.TestCase):
  673. def setUp(self) -> None:
  674. self.test_content: PowerLevelsContent = {
  675. "ban": 50,
  676. "events": {"m.room.name": 100, "m.room.power_levels": 100},
  677. "events_default": 0,
  678. "invite": 50,
  679. "kick": 50,
  680. "notifications": {"room": 20},
  681. "redact": 50,
  682. "state_default": 50,
  683. "users": {"@example:localhost": 100},
  684. "users_default": 0,
  685. }
  686. def _test(self, input: PowerLevelsContent) -> None:
  687. a = copy_and_fixup_power_levels_contents(input)
  688. self.assertEqual(a["ban"], 50)
  689. assert isinstance(a["events"], Mapping)
  690. self.assertEqual(a["events"]["m.room.name"], 100)
  691. # make sure that changing the copy changes the copy and not the orig
  692. a["ban"] = 10
  693. a["events"]["m.room.power_levels"] = 20
  694. self.assertEqual(input["ban"], 50)
  695. assert isinstance(input["events"], Mapping)
  696. self.assertEqual(input["events"]["m.room.power_levels"], 100)
  697. def test_unfrozen(self) -> None:
  698. self._test(self.test_content)
  699. def test_frozen(self) -> None:
  700. input = freeze(self.test_content)
  701. self._test(input)
  702. def test_stringy_integers(self) -> None:
  703. """String representations of decimal integers are converted to integers."""
  704. input: PowerLevelsContent = {
  705. "a": "100",
  706. "b": {
  707. "foo": 99,
  708. "bar": "-98",
  709. },
  710. "d": "0999",
  711. }
  712. output = copy_and_fixup_power_levels_contents(input)
  713. expected_output = {
  714. "a": 100,
  715. "b": {
  716. "foo": 99,
  717. "bar": -98,
  718. },
  719. "d": 999,
  720. }
  721. self.assertEqual(output, expected_output)
  722. def test_strings_that_dont_represent_decimal_integers(self) -> None:
  723. """Should raise when given inputs `s` for which `int(s, base=10)` raises."""
  724. for invalid_string in ["0x123", "123.0", "123.45", "hello", "0b1", "0o777"]:
  725. with self.assertRaises(TypeError):
  726. copy_and_fixup_power_levels_contents({"a": invalid_string})
  727. def test_invalid_types_raise_type_error(self) -> None:
  728. with self.assertRaises(TypeError):
  729. copy_and_fixup_power_levels_contents({"a": ["hello", "grandma"]}) # type: ignore[dict-item]
  730. copy_and_fixup_power_levels_contents({"a": None}) # type: ignore[dict-item]
  731. def test_invalid_nesting_raises_type_error(self) -> None:
  732. with self.assertRaises(TypeError):
  733. copy_and_fixup_power_levels_contents({"a": {"b": {"c": 1}}}) # type: ignore[dict-item]
  734. class SplitFieldTestCase(stdlib_unittest.TestCase):
  735. @parameterized.expand(
  736. [
  737. # A field with no dots.
  738. ["m", ["m"]],
  739. # Simple dotted fields.
  740. ["m.foo", ["m", "foo"]],
  741. ["m.foo.bar", ["m", "foo", "bar"]],
  742. # Backslash is used as an escape character.
  743. [r"m\.foo", ["m.foo"]],
  744. [r"m\\.foo", ["m\\", "foo"]],
  745. [r"m\\\.foo", [r"m\.foo"]],
  746. [r"m\\\\.foo", ["m\\\\", "foo"]],
  747. [r"m\foo", [r"m\foo"]],
  748. [r"m\\foo", [r"m\foo"]],
  749. [r"m\\\foo", [r"m\\foo"]],
  750. [r"m\\\\foo", [r"m\\foo"]],
  751. # Ensure that escapes at the end don't cause issues.
  752. ["m.foo\\", ["m", "foo\\"]],
  753. ["m.foo\\", ["m", "foo\\"]],
  754. [r"m.foo\.", ["m", "foo."]],
  755. [r"m.foo\\.", ["m", "foo\\", ""]],
  756. [r"m.foo\\\.", ["m", r"foo\."]],
  757. # Empty parts (corresponding to properties which are an empty string) are allowed.
  758. [".m", ["", "m"]],
  759. ["..m", ["", "", "m"]],
  760. ["m.", ["m", ""]],
  761. ["m..", ["m", "", ""]],
  762. ["m..foo", ["m", "", "foo"]],
  763. # Invalid escape sequences.
  764. [r"\m", [r"\m"]],
  765. ]
  766. )
  767. def test_split_field(self, input: str, expected: str) -> None:
  768. self.assertEqual(_split_field(input), expected)