Skip to content

Commit c3cdcfd

Browse files
authored
X509Name: Use functools.totalordering for comparisons (#1086)
* X509Name: Use functools.totalordering for comparisons - Reduce the magic - Make it more readable - Make it easier to add type annotations in the future * Correctly return NotImplemented * Add new comparison test case
1 parent d259e1d commit c3cdcfd

File tree

2 files changed

+23
-16
lines changed

2 files changed

+23
-16
lines changed

src/OpenSSL/crypto.py

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import calendar
22
import datetime
3-
43
from base64 import b16encode
4+
import functools
55
from functools import partial
6-
from operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__
76

87
from cryptography import utils, x509
98
from cryptography.hazmat.primitives.asymmetric import dsa, rsa
@@ -528,6 +527,7 @@ def get_elliptic_curve(name):
528527
raise ValueError("unknown curve name", name)
529528

530529

530+
@functools.total_ordering
531531
class X509Name:
532532
"""
533533
An X.509 Distinguished Name.
@@ -642,23 +642,17 @@ def __getattr__(self, name):
642642
_lib.OPENSSL_free(result_buffer[0])
643643
return result
644644

645-
def _cmp(op):
646-
def f(self, other):
647-
if not isinstance(other, X509Name):
648-
return NotImplemented
649-
result = _lib.X509_NAME_cmp(self._name, other._name)
650-
return op(result, 0)
651-
652-
return f
645+
def __eq__(self, other):
646+
if not isinstance(other, X509Name):
647+
return NotImplemented
653648

654-
__eq__ = _cmp(__eq__)
655-
__ne__ = _cmp(__ne__)
649+
return _lib.X509_NAME_cmp(self._name, other._name) == 0
656650

657-
__lt__ = _cmp(__lt__)
658-
__le__ = _cmp(__le__)
651+
def __lt__(self, other):
652+
if not isinstance(other, X509Name):
653+
return NotImplemented
659654

660-
__gt__ = _cmp(__gt__)
661-
__ge__ = _cmp(__ge__)
655+
return _lib.X509_NAME_cmp(self._name, other._name) < 0
662656

663657
def __repr__(self):
664658
"""

tests/test_crypto.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1398,6 +1398,19 @@ def assert_greater_than(a, b):
13981398
# other X509Name.
13991399
assert_greater_than(x509_name(CN="def"), x509_name(CN="abc"))
14001400

1401+
def assert_raises(a, b):
1402+
with pytest.raises(TypeError):
1403+
a < b
1404+
with pytest.raises(TypeError):
1405+
a <= b
1406+
with pytest.raises(TypeError):
1407+
a > b
1408+
with pytest.raises(TypeError):
1409+
a >= b
1410+
1411+
# Only X509Name objects can be compared with lesser than / greater than
1412+
assert_raises(x509_name(), object())
1413+
14011414
def test_hash(self):
14021415
"""
14031416
`X509Name.hash` returns an integer hash based on the value of the name.

0 commit comments

Comments
 (0)