Poco API精講之拖動drag_to()

上期回顧:Poco API精講之滑動swipe()


以下基於
python3.8;airtestIDE1.2.13;airtest1.2.4;pocoui1.0.85

注意:Poco框架和Airtest框架很多API是同名的,但使用方法完全不一樣!!!一定不要搞混了,我初學時也經常搞混,這點一定要注意!
具體Poco框架和Airtest框架是什麼關係,可以看之前文章:Airtest Project——UI自動化利器介紹

上期我們講了Poco的滑動swipe(),他是從一個點或元素向另一個點或方向滑動,那麼這裏目標的點或方向基本是定死的。

今天要講的Poco的拖動drag_to(),是從一個元素拖到另一個元素,這樣我們就不用關心寫死的目標了,甚至這2個元素可以是在屏幕任意位置來回變的,我不關心你在哪,不管你在哪,我的目的就是從一個拖到另一個。不過drag_to()同時也支持拖向某個點。

drag_to(target, duration=2.0)
將一個元素拖到另一個元素位置

參數:
target - 一個元素對象或屏幕相對座標
duration - 滑動時長,默認2秒

異常:
PocoNoSuchNodeException:元素不存在

源碼解析:

# 源碼位置:your_python_path\site-packages\poco\proxy.py
    def drag_to(self, target, duration=2.0):
        try:
            duration = float(duration)
        except ValueError:
            raise ValueError('Argument `duration` should be <float>. Got {}'.format(repr(duration)))

        if type(target) in (list, tuple):
            target_pos = target
        else:
            target_pos = target.get_position()
        origin_pos = self.get_position()
        dir_ = [target_pos[0] - origin_pos[0], target_pos[1] - origin_pos[1]]
        return self.swipe(dir_, duration=duration)

第1個代碼塊是確保duration參數的合法性

if type(target) in (list, tuple):
    target_pos = target
else:
    target_pos = target.get_position()

正如上面說的drag_to也支持拖到一個屏幕相對座標點,如果判斷target是list或tuple類似,直接將座標點賦值給目標變量。
否則target就應該是一個元素對象,通過get_position()獲取到其中心點的屏幕相對座標,賦值給目標變量。

origin_pos = self.get_position()

獲取元素自身座標點爲起始座標。

dir_ = [target_pos[0] - origin_pos[0], target_pos[1] - origin_pos[1]]

將目標座標減去起始座標,給下面的swipe計算出滑動的向量。

return self.swipe(dir_, duration=duration)

所以我們看到了,即使你是從一個元素拖到另一個元素,但底層還是通過swipe來實現的。

示例:

from airtest.core.api import *
from poco.drivers.unity3d import UnityPoco

auto_setup(__file__)

poco = UnityPoco()

# 將元素拖到屏幕左上角
poco("測試工程師小站").drag_to([0.1,0.1])

# 下面就是官方最經典的案例了,將官方遊戲demo中的所有星星拖到貝殼上
shell = poco('shell')
for star in poco('plays').offspring('star'):
    star.drag_to(shell)

 

上面示例代碼只寫了最核心的

圖片

另外drag_to()還有一個使用小技巧,能夠將元素自拖,即從元素一端拖到另一端,比如一個滾動條,從下往上拖

from airtest.core.api import *
from poco.drivers.unity3d import UnityPoco

auto_setup(__file__)

poco = UnityPoco()

scrollView = poco(type='ScollView')
scrollView.focus([0.5, 0.8]).drag_to(scrollView.focus([0.5, 0.2]))

之前我們講過:Poco API精講之focus()

focus後相當於複製了一個新的元素,所以scrollView.focus([0.5, 0.8])scrollView.focus([0.5, 0.2])相當於2個獨立的元素(1個錨在元素上方,1個錨在元素下方),雖然本質上是一個元素,只是錨點不一樣罷了。

 

---------------------------------------------------------------------------------

關注微信公衆號即可在手機上查閱,並可接收更多測試分享~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章