michael@0: #!/usr/bin/env python michael@0: """ michael@0: Unit-Tests for moznetwork michael@0: """ michael@0: michael@0: import mock michael@0: import mozinfo michael@0: import moznetwork michael@0: import re michael@0: import subprocess michael@0: import unittest michael@0: michael@0: michael@0: def verify_ip_in_list(ip): michael@0: """ michael@0: Helper Method to check if `ip` is listed in Network Adresses michael@0: returned by ipconfig/ifconfig, depending on the platform in use michael@0: michael@0: :param ip: IPv4 address in the xxx.xxx.xxx.xxx format as a string michael@0: Example Usage: michael@0: verify_ip_in_list('192.168.0.1') michael@0: michael@0: returns True if the `ip` is in the list of IPs in ipconfig/ifconfig michael@0: """ michael@0: michael@0: # Regex to match IPv4 addresses. michael@0: # 0-255.0-255.0-255.0-255, note order is important here. michael@0: regexip = re.compile("((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}" michael@0: "(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)") michael@0: michael@0: if mozinfo.isLinux or mozinfo.isMac or mozinfo.isBsd: michael@0: args = ["ifconfig"] michael@0: michael@0: if mozinfo.isWin: michael@0: args = ["ipconfig"] michael@0: michael@0: ps = subprocess.Popen(args, stdout=subprocess.PIPE) michael@0: standardoutput, standarderror = ps.communicate() michael@0: michael@0: # Generate a list of IPs by parsing the output of ip/ifconfig michael@0: ip_list = [x.group() for x in re.finditer(regexip, standardoutput)] michael@0: michael@0: # Check if ip is in list michael@0: if ip in ip_list: michael@0: return True michael@0: else: michael@0: return False michael@0: michael@0: michael@0: class TestGetIP(unittest.TestCase): michael@0: michael@0: def test_get_ip(self): michael@0: """ Attempt to test the IP address returned by michael@0: moznetwork.get_ip() is valid """ michael@0: michael@0: ip = moznetwork.get_ip() michael@0: michael@0: # Check the IP returned by moznetwork is in the list michael@0: self.assertTrue(verify_ip_in_list(ip)) michael@0: michael@0: def test_get_ip_using_get_interface(self): michael@0: """ Test that the control flow path for get_ip() using michael@0: _get_interface_list() is works """ michael@0: michael@0: if mozinfo.isLinux or mozinfo.isMac: michael@0: michael@0: with mock.patch('socket.gethostbyname') as byname: michael@0: # Force socket.gethostbyname to return None michael@0: byname.return_value = None michael@0: michael@0: ip = moznetwork.get_ip() michael@0: michael@0: # Check the IP returned by moznetwork is in the list michael@0: self.assertTrue(verify_ip_in_list(ip)) michael@0: michael@0: michael@0: if __name__ == '__main__': michael@0: unittest.main()