Explorar o código

calcex.Figure: overload Figure - sum([])

Fabian Peter Hammerle %!s(int64=8) %!d(string=hai) anos
pai
achega
43c87f264b
Modificáronse 2 ficheiros con 20 adicións e 4 borrados
  1. 7 4
      ioex/calcex.py
  2. 13 0
      tests/calcex/test_figure.py

+ 7 - 4
ioex/calcex.py

@@ -6,6 +6,9 @@ except ImportError:
     yaml = None
 
 
+EMPTY_SUM = sum([])
+
+
 class UnitMismatchError(ValueError):
     pass
 
@@ -122,11 +125,11 @@ class Figure(object):
             raise NotImplementedError('{!r} + {!r}'.format(other, self))
 
     def __sub__(self, other):
-        if not isinstance(self, type(other)):
+        if isinstance(other, type(EMPTY_SUM)) and other == EMPTY_SUM:
+            return copy.deepcopy(self)
+        elif not isinstance(self, type(other)):
             raise NotImplementedError('{!r} - {!r}'.format(self, other))
-        assert not self.value is None
-        assert not other.value is None
-        if self.unit != other.unit:
+        elif self.unit != other.unit:
             raise UnitMismatchError('{} - {}'.format(self, other))
         else:
             return type(self)(value=self.value - other.value, unit=self.unit)

+ 13 - 0
tests/calcex/test_figure.py

@@ -188,6 +188,15 @@ def test_sub_unit_mismatch(a, b):
         a - b
 
 
+@pytest.mark.parametrize(('a', 'b'), [
+    [Figure(1, 'm'), 2],
+    [Figure(1, 'm'), None],
+])
+def test_sub_not_implemented(a, b):
+    with pytest.raises(NotImplementedError):
+        a - b
+
+
 def test_sub_persistent():
     a = Figure(1, ['m'])
     b = Figure(2, ['m'])
@@ -200,6 +209,10 @@ def test_sub_persistent():
     assert Figure(-1, ['m']) == d
 
 
+def test_sub_null_subtrahend():
+    assert Figure(1, ['m']) == Figure(1, ['m']) - sum([])
+
+
 @pytest.mark.parametrize(('a', 'b', 'expected_product'), [
     [Figure(1, 'm'), Figure(2), Figure(2, 'm')],
     [Figure(1, 'm'), 2, Figure(2, 'm')],