Browse Source

yaml support for sum

Fabian Peter Hammerle 8 years ago
parent
commit
6834543b37
2 changed files with 39 additions and 2 deletions
  1. 18 2
      dingguo/__init__.py
  2. 21 0
      tests/test_yaml.py

+ 18 - 2
dingguo/__init__.py

@@ -42,7 +42,6 @@ class Figure(yaml.YAMLObject):
     @classmethod
     def from_yaml(cls, loader, node):
         attr = loader.construct_mapping(node)
-        print(type(attr['unit']), attr['unit'])
         return cls(
                 value = attr['value'],
                 unit = unicode(attr['unit']),
@@ -70,6 +69,8 @@ class Distance(Figure):
 
 class Sum(Figure):
 
+    yaml_tag = u'!sum'
+
     def __init__(self, value, currency):
         super(Sum, self).__init__(value, currency)
 
@@ -100,7 +101,22 @@ class Sum(Figure):
     """ use property() instead of decorator to enable overriding """
     unit = property(get_unit, set_unit)
 
-class Discount(object):
+    @classmethod
+    def from_yaml(cls, loader, node):
+        attr = loader.construct_scalar(node).split(' ')
+        return cls(
+                currency = attr[0],
+                value = float(attr[1]),
+                )
+
+    @classmethod
+    def to_yaml(cls, dumper, s):
+        return dumper.represent_scalar(
+                cls.yaml_tag,
+                '%s %s' % (s.currency, repr(s.value)),
+                )
+
+class Discount(yaml.YAMLObject):
 
     def __init__(
             self,

+ 21 - 0
tests/test_yaml.py

@@ -16,6 +16,12 @@ def get_figure_a():
 def get_figure_b():
     return dingguo.Figure(12300, u'米')
 
+def get_sum_a():
+    return dingguo.Sum(1.23, u'EUR')
+
+def get_sum_b():
+    return dingguo.Sum(20.45, u'€')
+
 def to_yaml(data):
     return yaml.dump(data, default_flow_style = False, allow_unicode = True).decode('utf-8')
 
@@ -42,3 +48,18 @@ def test_figure_to_yaml_unicode():
 unit: 米
 value: 12300
 """)
+
+def test_sum_to_yaml_a():
+    assert to_yaml(get_sum_a()) == u"!sum 'EUR 1.23'\n"
+
+def test_sum_to_yaml_b():
+    assert to_yaml(get_sum_b()) == u"!sum 'EUR 20.45'\n"
+
+def test_sum_from_yaml_a():
+    assert get_sum_a() == yaml.load(u"!sum EUR 1.23")
+
+def test_sum_from_yaml_a_sign():
+    assert get_sum_a() == yaml.load(u"!sum € 1.23")
+
+def test_sum_from_yaml_a_quotes():
+    assert get_sum_a() == yaml.load(u"!sum 'EUR 1.23'")