Skip to content

Commit 74db9d7

Browse files
committed
Fixed broken yaml serialization with benedict attributes. #89
1 parent 95a0ca1 commit 74db9d7

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

benedict/serializers/yaml.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22

33
from benedict.serializers.abstract import AbstractSerializer
4+
from benedict.serializers.json import JSONSerializer
45

56
import yaml
67

@@ -12,11 +13,13 @@ class YAMLSerializer(AbstractSerializer):
1213

1314
def __init__(self):
1415
super(YAMLSerializer, self).__init__()
16+
self._json_serializer = JSONSerializer()
1517

1618
def decode(self, s, **kwargs):
1719
data = yaml.safe_load(s, **kwargs)
1820
return data
1921

2022
def encode(self, d, **kwargs):
21-
data = yaml.dump(dict(d.items()), **kwargs)
23+
d = self._json_serializer.decode(self._json_serializer.encode(d))
24+
data = yaml.dump(d, **kwargs)
2225
return data

tests/github/test_issue_0089.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from benedict import benedict
4+
5+
import unittest
6+
7+
8+
class github_issue_0089_test_case(unittest.TestCase):
9+
"""
10+
This class describes a github issue 0089 test case.
11+
https://github.com/fabiocaccamo/python-benedict/issues/89
12+
13+
To run this specific test:
14+
- Run python -m unittest tests.github.test_issue_0089
15+
"""
16+
17+
def test_broken_serialization_with_benedict_attributes(self):
18+
d1 = benedict()
19+
d1["a"] = benedict({"b": 2})
20+
yaml_str = d1.to_yaml()
21+
# print(yaml_str)
22+
self.assertEqual(yaml_str, "a:\n b: 2\n")
23+
d2 = benedict.from_yaml(yaml_str)
24+
self.assertEqual(d1, d2)

0 commit comments

Comments
 (0)