Skip to content

Commit

Permalink
Country implements ordering (#361)
Browse files Browse the repository at this point in the history
* Orderable Country

Country needs to be orderable if it is part of the primary key and cascade deletion is in use.

* total ordering added. Using six to determine whether other is string.

* test of Country order operators.

* Fixed buggy order precedence in tests.

* NotImplemented is a returned type and not a thrown exception.

* total_ordering replaces explicit declaration of all order operators.

* Removed implementation check for __le__, __ge__ and __gt__.

* Parametrized test_ordering replaces test_op_operator.
  • Loading branch information
Carlos García Montoro authored and kvesteri committed Feb 2, 2019
1 parent db39922 commit e241b54
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
10 changes: 10 additions & 0 deletions sqlalchemy_utils/primitives/country.py
@@ -1,9 +1,12 @@
from functools import total_ordering

import six

from .. import i18n
from ..utils import str_coercible


@total_ordering
@str_coercible
class Country(object):
"""
Expand Down Expand Up @@ -95,6 +98,13 @@ def __hash__(self):
def __ne__(self, other):
return not (self == other)

def __lt__(self, other):
if isinstance(other, Country):
return self.code < other.code
elif isinstance(other, six.string_types):
return self.code < other
return NotImplemented

def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.code)

Expand Down
29 changes: 29 additions & 0 deletions tests/primitives/test_country.py
@@ -1,3 +1,5 @@
import operator

import pytest
import six

Expand Down Expand Up @@ -56,6 +58,33 @@ def test_non_equality_operator(self):
assert Country(u'FI') != u'sv'
assert not (Country(u'FI') != u'FI')

@pytest.mark.parametrize(
'op, code_left, code_right, is_',
[
(operator.lt, u'ES', u'FI', True),
(operator.lt, u'FI', u'ES', False),
(operator.lt, u'ES', u'ES', False),
(operator.le, u'ES', u'FI', True),
(operator.le, u'FI', u'ES', False),
(operator.le, u'ES', u'ES', True),
(operator.ge, u'ES', u'FI', False),
(operator.ge, u'FI', u'ES', True),
(operator.ge, u'ES', u'ES', True),
(operator.gt, u'ES', u'FI', False),
(operator.gt, u'FI', u'ES', True),
(operator.gt, u'ES', u'ES', False),
]
)
def test_ordering(self, op, code_left, code_right, is_):
country_left = Country(code_left)
country_right = Country(code_right)
assert op(country_left, country_right) is is_
assert op(country_left, code_right) is is_
assert op(code_left, country_right) is is_

def test_hash(self):
return hash(Country('FI')) == hash('FI')

Expand Down

0 comments on commit e241b54

Please sign in to comment.