1.iOS手机的滑动

相关代码

#python
class IOS(Device):...@property#获取屏幕的尺寸def display_info(self):if not self._size['width'] or not self._size['height']:self.snapshot()return {'width': self._size['width'], 'height': self._size['height'], 'orientation': self.orientation,\'physical_width': self._size['width'], 'physical_height': self._size['height']}...#滑动def swipe(self, fpos, tpos, duration=0.5, steps=5, fingers=1):# trans pos of swipefx, fy = self._touch_point_by_orientation(fpos)tx, ty = self._touch_point_by_orientation(tpos)self.session.swipe(fx * self._touch_factor, fy * self._touch_factor,tx * self._touch_factor, ty * self._touch_factor, duration)...

1.1直接使用IOS类进行滑动

#python
test=IOS()
a=test.display_info
for i in a:print(i,a[i])
fpos=(600,2000)
tpos=(600,1000)
test.swipe(fpos,tpos)
#log
[Start running..]
save log in '/var/folders/c7/kh0qq_r10kb7_7fhdsgmrgbh0000gn/T/AirtestIDE/scripts/c6f4a07d9c8371543fcf247becedb4ff'
width
1125
height
2436
orientation
PORTRAIT
physical_width
1125
physical_height
2436
----------------------------------------------------------------------
Ran 1 test in 1.628sOK
[Finished]============================================================

1.2编写一个类根据输入的比例值实现滑动

# -*- encoding=utf8 -*-
__author__ = "chenshanju"
#Base类实现屏幕的滑动
from airtest.core.api import *
from airtest.core.ios import IOS
auto_setup(__file__)
class Base():def __init__(self):test1=IOS()self.width=test1.display_info['physical_width']self.height=test1.display_info['physical_height']self.left_point=(0.2*self.width,0.5*self.height)self.right_point=(0.8*self.width,0.5*self.height)self.up_point=(0.5*self.width,0.25*self.height)self.down_point=(0.5*self.width,0.75*self.height)def swipe_to_left(self):swipe(self.right_point,self.left_point)print(self.right_point,self.left_point)def swipe_to_right(self):swipe(self.left_point,self.right_point)print(self.left_point,self.right_point)def swipe_to_up(self):swipe(self.down_point,self.up_point)print(self.down_point,self.up_point)def swipe_to_down(self):swipe(self.up_point,self.down_point)print(self.up_point,self.down_point)
#测试代码,要删掉
test=Base()
print("start")
test.swipe_to_up()
test.swipe_to_left()
print("end")
============================================================[Start running..]
save log in '/var/folders/c7/kh0qq_r10kb7_7fhdsgmrgbh0000gn/T/AirtestIDE/scripts/c6f4a07d9c8371543fcf247becedb4ff'
start
(562.5, 1827.0)
(562.5, 609.0)
(900.0, 1218.0)
(225.0, 1218.0)
end
----------------------------------------------------------------------
Ran 1 test in 3.406sOK
[Finished]============================================================

airtest ios类源代码

