Move get_random_mac into neutron-lib

get_random_mac is used by networking-ovn, tap-as-a-service,
neutron-vpnaas, and vmware-nsx, so we should move it into the
neutron-lib repository.

Change-Id: I391300e6f1d04b2413084bccdbacb038071c4509
This commit is contained in:
Trevor McCasland 2016-10-28 02:27:15 -05:00 committed by Ihar Hrachyshka
parent fa6c37f35b
commit ee0f5b2ab2
3 changed files with 38 additions and 0 deletions

View File

@ -27,3 +27,22 @@ class TestGetHostname(base.BaseTestCase):
self.assertEqual('fake-host-name', self.assertEqual('fake-host-name',
net.get_hostname()) net.get_hostname())
mock_gethostname.assert_called_once_with() mock_gethostname.assert_called_once_with()
class TestGetRandomMac(base.BaseTestCase):
def _test_get_random_mac(self, base_mac, startswith_len):
random_mac = net.get_random_mac(base_mac.split(':'))
self.assertEqual(base_mac[:startswith_len],
random_mac[:startswith_len])
self.assertEqual(len(base_mac), len(random_mac))
for i in random_mac.split(':'):
int(i, 16)
def test_get_random_mac_with_three_octets(self):
base_mac = 'fa:16:3e:00:00:00'
self._test_get_random_mac(base_mac, 9)
def test_get_random_mac_with_four_octets(self):
base_mac = 'fa:16:3e:fe:00:00'
self._test_get_random_mac(base_mac, 12)

View File

@ -11,6 +11,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import random
import socket import socket
@ -20,3 +21,17 @@ def get_hostname():
:returns: The hostname of the system. :returns: The hostname of the system.
""" """
return socket.gethostname() return socket.gethostname()
def get_random_mac(base_mac):
"""Get a random MAC address string of the specified base format.
:param base_mac: The base MAC address format for the MAC address string.
:returns: The MAC address string.
"""
mac = [int(base_mac[0], 16), int(base_mac[1], 16),
int(base_mac[2], 16), random.randint(0x00, 0xff),
random.randint(0x00, 0xff), random.randint(0x00, 0xff)]
if base_mac[3] != '00':
mac[3] = int(base_mac[3], 16)
return ':'.join(["%02x" % x for x in mac])

View File

@ -0,0 +1,4 @@
---
features:
- The ``get_random_mac`` utility function from ``neutron.common.utils`` is
now in ``neutron_lib.utils.net`` with the same name, ``get_random_mac``.