From 83f2521d5e2debf62e0496a0c4bd9ab6b1591bdd Mon Sep 17 00:00:00 2001 From: Till Maas Date: Tue, 22 May 2018 15:26:34 +0200 Subject: [PATCH] Fix python3 missing "cmp" keyword for list.sort() This fixes this exception on Python3: TypeError: 'cmp' is an invalid keyword argument for this function --- library/network_connections.py | 25 +++++++++++++++++++++++-- tests/test_network_connections.py | 4 ++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/library/network_connections.py b/library/network_connections.py index 1ac8aa4..64bea1d 100644 --- a/library/network_connections.py +++ b/library/network_connections.py @@ -16,10 +16,11 @@ options: Documentation needs to be written. Note that the network_connections mo this module outside the role. Thus, consult README.md for examples for the role. ''' +import functools +import os import socket import sys import traceback -import os ############################################################################### @@ -53,6 +54,21 @@ class ValidationError(MyError): def from_connection(idx, message): return ValidationError('connection[' + str(idx) + ']', message) + +# cmp() is not available in python 3 anymore +if "cmp" not in dir(__builtins__): + def cmp(x, y): + """ + Replacement for built-in function cmp that was removed in Python 3 + + Compare the two objects x and y and return an integer according to + the outcome. The return value is negative if x < y, zero if x == y + and strictly positive if x > y. + """ + + return (x > y) - (x < y) + + class Util: PY3 = (sys.version_info[0] == 3) @@ -1630,7 +1646,12 @@ class NMUtil: if t_b <= 0: return -1 return cmp(t_a, t_b) - cons.sort(cmp = _cmp) + + if Util.PY3: + # functools.cmp_to_key does not exist in Python 2.6 + cons.sort(key=functools.cmp_to_key(_cmp)) + else: + cons.sort(cmp=_cmp) return cons def connection_compare(self, con_a, con_b, normalize_a = False, normalize_b = False, compare_flags = None): diff --git a/tests/test_network_connections.py b/tests/test_network_connections.py index 2c76a8d..67cb1c9 100755 --- a/tests/test_network_connections.py +++ b/tests/test_network_connections.py @@ -1875,6 +1875,10 @@ class TestNM(unittest.TestCase): self.assertIs(s, s2) self.assertTrue(GObject.type_is_a(s, NM.SettingWired)) + def test_connection_list(self): + connections = nmutil.connection_list() + self.assertIsNotNone(connections) + class TestSysUtils(unittest.TestCase): def test_link_read_permaddress(self):