"convert_to_sanitized_mac_address" accepts netaddr.EUI type values

Change-Id: Iec317f00827b05455dba369afcb6f1fd8f0fca71
Closes-Bug: #1997680
This commit is contained in:
Rodolfo Alonso Hernandez 2022-11-16 22:35:44 +01:00 committed by Rodolfo Alonso
parent 2ded6ed3ce
commit f2bb7c72cd
2 changed files with 21 additions and 19 deletions

View File

@ -10,6 +10,7 @@
# License for the specific language governing permissions and limitations
# under the License.
import copy
import uuid
import netaddr
@ -328,12 +329,16 @@ def convert_to_mac_if_none(data):
def convert_to_sanitized_mac_address(mac_address):
"""Return a MAC address with format xx:xx:xx:xx:xx:xx
:param mac_address: The MAC address value
:param mac_address: (string, netaddr.EUI) The MAC address value
:return: A string with the MAC address formatted. If the MAC address
provided is invalid, the same input value is returned; the goal
of this method is not to validate it.
"""
try:
if isinstance(mac_address, netaddr.EUI):
_mac_address = copy.deepcopy(mac_address)
_mac_address.dialect = netaddr.mac_unix_expanded
return str(_mac_address)
return str(netaddr.EUI(mac_address, dialect=netaddr.mac_unix_expanded))
except netaddr.core.AddrFormatError:
return mac_address

View File

@ -358,24 +358,21 @@ class TestConvertPortMacAddress(base.BaseTestCase):
class TestConvertToSanitizedMacAddress(base.BaseTestCase):
def test_sanitize_mac_address(self):
self.assertEqual(
'00:11:22:33:44:55',
converters.convert_to_sanitized_mac_address('00:11:22:33:44:55'))
self.assertEqual(
'00:11:22:33:44:05',
converters.convert_to_sanitized_mac_address('00:11:22:33:44:5'))
self.assertEqual(
'00:01:02:03:04:05',
converters.convert_to_sanitized_mac_address('0:1:2:3:4:5'))
self.assertEqual(
'ca:fe:ca:fe:0a:0e',
converters.convert_to_sanitized_mac_address('ca:FE:cA:Fe:a:E'))
self.assertEqual(
'01:23:45:67:89:01',
converters.convert_to_sanitized_mac_address('12345678901'))
self.assertEqual(
'01:23:45:67:89:01',
converters.convert_to_sanitized_mac_address('012345678901'))
input_exp = (('00:11:22:33:44:55', '00:11:22:33:44:55'),
('00:11:22:33:44:5', '00:11:22:33:44:05'),
('0:1:2:3:4:5', '00:01:02:03:04:05'),
('ca:FE:cA:Fe:a:E', 'ca:fe:ca:fe:0a:0e'),
('12345678901', '01:23:45:67:89:01'),
('012345678901', '01:23:45:67:89:01'),
)
for input, expected in input_exp:
self.assertEqual(
expected,
converters.convert_to_sanitized_mac_address(input))
eui_address = netaddr.EUI(input)
self.assertEqual(
expected,
converters.convert_to_sanitized_mac_address(eui_address))
# Not converted, those MAC address will fail in the validation step.
self.assertEqual(