Bug 1428711 - add python3 compatibility to moznetwork r=ahal
authorEdwin Takahashi <egao@mozilla.com>
Fri, 15 Nov 2019 22:45:12 +0000
changeset 502297 520bfdde413e119e3409999d6139da9b0926ccd1
parent 502296 d7e41714afd172c1a027bca721a2e3bc319d0257
child 502298 2dcb4f20e472a3ff0fc61891746c59c9a8be75c4
push id114172
push userdluca@mozilla.com
push dateTue, 19 Nov 2019 11:31:10 +0000
treeherdermozilla-inbound@b5c5ba07d3db [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersahal
bugs1428711
milestone72.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1428711 - add python3 compatibility to moznetwork r=ahal Changes: - rename `test.py` to a more descriptive `test_moznetwork.py` and change associated names in the manifest - added `r` specifier to strings as per PEP warning - bump version to 1.0.0 pending release to pypi Differential Revision: https://phabricator.services.mozilla.com/D52107
testing/mozbase/moznetwork/moznetwork/moznetwork.py
testing/mozbase/moznetwork/setup.py
testing/mozbase/moznetwork/tests/manifest.ini
testing/mozbase/moznetwork/tests/test.py
testing/mozbase/moznetwork/tests/test_moznetwork.py
--- a/testing/mozbase/moznetwork/moznetwork/moznetwork.py
+++ b/testing/mozbase/moznetwork/moznetwork/moznetwork.py
@@ -30,17 +30,17 @@ def _get_logger():
     return logger
 
 
 def _get_interface_list():
     """Provides a list of available network interfaces
        as a list of tuples (name, ip)"""
     logger = _get_logger()
     logger.debug('Gathering interface list')
-    max_iface = 32  # Maximum number of interfaces(Aribtrary)
+    max_iface = 32  # Maximum number of interfaces(arbitrary)
     bytes = max_iface * 32
     is_32bit = (8 * struct.calcsize("P")) == 32  # Set Architecture
     struct_size = 32 if is_32bit else 40
 
     try:
         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         names = array.array('B', '\0' * bytes)
         outbytes = struct.unpack('iL', fcntl.ioctl(
@@ -69,40 +69,40 @@ def _proc_matches(args, regex):
 def _parse_ifconfig():
     """Parse the output of running ifconfig on mac in cases other methods
     have failed"""
     logger = _get_logger()
     logger.debug('Parsing ifconfig')
 
     # Attempt to determine the default interface in use.
     default_iface = _proc_matches(['route', '-n', 'get', 'default'],
-                                  'interface: (\w+)')
+                                  r'interface: (\w+)')
 
     if default_iface:
         addr_list = _proc_matches(['ifconfig', default_iface[0]],
-                                  'inet (\d+.\d+.\d+.\d+)')
+                                  r'inet (\d+.\d+.\d+.\d+)')
         if addr_list:
             logger.debug('Default interface: [%s] %s' % (default_iface[0],
                                                          addr_list[0]))
             if not addr_list[0].startswith('127.'):
                 return addr_list[0]
 
     # Iterate over plausible interfaces if we didn't find a suitable default.
     for iface in ['en%s' % i for i in range(10)]:
         addr_list = _proc_matches(['ifconfig', iface],
-                                  'inet (\d+.\d+.\d+.\d+)')
+                                  r'inet (\d+.\d+.\d+.\d+)')
         if addr_list:
             logger.debug('Interface: [%s] %s' % (iface, addr_list[0]))
             if not addr_list[0].startswith('127.'):
                 return addr_list[0]
 
     # Just return any that isn't localhost. If we can't find one, we have
     # failed.
     addrs = _proc_matches(['ifconfig'],
-                          'inet (\d+.\d+.\d+.\d+)')
+                          r'inet (\d+.\d+.\d+.\d+)')
     try:
         return [addr for addr in addrs if not addr.startswith('127.')][0]
     except IndexError:
         return None
 
 
 def get_ip():
     """Provides an available network interface address, for example
--- a/testing/mozbase/moznetwork/setup.py
+++ b/testing/mozbase/moznetwork/setup.py
@@ -1,33 +1,42 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
 # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import
 
 from setuptools import setup
 
-PACKAGE_VERSION = '0.27'
+PACKAGE_VERSION = '1.0.0'
 
-deps = ['mozinfo',
-        'mozlog >= 5.0',
-        ]
+deps = [
+    'mozinfo',
+    'mozlog >= 5.0',
+]
 
-setup(name='moznetwork',
-      version=PACKAGE_VERSION,
-      description="Library of network utilities for use in Mozilla testing",
-      long_description="see https://firefox-source-docs.mozilla.org/mozbase/index.html",
-      classifiers=['Programming Language :: Python :: 2.7',
-                   'Programming Language :: Python :: 2 :: Only'],
-      # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
-      keywords='mozilla',
-      author='Mozilla Automation and Tools team',
-      author_email='tools@lists.mozilla.org',
-      url='https://wiki.mozilla.org/Auto-tools/Projects/Mozbase',
-      license='MPL',
-      packages=['moznetwork'],
-      include_package_data=True,
-      zip_safe=False,
-      install_requires=deps,
-      entry_points={'console_scripts': [
-          'moznetwork = moznetwork:cli']},
-      )
+setup(
+    name='moznetwork',
+    version=PACKAGE_VERSION,
+    description="Library of network utilities for use in Mozilla testing",
+    long_description="see https://firefox-source-docs.mozilla.org/mozbase/index.html",
+    classifiers=[
+        'Programming Language :: Python :: 2.7',
+        "Programming Language :: Python :: 3",
+        "Programming Language :: Python :: 3.5",
+        "Development Status :: 5 - Production/Stable",
+    ],
+    # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
+    keywords='mozilla',
+    author='Mozilla Automation and Tools team',
+    author_email='tools@lists.mozilla.org',
+    url='https://wiki.mozilla.org/Auto-tools/Projects/Mozbase',
+    license='MPL',
+    packages=['moznetwork'],
+    include_package_data=True,
+    zip_safe=False,
+    install_requires=deps,
+    entry_points={
+        'console_scripts': [
+            'moznetwork = moznetwork:cli'
+        ]
+    },
+)
--- a/testing/mozbase/moznetwork/tests/manifest.ini
+++ b/testing/mozbase/moznetwork/tests/manifest.ini
@@ -1,4 +1,3 @@
 [DEFAULT]
 subsuite = mozbase
-skip-if = python == 3
-[test.py]
+[test_moznetwork.py]
deleted file mode 100644
--- a/testing/mozbase/moznetwork/tests/test.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env python
-"""
-Unit-Tests for moznetwork
-"""
-
-from __future__ import absolute_import
-
-import mock
-import mozinfo
-import moznetwork
-import re
-import subprocess
-from distutils.spawn import find_executable
-
-import mozunit
-import pytest
-
-
-@pytest.fixture(scope='session')
-def ip_addresses():
-    """List of IP addresses associated with the host."""
-
-    # Regex to match IPv4 addresses.
-    # 0-255.0-255.0-255.0-255, note order is important here.
-    regexip = re.compile("((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}"
-                         "(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)")
-
-    commands = (
-        ['ip', 'addr', 'show'],
-        ['ifconfig'],
-        ['ipconfig'],
-        # Explicitly search '/sbin' because it doesn't always appear
-        # to be on the $PATH of all systems
-        ['/sbin/ip', 'addr', 'show'],
-        ['/sbin/ifconfig'],
-    )
-
-    cmd = None
-    for command in commands:
-        if find_executable(command[0]):
-            cmd = command
-            break
-    else:
-        raise OSError("No program for detecting ip address found! Ensure one of 'ip', "
-                      "'ifconfig' or 'ipconfig' exists on your $PATH.")
-
-    ps = subprocess.Popen(cmd, stdout=subprocess.PIPE)
-    standardoutput, standarderror = ps.communicate()
-
-    # Generate a list of IPs by parsing the output of ip/ifconfig
-    return [x.group() for x in re.finditer(regexip, standardoutput)]
-
-
-def test_get_ip(ip_addresses):
-    """ Attempt to test the IP address returned by
-    moznetwork.get_ip() is valid """
-    assert moznetwork.get_ip() in ip_addresses
-
-
-def test_get_ip_using_get_interface(ip_addresses):
-    """ Test that the control flow path for get_ip() using
-    _get_interface_list() is works """
-
-    if mozinfo.isLinux or mozinfo.isMac:
-
-        with mock.patch('socket.gethostbyname') as byname:
-            # Force socket.gethostbyname to return None
-            byname.return_value = None
-            assert moznetwork.get_ip() in ip_addresses
-
-
-if __name__ == '__main__':
-    mozunit.main()
new file mode 100644
--- /dev/null
+++ b/testing/mozbase/moznetwork/tests/test_moznetwork.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+"""
+Unit-Tests for moznetwork
+"""
+
+from __future__ import absolute_import
+
+import re
+import subprocess
+from distutils.spawn import find_executable
+
+import moznetwork
+import pytest
+
+import mock
+import mozinfo
+import mozunit
+
+
+@pytest.fixture(scope='session')
+def ip_addresses():
+    """List of IP addresses associated with the host."""
+
+    # Regex to match IPv4 addresses.
+    # 0-255.0-255.0-255.0-255, note order is important here.
+    regexip = re.compile("((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}"
+                         "(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)")
+
+    commands = (
+        ['ip', 'addr', 'show'],
+        ['ifconfig'],
+        ['ipconfig'],
+        # Explicitly search '/sbin' because it doesn't always appear
+        # to be on the $PATH of all systems
+        ['/sbin/ip', 'addr', 'show'],
+        ['/sbin/ifconfig'],
+    )
+
+    cmd = None
+    for command in commands:
+        if find_executable(command[0]):
+            cmd = command
+            break
+    else:
+        raise OSError("No program for detecting ip address found! Ensure one of 'ip', "
+                      "'ifconfig' or 'ipconfig' exists on your $PATH.")
+
+    ps = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+    standardoutput, _ = ps.communicate()
+
+    # Generate a list of IPs by parsing the output of ip/ifconfig
+    return [x.group() for x in re.finditer(regexip, standardoutput.decode('UTF-8'))]
+
+
+def test_get_ip(ip_addresses):
+    """ Attempt to test the IP address returned by
+    moznetwork.get_ip() is valid """
+    assert moznetwork.get_ip() in ip_addresses
+
+
+@pytest.mark.skipif(mozinfo.isWin, reason="Test is not supported in Windows")
+def test_get_ip_using_get_interface(ip_addresses):
+    """ Test that the control flow path for get_ip() using
+    _get_interface_list() is works """
+    with mock.patch('socket.gethostbyname') as byname:
+        # Force socket.gethostbyname to return None
+        byname.return_value = None
+        assert moznetwork.get_ip() in ip_addresses
+
+
+if __name__ == '__main__':
+    mozunit.main()