diff --git a/benedict/dicts/__init__.py b/benedict/dicts/__init__.py index 8b85ea9..cf5c05a 100644 --- a/benedict/dicts/__init__.py +++ b/benedict/dicts/__init__.py @@ -130,6 +130,11 @@ class benedict(KeypathDict, IODict, ParseDict): Return a new flattened dict using the given separator to join nested dict keys to flatten keypaths. """ + if separator == self._keypath_separator: + raise ValueError( + f"Invalid flatten separator: '{separator}', " + "flatten separator must be different from keypath separator." + ) return _flatten(self, separator) def get(self, key, default=None): diff --git a/tests/github/test_issue_0088.py b/tests/github/test_issue_0088.py new file mode 100644 index 0000000..c86f4b9 --- /dev/null +++ b/tests/github/test_issue_0088.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +from benedict import benedict + +import unittest + + +class github_issue_0088_test_case(unittest.TestCase): + """ + This class describes a github issue 0088 test case. + https://github.com/fabiocaccamo/python-benedict/issues/88 + + To run this specific test: + - Run python -m unittest tests.github.test_issue_0088 + """ + + def test_flatten_without_keypath_separator(self): + d = benedict({"a": {"b": {"c": 1}}}, keypath_separator=None) + f = d.flatten(".") + self.assertEqual(f, {"a.b.c": 1}) + + def test_flatten_with_separator_equal_to_keypath_separator(self): + d = benedict({"a": {"b": {"c": 1}}}, keypath_separator=".") + with self.assertRaises(ValueError): + f = d.flatten(".") + d = benedict({"a": {"b": {"c": 1}}}, keypath_separator="_") + with self.assertRaises(ValueError): + f = d.flatten("_") + + def test_flatten_with_separator_different_from_keypath_separator(self): + d = benedict({"a": {"b": {"c": 1}}}, keypath_separator="_") + f = d.flatten(".") + self.assertEqual(f, {"a.b.c": 1}) + d = benedict({"a": {"b": {"c": 1}}}, keypath_separator=".") + f = d.flatten("_") + self.assertEqual(f, {"a_b_c": 1})