testing/mozbase/moznetwork/tests/test.py

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:90c448c6c4a8
1 #!/usr/bin/env python
2 """
3 Unit-Tests for moznetwork
4 """
5
6 import mock
7 import mozinfo
8 import moznetwork
9 import re
10 import subprocess
11 import unittest
12
13
14 def verify_ip_in_list(ip):
15 """
16 Helper Method to check if `ip` is listed in Network Adresses
17 returned by ipconfig/ifconfig, depending on the platform in use
18
19 :param ip: IPv4 address in the xxx.xxx.xxx.xxx format as a string
20 Example Usage:
21 verify_ip_in_list('192.168.0.1')
22
23 returns True if the `ip` is in the list of IPs in ipconfig/ifconfig
24 """
25
26 # Regex to match IPv4 addresses.
27 # 0-255.0-255.0-255.0-255, note order is important here.
28 regexip = re.compile("((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}"
29 "(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)")
30
31 if mozinfo.isLinux or mozinfo.isMac or mozinfo.isBsd:
32 args = ["ifconfig"]
33
34 if mozinfo.isWin:
35 args = ["ipconfig"]
36
37 ps = subprocess.Popen(args, stdout=subprocess.PIPE)
38 standardoutput, standarderror = ps.communicate()
39
40 # Generate a list of IPs by parsing the output of ip/ifconfig
41 ip_list = [x.group() for x in re.finditer(regexip, standardoutput)]
42
43 # Check if ip is in list
44 if ip in ip_list:
45 return True
46 else:
47 return False
48
49
50 class TestGetIP(unittest.TestCase):
51
52 def test_get_ip(self):
53 """ Attempt to test the IP address returned by
54 moznetwork.get_ip() is valid """
55
56 ip = moznetwork.get_ip()
57
58 # Check the IP returned by moznetwork is in the list
59 self.assertTrue(verify_ip_in_list(ip))
60
61 def test_get_ip_using_get_interface(self):
62 """ Test that the control flow path for get_ip() using
63 _get_interface_list() is works """
64
65 if mozinfo.isLinux or mozinfo.isMac:
66
67 with mock.patch('socket.gethostbyname') as byname:
68 # Force socket.gethostbyname to return None
69 byname.return_value = None
70
71 ip = moznetwork.get_ip()
72
73 # Check the IP returned by moznetwork is in the list
74 self.assertTrue(verify_ip_in_list(ip))
75
76
77 if __name__ == '__main__':
78 unittest.main()

mercurial