Add a docstring & tests for _flatten_dict. (#14981)

This commit is contained in:
Patrick Cloke 2023-02-03 11:48:13 -05:00 committed by GitHub
parent 52700a0bcf
commit f0cae26d58
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 49 additions and 1 deletions

1
changelog.d/14981.misc Normal file
View file

@ -0,0 +1 @@
Add tests for `_flatten_dict`.

View file

@ -473,6 +473,29 @@ def _flatten_dict(
prefix: Optional[List[str]] = None, prefix: Optional[List[str]] = None,
result: Optional[Dict[str, str]] = None, result: Optional[Dict[str, str]] = None,
) -> Dict[str, str]: ) -> Dict[str, str]:
"""
Given a JSON dictionary (or event) which might contain sub dictionaries,
flatten it into a single layer dictionary by combining the keys & sub-keys.
Any (non-dictionary), non-string value is dropped.
Transforms:
{"foo": {"bar": "test"}}
To:
{"foo.bar": "test"}
Args:
d: The event or content to continue flattening.
room_version: The room version object.
prefix: The key prefix (from outer dictionaries).
result: The result to mutate.
Returns:
The resulting dictionary.
"""
if prefix is None: if prefix is None:
prefix = [] prefix = []
if result is None: if result is None:

View file

@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from typing import Dict, List, Optional, Set, Union, cast from typing import Any, Dict, List, Optional, Set, Union, cast
import frozendict import frozendict
@ -37,6 +37,30 @@ from tests import unittest
from tests.test_utils.event_injection import create_event, inject_member_event from tests.test_utils.event_injection import create_event, inject_member_event
class FlattenDictTestCase(unittest.TestCase):
def test_simple(self) -> None:
"""Test a dictionary that isn't modified."""
input = {"foo": "abc"}
self.assertEqual(input, _flatten_dict(input))
def test_nested(self) -> None:
"""Nested dictionaries become dotted paths."""
input = {"foo": {"bar": "abc"}}
self.assertEqual({"foo.bar": "abc"}, _flatten_dict(input))
def test_non_string(self) -> None:
"""Non-string items are dropped."""
input: Dict[str, Any] = {
"woo": "woo",
"foo": True,
"bar": 1,
"baz": None,
"fuzz": [],
"boo": {},
}
self.assertEqual({"woo": "woo"}, _flatten_dict(input))
class PushRuleEvaluatorTestCase(unittest.TestCase): class PushRuleEvaluatorTestCase(unittest.TestCase):
def _get_evaluator( def _get_evaluator(
self, self,