#!  /usr/bin/env  python
#  -*-  coding:  utf-8  -*-import  requests
import  six
import  time
import  json
import  base64
import  wda
import  chenyiif  six.PY3:from  urllib.parse  import  urljoin
else:from  urlparse  import  urljoinfrom  airtest  import  aircv
from  airtest.core.device  import  Device
from  airtest.core.ios.constant  import  CAP_METHOD,  TOUCH_METHOD,  IME_METHOD
from  airtest.core.ios.rotation  import  XYTransformer,  RotationWatcher
from  airtest.core.ios.fake_minitouch  import  fakeMiniTouch
from  airtest.core.ios.instruct_helper  import  InstructHelper
from  airtest.utils.logger  import  get_logger#  roatations  of  ios
from  wda  import  LANDSCAPE,  PORTRAIT,  LANDSCAPE_RIGHT,  PORTRAIT_UPSIDEDOWN
from  wda  import  WDAErrorlogger  =  get_logger(__name__)
DEFAULT_ADDR  =  "http://localhost:8100/"#  retry  when  saved  session  failed
def  retry_session(func):def  wrapper(self,  *args,  **kwargs):try:return  func(self,  *args,  **kwargs)except  WDAError  as  err:#  6  :  Session  does  not  existif  err.status  ==  6:self._fetchNewSession()return  func(self,  *args,  **kwargs)else:raise  errreturn  wrapperclass  IOS(Device):"""ios  client#  befor  this  you  have  to  run  WebDriverAgent#  xcodebuild  -project  path/to/WebDriverAgent.xcodeproj  -scheme  WebDriverAgentRunner  -destination  "id=$(idevice_id  -l)"  test#  iproxy  $port  8100  $udid"""def  __init__(self,  addr=DEFAULT_ADDR):super(IOS,  self).__init__()#  if  none  or  empty,  use  default  addrself.addr  =  addr  or  DEFAULT_ADDR#  fit  wda  format,  make  url  start  with  http://if  not  self.addr.startswith("http://"):self.addr  =  "http://"  +  addr"""here  now  use  these  supported  cap  touch  and  ime  method"""self.cap_method  =  CAP_METHOD.WDACAPself.touch_method  =  TOUCH_METHOD.WDATOUCHself.ime_method  =  IME_METHOD.WDAIME#  wda  driver,  use  to  home,  start  app#  init  wda  session,  updata  when  start  app#  use  to  click/swipe/close  app/get  wda  sizewda.DEBUG  =  Falseself.driver  =  wda.Client(self.addr)#  record  device's  widthself._size  =  {'width':  None,  'height':  None}self._touch_factor  =  0.5self._last_orientation  =  Noneself.defaultSession  =  None#  start  up  RotationWatcher  with  default  sessionself.rotation_watcher  =  RotationWatcher(self)#  fake  minitouch  to  simulate  swipeself.minitouch  =  fakeMiniTouch(self)#  helper  of  run  process  like  iproxyself.instruct_helper  =  InstructHelper()@propertydef  uuid(self):return  self.addr@propertydef  session(self):if  not  self.defaultSession:self.defaultSession  =  self.driver.session()return  self.defaultSessiondef  _fetchNewSession(self):self.defaultSession  =  self.driver.sess ion()@retry_sessiondef window_size(self):"""return window sizenamedtuple:Size(wide , hight)"""return self.session.window_size()@property@retry_sessiondef orientation(self):"""return device oritantation statusin  LANDSACPE POR"""return self.session.orientation@propertydef display_info(self):if not self._size['width'] or not self._size['height']:self.snapshot()return {'width': self._size['width'], 'height': self._size['height'], 'orientation': self.orientation,\'physical_width': self._size['width'], 'physical_height': self._size['height']}def get_current_resolution(self):w, h = self.display_info["width"], self.display_info["height"]if self.display_info["orientation"] in [LANDSCAPE, LANDSCAPE_RIGHT]:w, h = h, wreturn w, hdef home(self):return self.driver.home()def _neo_wda_screenshot(self):"""this is almost same as wda implementation, but without png header check,as response data is now jpg format in mid quality"""value = self.driver.http.get('screenshot').valueraw_value = base64.b64decode(value)return raw_valuedef snapshot(self, filename=None, strType=False, ensure_orientation=True):"""take snapshotfilename: save screenshot to filename"""data = Noneif self.cap_method == CAP_METHOD.MINICAP:raise NotImplementedErrorelif self.cap_method == CAP_METHOD.MINICAP_STREAM:raise NotImplementedErrorelif self.cap_method == CAP_METHOD.WDACAP:data = self._neo_wda_screenshot()  # wda 截图不用考虑朝向if strType:if filename:with open(filename, 'wb') as f:f.write(data)return data# output cv2 objecttry:screen = aircv.utils.string_2_img(data)except:# may be black/locked screen or other reason, print exc for debuggingimport tracebacktraceback.print_exc()return Nonenow_orientation = self.orientation# ensure the orientation is rightif ensure_orientation and now_orientation in [LANDSCAPE, LANDSCAPE_RIGHT]:# minicap screenshots are different for various sdk_versionif self.cap_method in (CAP_METHOD.MINICAP, CAP_METHOD.MINICAP_STREAM) and self.sdk_version <= 16:h, w = screen.shape[:2]  # cvshape是高度在前面!!!!if w < h:  # 当前是横屏,但是图片是竖的,则旋转,针对sdk<=16的机器screen = aircv.rotate(screen, self.display_info["orientation"] * 90, clockwise=False)# wda 截图是要根据orientation旋转elif self.cap_method == CAP_METHOD.WDACAP:# seems need to rotate in opencv opencv-contrib-python==3.2.0.7screen = aircv.rotate(screen, 90, clockwise=(now_orientation == LANDSCAPE_RIGHT))# readed screen sizeh, w = screen.shape[:2]# save last res for portraitif now_orientation in [LANDSCAPE, LANDSCAPE_RIGHT]:self._size['height'] = wself._size['width'] = helse:self._size['height'] = hself._size['width'] = wwinw, winh = self.window_size()self._touch_factor = float(winh) / float(h)# save as file if neededif filename:aircv.imwrite(filename, screen)return screen@retry_sessiondef touch(self, pos, duration=0.01):# trans pos of clickpos = self._touch_point_by_orientation(pos)# scale touch postionx, y = pos[0] * self._touch_factor, pos[1] * self._touch_factorif duration >= 0.5:self.session.tap_hold(x, y, duration)else:self.session.tap(x, y)def double_click(self, pos):# trans pos of clickpos = self._touch_point_by_orientation(pos)x, y = pos[0] * self._touch_factor, pos[1] * self._touch_factorself.session.double_tap(x, y)def swipe(self, fpos, tpos, duration=0.5, steps=5, fingers=1):# trans pos of swipefx, fy = self._touch_point_by_orientation(fpos)tx, ty = self._touch_point_by_orientation(tpos)self.session.swipe(fx * self._touch_factor, fy * self._touch_factor,tx * self._touch_factor, ty * self._touch_factor, duration)def keyevent(self, keys):"""just use as home event"""if keys not in ['HOME', 'home', 'Home']:raise NotImplementedErrorself.home()@retry_sessiondef text(self, text, enter=True):"""bug in wda for now"""if enter:text += '\n'self.session.send_keys(text)def install_app(self, uri, package):"""curl -X POST $JSON_HEADER \-d "{\"desiredCapabilities\":{\"bundleId\":\"com.apple.mobilesafari\", \"app\":\"[host_path]/magicapp.app\"}}" \$DEVICE_URL/sessionhttps://github.com/facebook/WebDriverAgent/wiki/Queries"""raise NotImplementedErrordef start_app(self, package, activity=None):self.defaultSession = Noneself.driver.session(package)def stop_app(self, package):self.driver.session().close()def get_ip_address(self):"""get ip address from webDriverAgentReturns:raise if no IP address has been found, otherwise return the IP address"""return self.driver.status()['ios']['ip']def device_status(self):"""show status return by webDriverAgentReturn dicts of infos"""return self.driver.status()def _touch_point_by_orientation(self, tuple_xy):"""Convert image coordinates to physical display coordinates, the arbitrary point (origin) is upper left cornerof the device physical displayArgs:tuple_xy: image coordinates (x, y)Returns:"""x, y = tuple_xy# use correct w and h due to now orientation# _size 只对应竖直时候长宽now_orientation = self.orientationif now_orientation in [PORTRAIT, PORTRAIT_UPSIDEDOWN]:width, height = self._size['width'], self._size["height"]else:height, width = self._size['width'], self._size["height"]# check if not get screensize when touchingif not width or not height:# use snapshot to get current resulutonself.snapshot()x, y = XYTransformer.up_2_ori((x, y),(width, height),now_orientation)return x, ydef _check_orientation_change(self):passif __name__ == "__main__":start = time.time()ios = IOS("http://10.254.51.239:8100")ios.snapshot()# ios.touch((242 * 2 + 10, 484 * 2 + 20))# ios.start_app("com.tencent.xin")ios.home()ios.start_app('com.apple.mobilesafari')ios.touch((88, 88))ios.stop_app('com.apple.mobilesafari')ios.swipe((100, 100), (800, 100))print(ios.device_status())print(ios.get_ip_address())

