test_moznetwork.py (2002B)
1 #!/usr/bin/env python 2 """ 3 Unit-Tests for moznetwork 4 """ 5 6 import re 7 import shutil 8 import subprocess 9 from unittest import mock 10 11 import mozinfo 12 import moznetwork 13 import mozunit 14 import pytest 15 16 17 @pytest.fixture(scope="session") 18 def ip_addresses(): 19 """List of IP addresses associated with the host.""" 20 21 # Regex to match IPv4 addresses. 22 # 0-255.0-255.0-255.0-255, note order is important here. 23 regexip = re.compile( 24 r"((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}" 25 r"(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)" 26 ) 27 28 commands = ( 29 ["ip", "addr", "show"], 30 ["ifconfig"], 31 ["ipconfig"], 32 # Explicitly search '/sbin' because it doesn't always appear 33 # to be on the $PATH of all systems 34 ["/sbin/ip", "addr", "show"], 35 ["/sbin/ifconfig"], 36 ) 37 38 cmd = None 39 for command in commands: 40 if shutil.which(command[0]): 41 cmd = command 42 break 43 else: 44 raise OSError( 45 "No program for detecting ip address found! Ensure one of 'ip', " 46 "'ifconfig' or 'ipconfig' exists on your $PATH." 47 ) 48 49 ps = subprocess.Popen(cmd, stdout=subprocess.PIPE) 50 standardoutput, _ = ps.communicate() 51 52 # Generate a list of IPs by parsing the output of ip/ifconfig 53 return [x.group() for x in re.finditer(regexip, standardoutput.decode("UTF-8"))] 54 55 56 def test_get_ip(ip_addresses): 57 """Attempt to test the IP address returned by 58 moznetwork.get_ip() is valid""" 59 assert moznetwork.get_ip() in ip_addresses 60 61 62 @pytest.mark.skipif(mozinfo.isWin, reason="Test is not supported in Windows") 63 def test_get_ip_using_get_interface(ip_addresses): 64 """Test that the control flow path for get_ip() using 65 _get_interface_list() is works""" 66 with mock.patch("socket.gethostbyname") as byname: 67 # Force socket.gethostbyname to return None 68 byname.return_value = None 69 assert moznetwork.get_ip() in ip_addresses 70 71 72 if __name__ == "__main__": 73 mozunit.main()