pywifi_test.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. #!/usr/bin/env python3
  2. # vim: set fileencoding=utf-8
  3. """
  4. Test cases for pywifi.
  5. """
  6. import pytest
  7. import sys
  8. import time
  9. import platform
  10. import logging
  11. # For mocking
  12. import os
  13. import stat
  14. import socket
  15. import pywifi
  16. from pywifi import const
  17. pywifi.set_loglevel(logging.INFO)
  18. class SockMock:
  19. default_scan_results =\
  20. "bssid / frequency / signal level / flags / ssid\n"\
  21. "14:4d:67:14:1e:44\t2412\t-67\t[WPA2-PSK-CCMP][WPS][ESS]\tTOTOLINK N302RE\n"\
  22. "ac:9e:17:31:85:fc\t2437\t-63\t[WPA2-PSK-CCMP][WPS][ESS]\tEvan\n"\
  23. "0c:80:63:2b:0d:a8\t2417\t-79\t[WPA2-PSK-CCMP][WPS][ESS]\tKevin_H2\n"\
  24. "78:32:1b:63:96:05\t2422\t-91\t[WPA-PSK-CCMP][WPA2-PSK-CCMP][ESS]\tjoyfulness\n"
  25. def __init__(self):
  26. self._last_cmd = None
  27. self._last_state = None
  28. self._network_profiles = []
  29. def bind(self, *args, **kwargs):
  30. pass
  31. def connect(self, *args, **kwargs):
  32. pass
  33. def recv(self, *args, **kwargs):
  34. if 'SCAN' == self._last_cmd:
  35. #print('mock sock get scan cmd')
  36. return b'OK\n'
  37. elif 'PING' == self._last_cmd:
  38. #print('mock sock get ping cmd')
  39. return b'PONG'
  40. elif 'SCAN_RESULTS' == self._last_cmd:
  41. #print('mock sock get scan_result cmd')
  42. return bytearray(self.default_scan_results, 'utf-8')
  43. elif 'DISCONNECT' == self._last_cmd:
  44. #print('mock sock get scan_result cmd')
  45. self._last_state = 0
  46. return b'OK\n'
  47. elif 'SELECT_NETWORK' == self._last_cmd[0:len('SELECT_NETWORK')]:
  48. #print('mock sock get scan_result cmd')
  49. self._last_state = 1
  50. return b'OK\n'
  51. elif 'STATUS' == self._last_cmd:
  52. #print('mock sock get scan_result cmd')
  53. if self._last_state == 0:
  54. status = 'wpa_state=DISCONNECTED'
  55. elif self._last_state == 1:
  56. status = 'wpa_state=COMPLETED'
  57. return bytearray(status, 'utf-8')
  58. elif 'REMOVE_NETWORK all' == self._last_cmd:
  59. #print('mock sock get remove_network_all cmd')
  60. self._network_profiles = self._network_profiles[:]
  61. return b'OK\n'
  62. elif 'REMOVE_NETWORK' == self._last_cmd[:len('REMOVE_NETWORK')]:
  63. #print('mock sock get remove_network cmd')
  64. network_id = int(self._last_cmd.split(' ')[1])
  65. for idx, network in enumerate(self._network_profiles):
  66. if network['id'] == network_id:
  67. del self._network_profiles[idx]
  68. break
  69. return b'OK\n'
  70. elif 'LIST_NETWORKS' == self._last_cmd:
  71. #print('mock sock get list_network cmd')
  72. networks = 'network id / ssid / bssid / flag\n'
  73. for network in self._network_profiles:
  74. networks += "{}\t{}\t{}\t[DISABLED]\n".format(
  75. network['id'], network['ssid'], network.get('bssid', 'None'))
  76. return bytearray(networks, 'utf-8')
  77. elif 'ADD_NETWORK' == self._last_cmd:
  78. if self._network_profiles:
  79. self._network_profiles.sort(key=lambda obj: obj['id'])
  80. network_id = self._network_profiles[-1]['id'] + 1
  81. else:
  82. network_id = 0
  83. network = {}
  84. network['id'] = network_id
  85. self._network_profiles.append(network)
  86. return bytearray(str(network_id), 'utf-8')
  87. elif 'SET_NETWORK' == self._last_cmd[:len('SET_NETWORK')]:
  88. network_id = int(self._last_cmd.split(' ')[1])
  89. field_name = self._last_cmd.split(' ')[2]
  90. val = self._last_cmd.split(' ')[3]
  91. for profile in self._network_profiles:
  92. if profile['id'] == network_id:
  93. network = profile
  94. if field_name == 'ssid':
  95. val = val[1:-1]
  96. network[field_name] = val
  97. return b'OK\n'
  98. elif 'GET_NETWORK' == self._last_cmd[:len('GET_NETWORK')]:
  99. network_id = int(self._last_cmd.split(' ')[1])
  100. field_name = self._last_cmd.split(' ')[2]
  101. for profile in self._network_profiles:
  102. if profile['id'] == network_id:
  103. network = profile
  104. if field_name == 'pairwise':
  105. val = 'CCMP TKIP'
  106. elif field_name == 'ssid':
  107. val = '"' + network[field_name] + '"'
  108. else:
  109. val = network[field_name]
  110. return bytearray(val, 'utf-8')
  111. def send(self, *args, **kwargs):
  112. self._last_cmd = args[0].decode('utf-8')
  113. class Mock:
  114. def __init__(self):
  115. self._dict = {}
  116. def __getattr__(self, field):
  117. return self._dict.get(field, None)
  118. def pywifi_test_patch(test_func):
  119. def core_patch(*args, **kwargs):
  120. os.stat = lambda *args: Mock()
  121. os.listdir = lambda *args: ['wlx000c433243ce']
  122. stat.S_ISSOCK = lambda *args: True
  123. socket.socket = lambda *args: SockMock()
  124. os.remove = lambda *args: True
  125. test_func(*args, **kwargs)
  126. return core_patch
  127. @pywifi_test_patch
  128. def test_interfaces():
  129. wifi = pywifi.PyWiFi()
  130. assert wifi.interfaces()
  131. if platform.system().lower() == 'windows':
  132. assert wifi.interfaces()[0].name() ==\
  133. 'Intel(R) Dual Band Wireless-AC 7260'
  134. elif platform.system().lower() == 'linux':
  135. assert wifi.interfaces()[0].name() == 'wlx000c433243ce'
  136. @pywifi_test_patch
  137. def test_scan():
  138. wifi = pywifi.PyWiFi()
  139. iface = wifi.interfaces()[0]
  140. iface.scan()
  141. time.sleep(5)
  142. bsses = iface.scan_results()
  143. assert bsses
  144. def test_profile_comparison():
  145. profile1 = pywifi.Profile()
  146. profile1.ssid = 'testap'
  147. profile1.auth = const.AUTH_ALG_OPEN
  148. profile1.akm.append(const.AKM_TYPE_WPA2PSK)
  149. profile1.cipher = const.CIPHER_TYPE_CCMP
  150. profile1.key = '12345678'
  151. profile2 = pywifi.Profile()
  152. profile2.ssid = 'testap'
  153. profile2.auth = const.AUTH_ALG_OPEN
  154. profile2.akm.append(const.AKM_TYPE_WPA2PSK)
  155. profile2.cipher = const.CIPHER_TYPE_CCMP
  156. profile2.key = '12345678'
  157. assert profile1 == profile2
  158. profile3 = pywifi.Profile()
  159. profile3.ssid = 'testap'
  160. profile3.auth = const.AUTH_ALG_OPEN
  161. profile3.akm.append(const.AKM_TYPE_WPAPSK)
  162. profile3.cipher = const.CIPHER_TYPE_CCMP
  163. profile3.key = '12345678'
  164. assert profile1 == profile3
  165. @pywifi_test_patch
  166. def test_add_network_profile():
  167. wifi = pywifi.PyWiFi()
  168. iface = wifi.interfaces()[0]
  169. profile = pywifi.Profile()
  170. profile.ssid = 'testap'
  171. profile.auth = const.AUTH_ALG_OPEN
  172. profile.akm.append(const.AKM_TYPE_WPA2PSK)
  173. profile.cipher = const.CIPHER_TYPE_CCMP
  174. profile.key = '12345678'
  175. iface.remove_all_network_profiles()
  176. assert len(iface.network_profiles()) == 0
  177. iface.add_network_profile(profile)
  178. profiles = iface.network_profiles()
  179. assert profiles is not None
  180. assert profiles[0].ssid == "testap"
  181. assert const.AKM_TYPE_WPA2PSK in profiles[0].akm
  182. assert const.AUTH_ALG_OPEN == profiles[0].auth
  183. @pywifi_test_patch
  184. def test_remove_network_profile():
  185. wifi = pywifi.PyWiFi()
  186. iface = wifi.interfaces()[0]
  187. iface.remove_all_network_profiles()
  188. assert len(iface.network_profiles()) == 0
  189. profile1 = pywifi.Profile()
  190. profile1.ssid = 'testap'
  191. profile1.auth = const.AUTH_ALG_OPEN
  192. profile1.akm.append(const.AKM_TYPE_WPA2PSK)
  193. profile1.cipher = const.CIPHER_TYPE_CCMP
  194. profile1.key = '12345678'
  195. iface.add_network_profile(profile1)
  196. profile2 = pywifi.Profile()
  197. profile2.ssid = 'testap2'
  198. profile2.auth = const.AUTH_ALG_OPEN
  199. profile2.akm.append(const.AKM_TYPE_WPA2PSK)
  200. profile2.cipher = const.CIPHER_TYPE_CCMP
  201. profile2.key = '12345678'
  202. iface.add_network_profile(profile2)
  203. profile3 = pywifi.Profile()
  204. profile3.ssid = 'testap3'
  205. profile3.auth = const.AUTH_ALG_OPEN
  206. profile3.akm.append(const.AKM_TYPE_WPAPSK)
  207. profile3.cipher = const.CIPHER_TYPE_TKIP
  208. profile3.key = '12345678'
  209. iface.add_network_profile(profile3)
  210. profiles = iface.network_profiles()
  211. assert len(profiles) == 3
  212. iface.remove_network_profile(profile2)
  213. profiles = iface.network_profiles()
  214. assert len(profiles) == 2
  215. assert profile2 not in profiles
  216. @pywifi_test_patch
  217. def test_status():
  218. wifi = pywifi.PyWiFi()
  219. iface = wifi.interfaces()[0]
  220. iface.disconnect()
  221. assert iface.status() in\
  222. [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
  223. @pywifi_test_patch
  224. def test_connect():
  225. wifi = pywifi.PyWiFi()
  226. iface = wifi.interfaces()[0]
  227. iface.disconnect()
  228. time.sleep(1)
  229. assert iface.status() in\
  230. [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
  231. profile = pywifi.Profile()
  232. profile.ssid = 'testap'
  233. profile.auth = const.AUTH_ALG_OPEN
  234. profile.akm.append(const.AKM_TYPE_WPA2PSK)
  235. profile.cipher = const.CIPHER_TYPE_CCMP
  236. profile.key = '12345678'
  237. iface.remove_all_network_profiles()
  238. tmp_profile = iface.add_network_profile(profile)
  239. iface.connect(tmp_profile)
  240. time.sleep(5)
  241. assert iface.status() == const.IFACE_CONNECTED
  242. iface.disconnect()
  243. time.sleep(1)
  244. assert iface.status() in\
  245. [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
  246. @pywifi_test_patch
  247. def test_connect_open():
  248. wifi = pywifi.PyWiFi()
  249. iface = wifi.interfaces()[0]
  250. iface.disconnect()
  251. time.sleep(1)
  252. assert iface.status() in\
  253. [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
  254. profile = pywifi.Profile()
  255. profile.ssid = 'testap'
  256. profile.auth = const.AUTH_ALG_OPEN
  257. profile.akm.append(const.AKM_TYPE_NONE)
  258. iface.remove_all_network_profiles()
  259. tmp_profile = iface.add_network_profile(profile)
  260. iface.connect(tmp_profile)
  261. time.sleep(5)
  262. assert iface.status() == const.IFACE_CONNECTED
  263. iface.disconnect()
  264. time.sleep(1)
  265. assert iface.status() in\
  266. [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
  267. @pywifi_test_patch
  268. def test_disconnect():
  269. wifi = pywifi.PyWiFi()
  270. iface = wifi.interfaces()[0]
  271. iface.disconnect()
  272. assert iface.status() in\
  273. [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]