转载于:https://www.cnblogs.com/csj2018/p/9699832.html

Air test ios类使用相关推荐

  1. 与Xcode相比Adobe AIR开发iOS的优势和局限

    来自:http://www.zhihu.com/question/20001972/answer/15572624 AIR的优势 AIR的优势其实就是Flash或者ActionScript语言的优势. ...

  2. [air for ios] 三小时开发一个iOS飞行射击游戏

    [air for ios] 三小时开发一个iOS飞行射击游戏 http://www.badyoo.com/index.php/2012/07/04/158/index.html 2012-07-04 ...

  3. 与Xcode比照Adobe AIR开发iOS的优势和局限

    AIR的优势 AIR的优势其实就是Flash或者ActionScript语言的优势.这些优势大家已经在互联网上看过许多了,我还是啰嗦一下: 1. 优秀的2D性能和渲染机制 网络上关于Flash性能底下 ...

  4. AIR for IOS开发问题小结

    昨天终于成功地向APP STORE提交了应用,个人感觉用AIR做IOS开发就是个坑啊.出了问题之后,问苹果的技术支持,人家说"对于非XCODE环境下开发及发布所造成的问题我们在资料库中无法找 ...

  5. 分享用Adobe Air向iOS移植游戏的经验

    分享用Adobe Air向iOS移植游戏的经验 http://gamerboom.com/archives/47931 发布时间:2012-02-21 17:04:42 Tags:Adobe Air, ...

  6. flash air for ios 静音开关

    flash air for ios 静音开关 SoundMixer.audioPlaybackMode = AudioPlaybackMode.AMBIENT; 加上这句,静音开关就有效了!

  7. 从零开始学C++之IO流类库(四):输出流格式化(以操纵子方式格式化,以ios类成员函数方式格式化)

    一.以操纵子方式格式化 数据输入输出的格式控制使用系统头文件<iomanip>中提供的操纵符.把它们作为插入操作符<<的输出对象即可.如setiosflags.setw.set ...

  8. (转)利用AIR的ServerSocket类让 AIR 做socket服务器

    自:http://luoke920.iteye.com/blog/1161549 新的air sdk 新增了 ServerSocket类, 利用它我们做一些简单的局域网应用,比如小型的办公聊天软件,以 ...

  9. iOS类对象的初始化+initialize

    简介 在iOS中,对象可分为类对象和实例对象,实例对象即我们平时alloc init初始化的一个具体的对象,实例对象所属的类,称为类对象.类对象.实例对象 +initialize 是一个类方法,在iO ...

