python-benedict/tests/github/test_issue_0046.py

109 lines
3.4 KiB
Python
Raw Permalink Normal View History

import json
import unittest
from benedict import benedict
class github_issue_0046_test_case(unittest.TestCase):
"""
2022-02-13 10:35:43 +00:00
This class describes a github issue 0046 test case.
https://github.com/fabiocaccamo/python-benedict/issues/46
To run this specific test:
- Run python -m unittest tests.github.test_issue_0046
"""
2022-02-13 10:35:43 +00:00
def test_json_dumps_with_cloned_instance(self):
d = {
2022-02-13 10:35:43 +00:00
"id": "37e4f6e876",
"meta": {
"data": {
"category": "category0",
"id": "data_id",
"title": "A title",
},
2022-02-13 10:35:43 +00:00
"id": "37e4f6e876",
"k0": {
"ka": {
"key1": "",
"key2": "value2",
"key3": "value3",
"key4": True,
},
2022-02-13 10:35:43 +00:00
"kb": {
"key1": "",
"key2": "value2",
"key3": "value3",
"key4": True,
},
2022-02-13 10:35:43 +00:00
"kc": {
"extra_key2": "value2",
"key1": "",
"key2": "value2",
"key3": "value3",
"key4": True,
},
2022-02-13 10:35:43 +00:00
"kd": {
"key1": "",
"key2": "value2",
"key3": "value3",
"key4": True,
},
2022-02-13 10:35:43 +00:00
"ke": {
"key1": "",
"key2": "value2",
"key3": "value3",
"key4": True,
},
"kf": {
"key1": "",
"key2": "value2",
"key3": "separated",
"key4": True,
},
},
2022-02-13 10:35:43 +00:00
"language": "en",
"name": "name_value",
},
}
2022-02-13 10:35:43 +00:00
keypaths = ["id", "meta.k0.kc", "meta.language"]
d = benedict(d)
d_new = benedict()
d_new = d.subset(keypaths)
2021-01-18 15:00:22 +00:00
# patch the json module to force the use of the python encoder - #46
# import json
# json.encoder.c_make_encoder = None
json_encoder = None
2023-02-09 18:19:02 +00:00
def json_dumps(d):
return json.dumps(d, sort_keys=True, cls=json_encoder)
2021-01-18 15:00:22 +00:00
2022-02-13 10:35:43 +00:00
d_new_raw = {
"id": "37e4f6e876",
"meta": {
"k0": {
"kc": {
"extra_key2": "value2",
"key1": "",
"key2": "value2",
"key3": "value3",
"key4": True,
}
},
"language": "en",
},
}
self.assertEqual(d_new, d_new_raw)
2021-01-18 15:00:22 +00:00
self.assertEqual(json_dumps(d_new), json_dumps(d_new_raw))
2022-02-13 10:35:43 +00:00
self.assertEqual(
d_new.to_json(sort_keys=True, cls=json_encoder), json_dumps(d_new_raw)
)
2021-01-18 15:00:22 +00:00
d_new_cloned = d_new.clone()
self.assertEqual(d_new, d_new_cloned)
self.assertEqual(json_dumps(d_new), json_dumps(d_new_cloned))
2022-02-13 10:35:43 +00:00
self.assertEqual(
d_new.to_json(sort_keys=True), d_new_cloned.to_json(sort_keys=True)
)