From 74db9d7b7c28102dd54fd5e0cb230ce876cd4128 Mon Sep 17 00:00:00 2001 From: Fabio Caccamo Date: Wed, 27 Apr 2022 19:26:34 +0200 Subject: [PATCH] Fixed broken `yaml` serialization with `benedict` attributes. #89 --- benedict/serializers/yaml.py | 5 ++++- tests/github/test_issue_0089.py | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tests/github/test_issue_0089.py diff --git a/benedict/serializers/yaml.py b/benedict/serializers/yaml.py index 3f10b4f..3e11e30 100644 --- a/benedict/serializers/yaml.py +++ b/benedict/serializers/yaml.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- from benedict.serializers.abstract import AbstractSerializer +from benedict.serializers.json import JSONSerializer import yaml @@ -12,11 +13,13 @@ class YAMLSerializer(AbstractSerializer): def __init__(self): super(YAMLSerializer, self).__init__() + self._json_serializer = JSONSerializer() def decode(self, s, **kwargs): data = yaml.safe_load(s, **kwargs) return data def encode(self, d, **kwargs): - data = yaml.dump(dict(d.items()), **kwargs) + d = self._json_serializer.decode(self._json_serializer.encode(d)) + data = yaml.dump(d, **kwargs) return data diff --git a/tests/github/test_issue_0089.py b/tests/github/test_issue_0089.py new file mode 100644 index 0000000..690b0d0 --- /dev/null +++ b/tests/github/test_issue_0089.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +from benedict import benedict + +import unittest + + +class github_issue_0089_test_case(unittest.TestCase): + """ + This class describes a github issue 0089 test case. + https://github.com/fabiocaccamo/python-benedict/issues/89 + + To run this specific test: + - Run python -m unittest tests.github.test_issue_0089 + """ + + def test_broken_serialization_with_benedict_attributes(self): + d1 = benedict() + d1["a"] = benedict({"b": 2}) + yaml_str = d1.to_yaml() + # print(yaml_str) + self.assertEqual(yaml_str, "a:\n b: 2\n") + d2 = benedict.from_yaml(yaml_str) + self.assertEqual(d1, d2)