最新文章

  1. 网络工程师考试部分技术要点
  2. linux指定查看文件目录,【Linux】查看指定目录下的每个文件或目录的大小
  3. WebView 文档 翻译
  4. 查看电脑boot mode方式
  5. 豪掷197亿美元!微软收购Siri背后的语音技术研发公司
  6. 扑克牌大小的充电宝,你有吗?
  7. 每日英语阅读(五十四)
  8. 坦克世界怎么显示服务器准心,坦克世界设置方法 坦克世界如何设置图像
  9. 二. Binding 详解
  10. 中国近12个月以来的搜索引擎市场份额
  11. Drawable的setBounds方法
  12. [转贴]民国记者有多牛:揭黑损人骂街是常事
  13. 什么事件必须要我王二狗来处理?
  14. java 常用四舍五入保留小数点后两位方法
  15. teamviewer 使用
  16. QueryDSL 关于Q类找不到的问题
  17. the little scheme 代码
  18. js-sha1实现SHA1加密
  19. 成都5日--成都-都江堰-青城山-西岭雪山1116
  20. 中国流动人口数据(cmds)

热门文章

  1. 247 中心对称数 II
  2. 使用PowerDesigner反向生成数据模型
  3. 考研路上的那些一战二战三战成功与失败的故事系列之一
  4. 深入理解Android相机体系结构之二
  5. cpm、cpc、cps和cpa分别是什么意思
  6. 徐志果:创业就是遇见更好的自己(我的成长之路)
  7. VR虚拟现实培训解决方案
  8. 《Effective Python 编写高质量Python代码的59个有效方法》读书笔记
  9. Google体系地图纠偏算法
  10. 闲聊2022卡塔尔世界杯