Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit f0cae26

Browse files
authored
Add a docstring & tests for _flatten_dict. (#14981)
1 parent 52700a0 commit f0cae26

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

changelog.d/14981.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add tests for `_flatten_dict`.

synapse/push/bulk_push_rule_evaluator.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,29 @@ def _flatten_dict(
473473
prefix: Optional[List[str]] = None,
474474
result: Optional[Dict[str, str]] = None,
475475
) -> Dict[str, str]:
476+
"""
477+
Given a JSON dictionary (or event) which might contain sub dictionaries,
478+
flatten it into a single layer dictionary by combining the keys & sub-keys.
479+
480+
Any (non-dictionary), non-string value is dropped.
481+
482+
Transforms:
483+
484+
{"foo": {"bar": "test"}}
485+
486+
To:
487+
488+
{"foo.bar": "test"}
489+
490+
Args:
491+
d: The event or content to continue flattening.
492+
room_version: The room version object.
493+
prefix: The key prefix (from outer dictionaries).
494+
result: The result to mutate.
495+
496+
Returns:
497+
The resulting dictionary.
498+
"""
476499
if prefix is None:
477500
prefix = []
478501
if result is None:

tests/push/test_push_rule_evaluator.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
from typing import Dict, List, Optional, Set, Union, cast
15+
from typing import Any, Dict, List, Optional, Set, Union, cast
1616

1717
import frozendict
1818

@@ -37,6 +37,30 @@
3737
from tests.test_utils.event_injection import create_event, inject_member_event
3838

3939

40+
class FlattenDictTestCase(unittest.TestCase):
41+
def test_simple(self) -> None:
42+
"""Test a dictionary that isn't modified."""
43+
input = {"foo": "abc"}
44+
self.assertEqual(input, _flatten_dict(input))
45+
46+
def test_nested(self) -> None:
47+
"""Nested dictionaries become dotted paths."""
48+
input = {"foo": {"bar": "abc"}}
49+
self.assertEqual({"foo.bar": "abc"}, _flatten_dict(input))
50+
51+
def test_non_string(self) -> None:
52+
"""Non-string items are dropped."""
53+
input: Dict[str, Any] = {
54+
"woo": "woo",
55+
"foo": True,
56+
"bar": 1,
57+
"baz": None,
58+
"fuzz": [],
59+
"boo": {},
60+
}
61+
self.assertEqual({"woo": "woo"}, _flatten_dict(input))
62+
63+
4064
class PushRuleEvaluatorTestCase(unittest.TestCase):
4165
def _get_evaluator(
4266
self,

0 commit comments

Comments
 (0)