如何远程调用Appium Server
参考代码:
# coding=utf-8
import os
import sys
from datetime import datetime
from appium import webdriver
from Appium import Appium
import time
import re
from datetime import datetime
from clicmdfromwindows import clicmdfromwindows
class AndroidOnNexus:
def __init__(self):
# print os.getcwd()
# print os.path.dirname(__file__)
self.desired_caps = {}
self.desired_caps['platformName'] = 'Android'
self.desired_caps['platformVersion'] = '5.0.1'
self.desired_caps['deviceName'] = 'Nexus_5_API_21_x86'
# desired_caps['app']=''
self.command_url = 'http://localhost:4723/wd/hub'
self.driver = None
self.iperf_server_log = None
# android=webself.driver.DesiredCapabilities.ANDROID
def ConnSSID(self, ssid, key, expect=True):
"""
Connect SSID on Android
"""
print '\nBegin Connect SSID on ASUS Android...'
ssid = ssid
key = key
expect = expect
print ssid
print key
print expect
self._OpenWiFi()
ssid_elem = self._ScanSSID(ssid)
try:
ssid_elem.click()
try:
forget = self.driver.find_element_by_id('android:id/button3')
except Exception, e:
forget = None
if forget:
forget.click()
for i in range(5):
self.driver.swipe(200, 200 , 200, 1000, 2000)
time.sleep(10)
ssid_elem = self._ScanSSID(ssid)
ssid_elem.click()
print 'Input Password'
self.driver.save_screenshot(os.path.join(os.getcwd(), 'Input_Password0.jpg'))
input_pwd = self.driver.find_element_by_id('com.android.settings:id/password')
input_pwd.send_keys(key)
self.driver.find_element_by_id('com.android.settings:id/show_password').click()
self.driver.back()
self.driver.save_screenshot(os.path.join(os.getcwd(), 'Input_Password1.jpg'))
time.sleep(1)
self.driver.find_element_by_id('android:id/button1').click()
print 'Check Connect status'
# Check Connect Status
time1 = datetime.now()
status = None
for i in range(30):
status = self.driver.find_element_by_id('android:id/summary').text
print status
if status == 'Connected':
time2 = datetime.now()
ConnectSpendTime = (time2 - time1).seconds
print 'AT_INFO : Connect Spend Time ' + str(ConnectSpendTime) + ' seconds!'
break
else:
time.sleep(1)
if status:
print 'AT_INFO : Connect SSID ' + ssid + ' Success!'
else:
Appium.raiseError('AT_ERROR : Connect SSID ' + ssid + ' FAIL!')
# Get Status Info
elem = self.driver.find_element_by_id('android:id/title')
Info = self.getConnInfo(element=elem)
Info['ConnectSpendTime'] = ConnectSpendTime
print Info
time.sleep(5)
print 'AT_INFO : Connect SSID ' + ssid + ' Success!'
except Exception, e:
print e
Appium.raiseError('AT_ERROR : Connect SSID ' + ssid + ' FAIL!')
finally:
self._quit()
def _OpenWiFi(self):
"""
Open Wi-Fi
"""
self.desired_caps['appPackage'] = 'com.android.settings'
self.desired_caps['appActivity'] = 'Settings'
try:
self.driver = webdriver.Remote(self.command_url, self.desired_caps)
self.driver.implicitly_wait(10)
# click wifi
self.driver.save_screenshot(os.path.join(os.getcwd(), 'Settings.jpg'))
elem = self.driver.find_elements_by_id("android:id/title")
for e in elem:
try:
aaa = e.text.encode("GBK", 'ignore')
except Exception, c:
print c
m = re.match(r'Wi', aaa)
if m:
e.click()
time.sleep(2)
break
# open wifi switch
wifi_switch = self.driver.find_element_by_class_name('android.widget.Switch')
if wifi_switch.text not in ['On', 'on', 'ON']:
wifi_switch.click()
time.sleep(2)
self.driver.save_screenshot(os.path.join(os.getcwd(), 'Wi-Fi.jpg'))
except Exception, e:
self._quit()
Appium.raiseError('AT_ERROR : Open Wi-Fi Setting FAIL!')
def _ScanSSID(self, ssid):
"""
Scan SSID
"""
scan_result = False
ssid_elem = None
# win_height = self.driver.get_window_size()['height']
# print win_height
# start_y = win_height - 5
for i in range(10):
self.driver.save_screenshot(os.path.join(os.getcwd(), 'SSIDs_On_Page_' + str(int(i) + 1) + '.jpg'))
elem = self.driver.find_elements_by_id('android:id/title')
for e in elem:
print e.text
if e.text == ssid:
scan_result = True
ssid_elem = e
print 'AT_INFO : Scan SSID ' + ssid + ' PASS!'
break
if scan_result:
break
else:
self.driver.swipe(200, 1000 , 200, 200, 3000)
if not scan_result:
self._quit()
Appium.raiseError('AT_ERROR : Scan SSID ' + ssid + ' FAIL!')
else:
return ssid_elem
def getConnInfo(self, ssid=None, element=None):
"""
Get Connect Infomation
"""
print '\nBegin Get Wi-Fi Connect Info...'
ssid = ssid
elem = element
Info = {}
try:
if ssid and not element:
self._OpenWiFi()
elem = self._ScanSSID(ssid)
elif element:
elem = elem
else:
pass
elem.click()
infos = self.driver.find_elements_by_class_name('android.widget.TextView')
length = len(infos)
for i in range(1, length, 2):
Info[str(infos[i].text)] = str(infos[i + 1].text)
print Info
print 'AT_INFO : Get Wi-Fi Connect Info Success!'
except Exception, e:
print e
Appium.raiseError('AT_ERROR : Get Wi-Fi Connect Info FAIL!')
finally:
self._quit()
return Info
def pingtesting(self, dstIP, expect=True):
"""
Do ping test on mobile Devices via App.
"""
print 'Begin do ping test'
self.desired_caps['udid'] = '015d2ebeae24020c'
self.desired_caps['appPackage'] = 'com.yqwireless'
self.desired_caps['appActivity'] = '.MainActivity'
self.driver = webdriver.Remote(self.command_url, self.desired_caps)
print "start remote appium server"
try:
time.sleep(5)
self.driver.back()
time.sleep(5)
print "click clear button"
clearButton = self.driver.find_element_by_id('com.yqwireless:id/main_clear')
clearButton.click()
print "input dstIP"
input_url = self.driver.find_element_by_id('com.yqwireless:id/main_input_url')
input_url.clear()
input_url.send_keys(dstIP)
startButton = self.driver.find_element_by_id('com.yqwireless:id/main_start_btn')
startButton.click()
time.sleep(5)
testResult = self.driver.find_element_by_id('com.yqwireless:id/main_show_text')
testResultLog=testResult.get_attribute("text")
print testResultLog
if testResultLog:
testResultLog = testResultLog.splitlines()
print testResultLog
print "Check the Ping Test Result:"
for eachline in testResultLog:
match = re.search(r'rtt min/avg/max/mdev =', eachline)
if match:
print eachline
print "\nAT_INFO: Ping Test PASS!"
else:
Appium.raiseError("AT_ERROR : Ping Test FAIL!")
except Exception, e:
print e
Appium.raiseError('AT_ERROR : Ping Test FAIL!')
finally:
self._quit()
def speedtesting(self):
"""
"""
print '\nBegin Speed Test...'
self.desired_caps['appPackage'] = 'org.mozilla.firefox'
self.desired_caps['appActivity'] = '.App'
try:
self.driver = webdriver.Remote(self.command_url, self.desired_caps)
elem = self.driver.find_element_by_id('org.mozilla.firefox:id/url_bar_entry')
elem.click()
elem.send_keys('http://192.168.10.108/mini/index-php.html')
self.driver.press_keycode(66)
time.sleep(5)
self.driver.swipe(383, 650 , 385, 650, 0)
time.sleep(10)
print 'Find plug-in'
print 'Begin Test'
self.driver.swipe(383, 648 , 385, 648, 0)
time.sleep(50)
self.driver.save_screenshot(os.path.join(os.getcwd(), 'SpeedTest.jpg'))
print str(self.driver.page_source)
print 'AT_INFO : Speed Test Finished!'
except Exception, e:
print e
Appium.raiseError('AT_ERROR : Speed Test FAIL!')
finally:
self._quit()
def _startiperfserver(self, port='', protocol='TCP'):
"""
"""
print 'Begin start iperf test'
cmd = 'iperf -s -p ' + str(port)
if str(protocol).upper() == 'UDP':
cmd += ' -u'
file1 = os.path.join(os.getcwd(), 'iperf_process.log')
obj = clicmdfromwindows()
obj.sshclifromwindows('', 'killall iperf')
obj.sshclifromwindows('', 'nohup iperf -s -p ' + str(port) + ' -f M > ' + self.iperf_server_log + ' 2>&1 &')
obj.sshclifromwindows(file1, 'ps aux |grep -v grep |grep iperf')
def _stopiperftest(self):
print 'Begin stop iperf test'
obj = clicmdfromwindows()
obj.sshclifromwindows('', 'sleep 2;sync;killall iperf')
def _getiperfresult(self):
up = ""
down = ""
self._stopiperftest()
print 'Begin Parse iperf test result'
file = os.path.join(os.getcwd(), os.path.basename(self.iperf_server_log))
obj = clicmdfromwindows()
severlog = obj.sshclifromwindows(file, 'cat ' + self.iperf_server_log)
m = re.findall(r'(\d+\.*\d+) +MBytes/sec', severlog)
if m:
up = str(m[0])
down = str(m[1])
else:
Appium.raiseError('AT_ERROR : Iperf server result parse FAIL!')
print 'up :', up, 'MBytes/sec'
print 'down:', down, 'MBytes/sec'
return up, down
def iperftest(self, port='', protocol='TCP', iperf_server_log=None):
"""
"""
if not iperf_server_log:
self.iperf_server_log = '/tmp/iperf_server.log'
else:
self.iperf_server_log = iperf_server_log
self._startiperfserver(port, protocol)
returncode = False
self.desired_caps['appPackage'] = 'com.magicandroidapps.iperf'
self.desired_caps['appActivity'] = '.iperf'
current_element = None
try:
self.driver = webdriver.Remote(self.command_url, self.desired_caps)
# current_element = 'android.widget.ImageButton'
# print current_element
# elem = self.driver.find_element_by_class_name(current_element)
# elem.click()
# time.sleep(1)
#
# current_element = 'android:id/title'
# print current_element
# elems = self.driver.find_elements_by_id(current_element)
# print elems
# for elem in elems:
# print elem
# if elem.text == 'Clear':
# elem.click()
# break
# time.sleep(1)
current_element = 'com.magicandroidapps.iperf:id/cmdlineargs'
elem = self.driver.find_element_by_id(current_element)
elem.clear()
cmd = 'iperf -c 192.168.55.254 -p ' + str(port) + ' -d -f M'
print cmd
elem.send_keys(cmd)
self.driver.back()
print 'Click StartstopButton to On'
current_element = 'com.magicandroidapps.iperf:id/startstopButton'
print current_element
elem = self.driver.find_element_by_id(current_element)
if elem.text == 'OFF':
elem.click()
else:
elem.click()
time.sleep(1)
elem.click()
time.sleep(1)
try:
assert elem.text == 'ON'
except AssertionError, args:
Appium.raiseError('AT_ERROR : StartStopButton is NOT NO!')
for i in range(6):
time.sleep(10)
current_element = 'com.magicandroidapps.iperf:id/outputwindow'
elem = self.driver.find_element_by_id(current_element)
output = str(elem.text)
print '^' * 100
print 'AT_INFO : iperf client test result'
print output
print '^' * 100
if output.find('connect failed') > -1:
Appium.raiseError('AT_ERROR : Iperf Test FAIL!')
print 'Check StartstopButton Status'
current_element = 'com.magicandroidapps.iperf:id/startstopButton'
print current_element
elem = self.driver.find_element_by_id(current_element).text
print elem
if elem == 'OFF':
if output.find('Bytes/sec') > -1:
returncode = True
break
elif output.find('Bytes/sec') > -1:
returncode = True
break
if not returncode:
Appium.raiseError('AT_ERROR : Iperf test Error!')
print returncode
# Get iperf result
up, down = self._getiperfresult()
print 'AT_INFO : Iperf Test Finished!'
return up, down
except Exception, e:
print current_element
print e
Appium.raiseError('AT_ERROR : Iperf Test FAIL!')
finally:
self._quit()
def _quit(self):
try:
if self.driver:
self.driver.quit()
pass
else:
pass
except Exception, e:
print e
return True
if __name__ == '__main__':
android = AndroidOnNexus()
# android.ConnSSID('TELUS0079-2.4G', '1234567890')
# android.getConnInfo('TELUS0079-2.4G')
android.iperftest(port=20000)
self.command_url = 'http://localhost:4723/wd/hub'
将localhost 替换成为 appium server的ip就可以了。