Skip to content

Commit

Permalink
Add correct comparison support for Scalar
Browse files Browse the repository at this point in the history
BARRIL-26
  • Loading branch information
arthursoprana committed Oct 4, 2019
1 parent e090474 commit 11e62f0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 10 deletions.
14 changes: 11 additions & 3 deletions src/barril/units/_quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -660,9 +660,17 @@ def Convert(self, value, to_unit):
:returns:
An object with values to the passed unit.
"""
return self._unit_database.Convert(
self._composing_categories, self._composing_units, to_unit, value
)
try:
return self._unit_database.Convert(
self._composing_categories, self._composing_units, to_unit, value
)
except:
return self._unit_database.Convert(
self._category,
self._CreateUnitsWithJoinedExponentsString(),
to_unit,
value,
)

@classmethod
def _GetComparison(cls, operator, use_literals=False):
Expand Down
7 changes: 4 additions & 3 deletions src/barril/units/_scalar.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,8 @@ def GetFormatted(self, unit=None, value_format=None):
def __eq__(self, other):
return (
type(self) is type(other)
and self._value == other.value
and self._quantity == other._quantity
and self._value == other.GetValue(self.unit)
and self._quantity._category == other._quantity._category
)

def AlmostEqual(self, other, precision):
Expand All @@ -254,7 +254,8 @@ def AlmostEqual(self, other, precision):
)

def __hash__(self, *args, **kwargs):
return hash((self._value, self._quantity))
default_unit = self._unit_database.GetDefaultUnit(self._quantity._category)
return hash((self.GetValue(default_unit), self._quantity._category))

def __lt__(self, other):
if self.quantity_type != other.quantity_type:
Expand Down
22 changes: 18 additions & 4 deletions src/barril/units/_tests/test_scalar.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@
"""

import pytest
from pytest import approx

from barril._foundation.odict import odict
from barril import units
from barril._foundation.odict import odict
from barril.units import (
ChangeScalars,
InvalidOperationError,
InvalidUnitError,
ObtainQuantity,
Quantity,
Scalar,
ChangeScalars,
)
from pytest import approx


def testScalarInterface(unit_database_well_length):
Expand Down Expand Up @@ -615,3 +614,18 @@ class Fluid:

assert fluid.density.GetValue("lbm/galUS") == 10
assert fluid.concentration.GetValue("%") == 1.0


def testComparison():
a = Scalar(1, "m")
b = Scalar(100, "cm")
c = Scalar(99, "cm")

assert a == b
assert a <= b
assert b >= a
assert c <= b
assert c <= a

# Test set creation with scalars
assert {b, a, c} == {a, b, c} == {c, a, b}

0 comments on commit 11e62f0

Please sign in to comment.