How to use element.flick method in Appium

Best JavaScript code snippet using appium

_api.js

Source:_api.js Github

copy

Full Screen

1// QT4i-Instruments端-JavaScript-API2(function($) {3 UIAElementsCache = function() {4 this.caches = {};5 this.id = 0;6 this.append(UIATarget.localTarget().frontMostApp());7 };8 UIAElementsCache.prototype = {9 release_all : function() {10 this.caches = {};11 },12 release_invalid : function() {13 //for (var id in this.caches) {14 // if (!this.caches[id].isValid()) {15 // delete this.caches[id];16 // };17 //};18 },19 release : function(id) {20 //var element = this.caches[id];21 //if (!element.isValid()) {22 // delete this.caches[id];23 //};24 },25 append : function(element) {26 if (element == null || element.toString() == "[object UIAElementNil]") {27 return undefined;28 }29 var id = (this.id += 1);30 this.caches[id] = element;31 return id;32 },33 append_elements : function(elements) {34 var ids = new Array();35 for (var i = 0; i < elements.length; i++) {36 ids.push(this.append(elements[i]));37 };38 return ids;39 },40 set : function(id, element) {41 if (this.caches[id]) {42 this.caches[id] = element;43 return true;44 };45 return false;46 },47 get : function(id) {48 this.set(1, UIATarget.localTarget().frontMostApp());49 if ( typeof id == 'number') {50 var element = this.caches[id];51 if (element) {52 //if (element.isValid()) {53 return element;54 //} else {55 // this.release(id);56 //};57 };58 };59 if ( typeof id == 'string' && new RegExp(/^\/classname *\= *(\'|\")\w+(\'|\").*$/i).test(id)) {60 var element = $.QPath(id).findElement(0);61 if (element) {62 return element;63 };64 throw new Error("element not found: " + id);65 };66 throw new Error("element id is invalid: " + id);67 }68 };69})($);70// -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*-71(function($) {72 var uia_elements_cache = new UIAElementsCache();73 var switch_locator = function(strategy, locator) {74 switch(strategy.toLocaleLowerCase()) {75 case 'qpath':76 return $.QPath(locator);77 };78 };79 var last_alert_msg = null;80 var flag_alert_auto_handled = Environment.flag_alert_auto_handled ? Environment.flag_alert_auto_handled : false;81 var rules_of_alert_auto_handle = Environment.rules_of_alert_auto_handle ? Environment.rules_of_alert_auto_handle : new Array();82 UIATarget.onAlert = function(alert) {83 alert.logElementTreeExt();84 $.log("enter onAlert flag_alert_auto_handled: "+$.str.objectToString(flag_alert_auto_handled))85 var texts = alert.getAllTexts();86 last_alert_msg = texts;87 var buttons = [];88 buttons = alert.getElementsByClassName('^UIAButton$');89 if (buttons.length == 0) {90 buttons = alert.getElementsByClassName('^UIACollectionCell$');91 };92 if (buttons.length == 0) {93 buttons = alert.getElementsByClassName('^UIATableCell$');94 };95 for (var rule_i = 0; rule_i < rules_of_alert_auto_handle.length; rule_i++) {96 var rule = rules_of_alert_auto_handle[rule_i];97 for (var text_i = 0; text_i < texts.length; text_i++) {98 var text = texts[text_i];99 if (rule.message_text == text || new RegExp(rule.message_text).test(text)) {100 if (rule.button_text) {101 for (var button_i = 0; button_i < buttons.length; button_i++) {102 var button = buttons[button_i];103 var button_texts = button.getAllTexts();104 for (var button_text_i = 0; button_text_i < button_texts.length; button_text_i++) {105 var button_text = button_texts[button_text_i];106 if (rule.button_text == button_text || new RegExp(rule.button_text).test(button_text)) {107 button.tap();108 //for(var delay_i=0; delay_i<30; delay_i++){109 // UIATarget.localTarget().delay(0.1);110 // if (alert.isValid()==false){111 // return true;112 // };113 //};114 $.log("onAlert double matched: "+$.str.objectToString(flag_alert_auto_handled))115 return true;116 };117 };118 };119 };120 $.log("onAlert single matched: "+$.str.objectToString(flag_alert_auto_handled))121 return true;122 };123 };124 };125 $.log("onAlert no matched: "+$.str.objectToString(flag_alert_auto_handled))126 return flag_alert_auto_handled;127 };128 // -*- -*- -*- -*- -*- -*-129 api = {130 'DoNotReturn' : encodeURIComponent("<<<[[[DoNotReturn]]]>>>"),131 // -*- -*- -*- -*- -*- -*-132 'uia.release' : function(cmd_id) {133 /**134 * 终止并退出Driver135 * Returns136 * 'released' - 终止完毕137 */138 return bootstrap.release();139 },140 'uia.set_cmd_fetch_delegate_timeout' : function(cmd_id, seconds) {141 /**142 * 设置cmd_fetch_delegate的超时值143 * Paramaters:144 * seconds - 秒145 */146 var seconds = parseInt(seconds);147 if (seconds > 0) {148 Environment.cmd_fetch_delegate_timeout = seconds;149 };150 },151 'uia.get_cmd_fetch_delegate_timeout' : function(cmd_id) {152 /**153 * 获取cmd_fetch_delegate的超时值154 * Returns155 * seconds - 秒156 */157 return Environment.cmd_fetch_delegate_timeout;158 },159 'uia.uia_elements_cache.release_all' : function(cmd_id) {160 /**161 * 清空所有的elements的缓存(异常时会自动清理,element无效时会自动清理)162 */163 uia_elements_cache.release_all();164 },165 'uia.uia_elements_cache.release_invalid' : function(cmd_id) {166 /**167 * 清空无效的element的缓存(异常时会自动清理,element无效时会自动清理)168 */169 uia_elements_cache.release_invalid();170 },171 'uia.uia_elements_cache.release_element' : function(cmd_id, id) {172 /**173 * 清理指定element的缓存174 * Paramaters:175 * id - element的id176 */177 uia_elements_cache.release(id);178 },179 'uia.front_most_app' : function(cmd_id) {180 return uia_elements_cache.append(UIATarget.localTarget().frontMostApp());181 },182 // -*- -*- -*- -*- -*- -*-183 'uia.element.function' : function(cmd_id, id, func, args) {184 /**185 * 调用指定element的原生函数(UIAElement)186 * Paramaters:187 * id - element的id188 * func - 函数名189 * args - 函数的有序参数集合190 * Returns:191 * return value - 被调用函数的返回值(基础类型)192 */193 var element = uia_elements_cache.get(id);194 var args = args ? args : [];195 if (element[func]) {196 return element[func].apply(element, args);197 };198 throw new Error('uia.element.function "func: ' + func + '" is invalid.');199 },200 'uia.element.is_valid' : function(cmd_id, id) {201 try {202 uia_elements_cache.get(id);203 return true;204 } catch(e) {205 return false;206 };207 },208 'uia.element.find' : function(cmd_id, locator, timeout, interval, strategy, parent_id) {209 /**210 * 查找单个element对象,返回查找到的element对象的缓存id。不指定parent_id则从UIAApplication下开始搜索。211 * 第一个对象永远是UIAApplication - 这是为了兼容Python层Window封装不写Path。212 * Paramaters:213 * locator - 定位element的字符串,例如: "/classname='UIAWindow'"214 * parent_id - 父element的id,如不指定则从UIAApplication下查找215 * timeout - 查找element的超时值(单位: 秒)216 * strategy - locator的类型,例如: "qpath"217 * Returns - json: {'element': id, 'path': <encode str>, 'valid_path_part': <encode str>, 'invalid_path_part': <encode str>, 'find_count': <int>, "find_time": int}218 */219 var strategy = strategy ? strategy : 'qpath';220 var locator = switch_locator(strategy, locator);221 var parent = parent_id ? uia_elements_cache.get(parent_id) : null;222 var timeout = timeout ? (timeout * 1000 - 80) : 0;223 var interval = interval ? (interval * 1000) : 10;224 var result = locator.findElement(timeout, interval, parent);225 var element = result['element'];226 var element_id = element ? uia_elements_cache.append(element) : null;227 result['element'] = element_id;228 $.log("TORPC: " + $.str.objectToString({'id':cmd_id, 'result':result}));229 return api.DoNotReturn;230 },231 'uia.element.find_elements' : function(cmd_id, locator, timeout, interval, strategy, parent_id) {232 /**233 * 查找多个element对象,返回查找到的element对象的缓存的id集合。不指定parent_id则从UIAApplication下开始搜索。234 * Paramaters:235 * locator - 定位element的字符串,例如: "/classname='UIAWindow'"236 * parent_id - 父element的id,如不指定则从UIAApplication下查找237 * timeout - 查找element的超时值(单位: 秒)238 * strategy - locator的类型,例如: "qpath"239 * Returns - json: {'elements': [{'element':id, 'attributes':<encode str>}], 'path': <encode str>, 'valid_path_part': <encode str>, 'invalid_path_part': <encode str>, 'find_count': <int>, "find_time": int}240 */241 var strategy = strategy ? strategy : 'qpath';242 var locator = switch_locator(strategy, locator);243 var parent = parent_id ? uia_elements_cache.get(parent_id) : null;244 var timeout = timeout ? (timeout * 1000 - 100) : 0;245 var interval = interval ? (interval * 1000) : 10;246 var result = locator.findElements(timeout, interval, parent);247 var elements = result['elements'];248 var elements_dict = new Array();249 for (var i=0; i<elements.length; i++){250 var element_id = uia_elements_cache.append(elements[i]);251 var element_dict = encodeURIComponent($.str.objectToString(elements[i].getElementDict()));252 elements_dict.push({'element': element_id, 'attributes': element_dict});253 };254 result['elements'] = elements_dict;255 $.log("TORPC: " + $.str.objectToString({'id':cmd_id, 'result':result}));256 return api.DoNotReturn;257 },258 'uia.element.first_with_name' : function(cmd_id, id, name) {259 /**260 * 通过name文本获取第一个匹配的子element261 * Paramaters:262 * id - element的id263 * name - 预期子element的name264 * Returns:265 * id - 子控件的id266 */267 var root = uia_elements_cache.get(id);268 var elem = root.elements().firstWithName(name);269 return uia_elements_cache.append(elem);270 },271 'uia.element.with_name' : function(cmd_id, id, name) {272 /**273 * 通过name文本获取匹配的子elements274 * Paramaters:275 * id - element的id276 * name - 预期子element的name277 * Returns:278 * id - 子控件的id集合279 */280 var root = uia_elements_cache.get(id);281 var elems = root.elements().withName(name);282 return uia_elements_cache.append_elements(elems);283 },284 'uia.element.first_with_predicate' : function(cmd_id, id, predicate) {285 /**286 * 通过predicate文本获取第一个匹配的子element287 * Paramaters:288 * id - element的id289 * predicate - 预期子element的predicate (例如:“name beginswith 'xxx'”)290 * Returns:291 * id - 子控件的id292 */293 var root = uia_elements_cache.get(id);294 var elem = root.elements().firstWithPredicate(predicate);295 return uia_elements_cache.append(elem);296 },297 'uia.element.with_predicate' : function(cmd_id, id, predicate) {298 /**299 * 通过predicate文本获取匹配的子elements300 * Paramaters:301 * id - element的id302 * predicate - 预期子element的predicate (例如:“name beginswith ‘xxx'”)303 * Returns:304 * id - 子控件的id集合305 */306 var root = uia_elements_cache.get(id);307 var elems = root.elements().withPredicate(predicate);308 return uia_elements_cache.append_elements(elems);309 },310 'uia.element.first_with_value_for_key' : function(cmd_id, id, key, value) {311 /**312 * 通过匹配指定key的value,获取第一个匹配的子element313 * Paramaters:314 * id - element的id315 * key - key (例如:label、name、value)316 * value - 对应key的value值317 * Returns:318 * id - 子控件的id319 */320 var root = uia_elements_cache.get(id);321 var elem = root.elements().firstWithValueForKey(value, key);322 return uia_elements_cache.append(elem);323 },324 'uia.element.with_value_for_key' : function(cmd_id, id, key, value) {325 /**326 * 通过匹配指定key的value,获取匹配的子elements327 * Paramaters:328 * id - element的id329 * key - key (例如:label、name、value)330 * value - 对应key的value值331 * Returns:332 * id - 子控件的id集合333 */334 var root = uia_elements_cache.get(id);335 var elems = root.elements().withValueForKey(value, key);336 return uia_elements_cache.append_elements(elems);337 },338 'uia.element.get_parent' : function(cmd_id, id) {339 /**340 * 获取指定element的父element的id341 * Paramaters:342 * id - element的id343 * Returns:344 * id - 父element的id345 */346 var parent = uia_elements_cache.get(id).parent();347 return parent ? uia_elements_cache.append(parent) : undefined;348 },349 'uia.element.get_children' : function(cmd_id, id) {350 /**351 * 获取指定element的子elements集合352 * Paramaters:353 * id - element的id354 * Returns:355 * [id, ...] - 子elements的id集合356 */357 var elements = uia_elements_cache.get(id).elements();358 return elements.length > 0 ? uia_elements_cache.append_elements(elements) : [];359 },360 'uia.element.get_attr' : function(cmd_id, id, name) {361 /**362 * 获取指定element的属性363 * Paramaters:364 * id - element的id365 * name - 属性名,例如: name、lable、value366 * Returns:367 * attr value - 返回基础类型的数据368 */369 var name = name.toLowerCase();370 if (new RegExp(/^isEnabled$|^enabled$|^isValid$|^valid$|^isVisible$|^visible$|^hasKeyboardFocus$|^focus$/i).test(name)) {371 switch (name) {372 case "isenabled":373 name = "isEnabled";374 break;375 case "enabled":376 name = "isEnabled";377 break;378 case "isvalid":379 name = "isValid";380 break;381 case "valid":382 name = "isValid";383 break;384 case "isvisible":385 name = "isVisible";386 break;387 case "visible":388 name = "isVisible";389 break;390 case "haskeyboardfocus":391 name = "hasKeyboardFocus";392 break;393 case "focus":394 name = "hasKeyboardFocus";395 break;396 };397 };398 return api['uia.element.function'](cmd_id, id, name);399 },400 'uia.element.get_rect' : function(cmd_id, id) {401 /**402 * 获取指定element的坐标和长宽403 * Paramaters:404 * id - element id405 * Returns:406 * JSON - 坐标和长宽407 */408 return uia_elements_cache.get(id).rect();409 },410 'uia.element.capture' : function(cmd_id, id, path) {411 /**412 * 截图(截取指定element的图片,并将图片输出至指定的路径)413 * Paramaters:414 * path - 将图片存储至该路径(png格式),例如:/Users/tester/Desktop/test.png415 * 不传路径 或 路径仅含文件名,则截图后存储至默认路径(默认路径内存储的图片每次重启都会被清空)。416 */417 var rect = uia_elements_cache.get(id).rect();418 return api['uia.target.capture_rect'](cmd_id, rect, path);419 },420 'uia.element.tap' : function(cmd_id, id, x, y) {421 /**422 * 点击指定的element423 * Paramaters:424 * id - element id425 * x - x坐标(相对于当前element),可不传入该参数426 * y - y坐标(相对于当前element),可不传入该参数427 */428 var element = uia_elements_cache.get(id);429 var rect = element.rect();430 var size = rect['size'];431 var x = size['width'] * x;432 var y = size['height'] * y;433 //element.scrollToVisible();434 element.tap(x, y);435 },436 'uia.element.double_tap' : function(cmd_id, id, x, y) {437 /**438 * 双击指定的element439 * Paramaters:440 * id - element id441 * x - x坐标(相对于当前element),可不传入该参数442 * y - y坐标(相对于当前element),可不传入该参数443 */444 if (x && y) {445 for (var i = 0; i < 2; i++) {446 api['uia.element.tap'](cmd_id, id, x, y);447 };448 } else {449 var element = uia_elements_cache.get(id);450 //element.scrollToVisible();451 element.doubleTap();452 };453 },454 'uia.element.tap_with_options' : function(cmd_id, id, options) {455 /**456 * 自定义点击457 * Paramaters:458 * id - element id459 * options = {460 * tapCount : 1, // 轻触次数461 * touchCount : 1, // 触摸点462 * duration : 1, // 持续时间463 * tapOffset : { x: 1.0, y: 0.1 } // 轻触偏移百分比464 * }465 */466 var element = uia_elements_cache.get(id);467 //element.scrollToVisible();468 element.tapWithOptions(options);469 },470 'uia.element.click' : function(cmd_id, id, x, y) {471 /**472 * 点击指定的element(适配QTA)473 * Paramaters:474 * id - element id475 * x - x坐标(相对于当前element),可不传入该参数476 * y - y坐标(相对于当前element),可不传入该参数477 */478 api['uia.element.tap'](cmd_id, id, x, y);479 },480 'uia.element.double_click' : function(cmd_id, id, x, y) {481 /**482 * 双击指定的element483 * Paramaters:484 * id - element id485 * x - x坐标(相对于当前element),可不传入该参数486 * y - y坐标(相对于当前element),可不传入该参数487 */488 api['uia.element.double_tap'](cmd_id, id, x, y);489 },490 'uia.element.drag_inside_with_options' : function(cmd_id, id, options) {491 /**492 * 拖拽493 * Paramaters:494 * id - element id495 * options = {496 * touchCount : 1, // 触摸点497 * duration : 0.5, // 时间498 * startOffset : { x: 0.0, y: 0.1}, // 偏移百分比499 * endOffset : { x: 1.0, y: 0.1 }, // 偏移百分比500 * repeat : 1 // 重复该操作501 * interval : 0 // 重复该操作的间隙时间(秒)502 * }503 */504 var repeat = options.repeat ? options.repeat : 1;505 var interval = options.interval ? options.interval : 0;506 for (var i = 0; i < repeat; i++) {507 uia_elements_cache.get(id).dragInsideWithOptions(options);508 if (repeat > 1 && interval > 0) {509 UIATarget.localTarget().delay(interval);510 };511 };512 },513 'uia.element.drag_inside_right_to_left' : function(cmd_id, id) {514 /**515 * 单指在控件的中央从右向左拖拽(回避控件边缘,拖拽过程使用1秒)516 */517 var _options = {518 touchCount : 1,519 duration : 1.5,520 startOffset : {521 x : 0.5,522 y : 0.5523 },524 endOffset : {525 x : 0.1,526 y : 0.5527 }528 };529 uia_elements_cache.get(id).dragInsideWithOptions(_options);530 },531 'uia.element.drag_inside_left_to_right' : function(cmd_id, id) {532 /**533 * 单指在控件的中央从左向右拖拽(回避控件边缘,拖拽过程使用1秒)534 */535 var _options = {536 touchCount : 1,537 duration : 1.5,538 startOffset : {539 x : 0.5,540 y : 0.5541 },542 endOffset : {543 x : 0.9,544 y : 0.5545 }546 };547 uia_elements_cache.get(id).dragInsideWithOptions(_options);548 },549 'uia.element.drag_inside_up_to_down' : function(cmd_id, id) {550 /**551 * 单指在控件的中央从上向下拖拽(回避控件边缘,拖拽过程使用1秒)552 */553 var _options = {554 touchCount : 1,555 duration : 1.5,556 startOffset : {557 x : 0.5,558 y : 0.5559 },560 endOffset : {561 x : 0.5,562 y : 0.9563 }564 };565 uia_elements_cache.get(id).dragInsideWithOptions(_options);566 },567 'uia.element.drag_inside_down_to_up' : function(cmd_id, id) {568 /**569 * 单指在控件的中央从下向上拖拽(回避控件边缘,拖拽过程使用1秒)570 */571 var _options = {572 touchCount : 1,573 duration : 1.5,574 startOffset : {575 x : 0.5,576 y : 0.5577 },578 endOffset : {579 x : 0.5,580 y : 0.1581 }582 };583 uia_elements_cache.get(id).dragInsideWithOptions(_options);584 },585 'uia.element.flick_inside_with_options' : function(cmd_id, id, options) {586 /**587 * 弹去/拂去588 * Paramaters:589 * id - element id590 * options = {591 * touchCount : 1, // 触摸点592 * startOffset : { x: 0.5, y: 0.9 }, // 偏移百分比593 * endOffset : { x: 1.0, y: 0.9 } // 偏移百分比594 * repeat : 1 // 重复该操作595 * interval : 0 // 重复该操作的间隙时间(秒)596 * }597 */598 var repeat = options.repeat ? options.repeat : 1;599 var interval = options.interval ? options.interval : 0;600 for (var i = 0; i < repeat; i++) {601 uia_elements_cache.get(id).flickInsideWithOptions(options);602 if (repeat > 1 && interval > 0) {603 UIATarget.localTarget().delay(interval);604 };605 };606 },607 'uia.element.flick_inside_right_to_left' : function(cmd_id, id) {608 /**609 * 单指在控件中央从右向左弹去/拂去(回避控件边缘)610 */611 var _options = {612 touchCount : 1,613 startOffset : {614 x : 0.5,615 y : 0.5616 },617 endOffset : {618 x : 0.1,619 y : 0.5620 }621 };622 uia_elements_cache.get(id).flickInsideWithOptions(_options);623 },624 'uia.element.flick_inside_left_to_right' : function(cmd_id, id) {625 /**626 * 单指在控件中央从左向右弹去/拂去(回避控件边缘)627 */628 var _options = {629 touchCount : 1,630 startOffset : {631 x : 0.5,632 y : 0.5633 },634 endOffset : {635 x : 0.9,636 y : 0.5637 }638 };639 uia_elements_cache.get(id).flickInsideWithOptions(_options);640 },641 'uia.element.flick_inside_up_to_down' : function(cmd_id, id) {642 /**643 * 单指在控件中央从上向下弹去/拂去(回避控件边缘)644 */645 var _options = {646 touchCount : 1,647 startOffset : {648 x : 0.5,649 y : 0.5650 },651 endOffset : {652 x : 0.5,653 y : 0.9654 }655 };656 uia_elements_cache.get(id).flickInsideWithOptions(_options);657 },658 'uia.element.flick_inside_down_to_up' : function(cmd_id, id) {659 /**660 * 单指在控件中央从下向上弹去/拂去(回避控件边缘)661 */662 var _options = {663 touchCount : 1,664 startOffset : {665 x : 0.5,666 y : 0.5667 },668 endOffset : {669 x : 0.5,670 y : 0.1671 }672 };673 uia_elements_cache.get(id).flickInsideWithOptions(_options);674 },675 'uia.element.rotate_with_options' : function(cmd_id, id, options) {676 /**677 * 旋转678 * Paramaters:679 * id - element id680 * options = {681 * centerOffset : {x:0.0, y:0.0}, // 中心点682 * duration : 1.5, // 持续时间683 * radius : 100, // 半径684 * rotation : 100, // 旋转弧度的长度,默认为圆周率PI685 * touchCount : 2 // 触摸点(最大5个点,这里默认2个)686 * }687 */688 uia_elements_cache.get(id).rotateWithOptions(options);689 },690 'uia.element.scroll_to_visible' : function(cmd_id, id) {691 /**692 * 自动滚动到该element为可见693 * Paramaters:694 * id - element id695 */696 uia_elements_cache.get(id).scrollToVisible();697 // --- --- --- retry无效698 //var element = uia_elements_cache.get(id);699 //var retry = retry ? retry : 5;700 //var target = UIATarget.localTarget();701 //var error = null;702 //for (var i = 0; i < retry; i++) {703 // try {704 // element.scrollToVisible();705 // return;706 // } catch(e) {707 // target.delay(1);708 // error = e;709 // };710 //};711 //throw error;712 // --- --- ---713 },714 'uia.element.touch_and_hold' : function(cmd_id, id, duration) {715 /**716 * 持续按住717 * Paramaters:718 * id - element id719 * duration - 按住多长时间(秒)720 */721 uia_elements_cache.get(id).touchAndHold(duration);722 },723 'uia.element.two_finger_tap' : function(cmd_id, id) {724 /**725 * 二指轻触726 * Paramaters:727 * id - element id728 */729 uia_elements_cache.get(id).twoFingerTap();730 },731 'uia.element.wait_for_invalid' : function(cmd_id, id, timeout) {732 /**733 * 等待当前element直到无效734 * Paramaters:735 * id - element id736 * timeout - 超时值(秒)737 */738 var element = uia_elements_cache.get(id);739 var timeout = timeout ? timeout : 5;740 var target = UIATarget.localTarget();741 target.pushTimeout(timeout);742 var result = element.waitForInvalid();743 target.popTimeout();744 return result;745 },746 'uia.element.set_value' : function(cmd_id, id, value) {747 /**748 * 设置指定element的value749 * Paramaters:750 * id - element id751 * value - 值752 */753 uia_elements_cache.get(id).setValue(value);754 },755 'uia.element.drag_to_value' : function(cmd_id, id, value) {756 /**757 * 设置指定slider的value758 * Paramaters:759 * id - element id760 * value - 值761 */762 uia_elements_cache.get(id).dragToValue(value);763 }, 764 'uia.element.sent_keys' : function(cmd_id, id, keys) {765 /**766 * 在指定element中键盘输入767 * Paramaters:768 * id - element id769 * keys - 键入的字符串770 */771 var elem = uia_elements_cache.get(id);772 elem.tap();773 elem.typeString(keys);774 },775 'uia.element.get_element_dict' : function(cmd_id, id) {776 /**777 * 获取指定element的属性信息778 * Returns779 * JSON String - 属性780 */781 var dict = uia_elements_cache.get(id).getElementDict();782 var result = encodeURIComponent($.str.objectToString(dict, true));783 $.log("TORPC: " + $.str.objectToString({784 'id' : cmd_id,785 'result' : result786 }));787 return api.DoNotReturn;788 },789 'uia.element.log_element_dict' : function(cmd_id, id) {790 /**791 * 打印并获取指定element的属性信息792 * Returns793 * JSON String - 属性794 */795 var dict = uia_elements_cache.get(id).logElementDict();796 var result = encodeURIComponent($.str.objectToString(dict, true));797 $.log("TORPC: " + $.str.objectToString({798 'id' : cmd_id,799 'result' : result800 }));801 return api.DoNotReturn;802 },803 'uia.element.get_element_tree' : function(cmd_id, id) {804 /**805 * 获取指定element的所有子孙element树806 * Paramaters:807 * id - element的id808 * Returns:809 * JSON - 子孙节点树810 */811 var dict = uia_elements_cache.get(id).getElementTree();812 var result = encodeURIComponent($.str.objectToString(dict, true));813 $.log("TORPC: " + $.str.objectToString({814 'id' : cmd_id,815 'result' : result816 }));817 return api.DoNotReturn;818 },819 'uia.element.log_element_tree_ext' : function(cmd_id, id) {820 /**821 * 从指定element开始获取UI树822 * Returns823 * JSON String - UI树824 */825 var dict = uia_elements_cache.get(id).logElementTreeExt();826 var result = encodeURIComponent($.str.objectToString(dict, true));827 $.log("TORPC: " + $.str.objectToString({828 'id' : cmd_id,829 'result' : result830 }));831 return api.DoNotReturn;832 },833 // -*- -*- -*- -*- -*- -*-834 'uia.application.function' : function(cmd_id, func, args) {835 /**836 * 调用UIAApplication的原生函数837 * Paramaters:838 * func - 函数名839 * args - 函数的有序参数集840 * Returns:841 * return value - 被调用函数的返回值(基础类型)842 */843 var app = UIATarget.localTarget().frontMostApp();844 var args = args ? args : [];845 if (app[func]) {846 return app[func].apply(app, args);847 };848 throw new Error('uia.application.function "func: ' + func + '" is invalid.');849 },850 //'uia.application.get_attr' : function(cmd_id, name) {851 // /**852 // * 获取UIAApplication的属性853 // * Paramaters:854 // * name - 属性名,例如: name、lable、value855 // * Returns:856 // * attr value - 返回基础类型的数据857 // */858 // return api['uia.application.function'](cmd_id, name);859 //},860 'uia.application.get_main_window' : function(cmd_id) {861 /**862 * 获取App的主窗口863 * Returns864 * id - element的id865 */866 return uia_elements_cache.append(UIATarget.localTarget().frontMostApp().mainWindow());867 },868 'uia.application.get_interface_orientation' : function(cmd_id) {869 /**870 * 获取接口方向871 * Returns872 * number - 表示方向873 */874 return UIATarget.localTarget().frontMostApp().interfaceOrientation();875 },876 'uia.application.get_app_bundle_id' : function(cmd_id) {877 /**878 * 获取App的bundleID879 * Returns880 * string - bundleID881 */882 return UIATarget.localTarget().frontMostApp().bundleID();883 },884 'uia.application.get_app_version' : function(cmd_id) {885 /**886 * 获取App的version887 * Returns888 * string - version889 */890 return UIATarget.localTarget().frontMostApp().version();891 },892 // -*- -*- -*- -*- -*- -*-893 'uia.target.function' : function(cmd_id, func, args) {894 /**895 * 调用UIATarget的原生函数(注:device命名空间对应UIATarget对象)896 * Paramaters:897 * func - 函数名898 * args - 函数的有序参数集899 * Returns:900 * return value - 被调用函数的返回值(基础类型)901 */902 var target = UIATarget.localTarget();903 var args = args ? args : [];904 if (target[func]) {905 return target[func].apply(target, args);906 };907 throw new Error('uia.target.function "func: ' + func + '" is invalid.');908 },909 //'uia.target.get_attr' : function(cmd_id, name) {910 // /**911 // * 获取UIATarget的属性912 // * Paramaters:913 // * name - 属性名,例如: name、lable、value914 // * Returns:915 // * attr value - 返回基础类型的数据916 // */917 // return api['uia.target.function'](cmd_id, name);918 //},919 'uia.target.get_rect' : function(cmd_id) {920 /**921 * 获取设备屏幕大小922 * Returns:923 * 宽高924 */925 return UIATarget.localTarget().rect();926 },927 'uia.target.get_model' : function(cmd_id) {928 /**929 * 获取设备模型930 * Returns:931 * string932 */933 return UIATarget.localTarget().model();934 },935 'uia.target.get_name' : function(cmd_id) {936 /**937 * 获取设备名938 * Returns:939 * string940 */941 return UIATarget.localTarget().name();942 },943 'uia.target.get_system_name' : function(cmd_id) {944 /**945 * 获取系统名946 * Returns:947 * string948 */949 return UIATarget.localTarget().systemName();950 },951 'uia.target.get_system_version' : function(cmd_id) {952 /**953 * 获取系统版本954 * Returns:955 * string956 */957 return UIATarget.localTarget().systemVersion();958 },959 'uia.target.capture_rect' : function(cmd_id, rect, path) {960 /**961 * 截图(指定区域截图,并将图片输出至指定的路径)962 * Paramaters:963 * rect - 指定区域964 * {965 * origin : { x: xposition, y: yposition },966 * size : { width: widthvalue, height: heightvalue}967 * }968 * path - 将图片存储至该路径(png格式),例如:/Users/tester/Desktop/test.png969 * 不传路径 或 路径仅含文件名,则截图后存储至默认路径(默认路径内存储的图片每次重启都会被清空)。970 */971 var name = String(new Date().getTime());972 if (path) {973 var nodes = path.split('/');974 if (nodes[nodes.length - 1].length > 0) {975 name = nodes[nodes.length - 1].replace(/\.\w{3,4} *$/, '');976 nodes[nodes.length - 1] = name;977 };978 path = nodes.join('/');979 };980 if (!new RegExp('^/').test(path)) {981 path = [Environment.screen_shot_path, name].join('/');982 };983 UIATarget.localTarget().captureRectWithName(rect, name);984 name += '.png';985 path += '.png';986 $.log('ScreenshotCaptured: {"name": "' + name + '", "path": "' + path + '"}');987 return path;988 },989 'uia.target.capture_screen' : function(cmd_id, path) {990 /**991 * 截屏(将输出图片至指定的路径)992 * Paramaters:993 * path - 将图片存储至该路径(png格式),例如:/Users/tester/Desktop/test.png994 * - 不传路径 或 路径仅含文件名,则截图后存储至默认路径(默认路径内存储的图片每次重启都会被清空)。995 */996 var name = String(new Date().getTime());997 if (path) {998 var nodes = path.split('/');999 if (nodes[nodes.length - 1].length > 0) {1000 name = nodes[nodes.length - 1].replace(/\.\w{3,4} *$/, '');1001 nodes[nodes.length - 1] = name;1002 };1003 path = nodes.join('/');1004 };1005 if (!new RegExp('^/').test(path)) {1006 path = [Environment.screen_shot_path, name].join('/');1007 };1008 UIATarget.localTarget().captureScreenWithName(name);1009 name += '.png';1010 path += '.png';1011 $.log('ScreenshotCaptured: {"name": "' + name + '", "path": "' + path + '"}');1012 return path;1013 },1014 'uia.target.get_element_tree_and_capture_screen' : function(cmd_id, path) {1015 /**1016 * 获取UI树并截屏(输出的JSON字符串数据需要URL解码)1017 * Paramaters:1018 * path - 将图片存储至该路径(png格式),例如:/Users/tester/Desktop/test.png1019 * - 不传路径 或 路径仅含文件名,则截图后存储至默认路径(默认路径内存储的图片每次重启都会被清空)。1020 * Returns:1021 * Dict - { element_tree: {}, capture_screen: file_path }1022 */1023 $.log("TORPC: " + $.str.objectToString({1024 'id' : cmd_id,1025 'result' : encodeURIComponent($.str.objectToString({1026 element_tree : UIATarget.localTarget().getElementTree(),1027 capture_screen : api['uia.target.capture_screen'](cmd_id, path)1028 }, true))1029 }));1030 return api.DoNotReturn;1031 },1032 'uia.target.set_rules_of_alert_auto_handle' : function(cmd_id, rules) {1033 /**1034 * 设置自动处理Alert规则1035 * Paramaters:1036 * rules = [ {"message_text": "message_text", "button_text": "button_text"}, ... ]1037 * message_text - (支持正则表达式)在Alert内所有Element的文本中的某文本(单一Element的label、name、value,等于三段文本。其中一项匹配即可。)1038 * button_text - (支持正则表达式)在Alert内的匹配文本的按钮(UIAButton的label、name、value,等于三段文本。其中一项匹配即可。)1039 */1040 rules_of_alert_auto_handle = rules;1041 },1042 'uia.target.get_rules_of_alert_auto_handle' : function(cmd_id) {1043 /**1044 * 查询已设置的自动处理Alert规则1045 * Returns:1046 * list - [ {"message_text": "message_text", "button_text": "button_text"}, ... ]1047 */1048 return encodeURIComponent($.str.objectToString(rules_of_alert_auto_handle, true));1049 },1050 'uia.target.add_rule_of_alert_auto_handle' : function(cmd_id, message_text, button_text) {1051 /**1052 * 自动处理Alert规则增加一项1053 * Paramaters:1054 * message_text - (支持正则表达式)在Alert内所有Element的文本中的某文本(单一Element的label、name、value,等于三段文本。其中一项匹配即可。)1055 * button_text - (支持正则表达式)在Alert内的匹配文本的按钮(UIAButton的label、name、value,等于三段文本。其中一项匹配即可。)1056 */1057 rules_of_alert_auto_handle.push({1058 message_text : message_text,1059 button_text : button_text1060 });1061 },1062 'uia.target.clean_rules_of_alert_auto_handle' : function(cmd_id) {1063 /**1064 * 清除所有自动处理Alert的规则1065 */1066 rules_of_alert_auto_handle = new Array();1067 },1068 'uia.target.turn_on_auto_close_alert' : function(cmd_id) {1069 /**1070 * 打开自动关闭alert框(如果rules_of_alert_auto_handle无匹配,则交由系统自动关闭)1071 */1072 flag_alert_auto_handled = false;1073 // 我方未处理,UIA默认自动处理1074 },1075 'uia.target.turn_off_auto_close_alert' : function(cmd_id) {1076 /**1077 * 关闭自动关闭alert框1078 */1079 flag_alert_auto_handled = true;1080 // 我方已处理,UIA不再自动处理1081 },1082 'uia.target.get_last_alert_msg' : function(cmd_id) {1083 /**1084 * 获取最近一次alert框的提示内容1085 * Returns1086 * msg - 文本内容1087 */1088 return last_alert_msg;1089 },1090 'uia.target.delay' : function(cmd_id, seconds) {1091 /**1092 * 等待1093 * Paramaters:1094 * seconds - 秒1095 */1096 UIATarget.localTarget().delay(seconds);1097 },1098 'uia.target.get_element_tree' : function(cmd_id) {1099 /**1100 * 从顶层开始获取UI树(输出的JSON字符串数据需要URL解码)1101 * Returns1102 * JSON String - UI树1103 */1104 var dict = UIATarget.localTarget().getElementTree();1105 var result = encodeURIComponent($.str.objectToString(dict, true));1106 $.log("TORPC: " + $.str.objectToString({1107 'id' : cmd_id,1108 'result' : result1109 }));1110 return api.DoNotReturn;1111 },1112 'uia.target.log_element_tree_ext' : function(cmd_id) {1113 /**1114 * 从顶层开始获取UI树(输出的JSON字符串数据需要URL解码)1115 * Returns1116 * JSON String - UI树1117 */1118 var dict = UIATarget.localTarget().logElementTreeExt();1119 var result = encodeURIComponent($.str.objectToString(dict, true));1120 $.log("TORPC: " + $.str.objectToString({1121 'id' : cmd_id,1122 'result' : result1123 }));1124 return api.DoNotReturn;1125 },1126 'uia.target.click_volume_down' : function(cmd_id) {1127 /**1128 * 按下一次减少音量按键1129 */1130 UIATarget.localTarget().clickVolumeDown();1131 },1132 'uia.target.click_volume_up' : function(cmd_id) {1133 /**1134 * 按下一次增加音量按键1135 */1136 UIATarget.localTarget().clickVolumeUp();1137 },1138 'uia.target.hold_volume_down' : function(cmd_id, seconds) {1139 /**1140 * 持续按住减少音量按键1141 * * Paramaters:1142 * seconds - 秒1143 */1144 var seconds = seconds ? seconds : 1;1145 UIATarget.localTarget().holdVolumeDown(seconds);1146 },1147 'uia.target.hold_volume_up' : function(cmd_id, seconds) {1148 /**1149 * 持续按住增加音量按键1150 * * Paramaters:1151 * seconds - 秒1152 */1153 var seconds = seconds ? seconds : 1;1154 UIATarget.localTarget().holdVolumeUp(seconds);1155 },1156 'uia.target.deactivate_app_ror_duration' : function(cmd_id, seconds) {1157 /**1158 * 将App置于后台一定时间1159 * Paramaters:1160 * seconds - 秒1161 * Returns1162 * Boolean1163 */1164 var seconds = seconds ? seconds : 3;1165 return UIATarget.localTarget().deactivateAppForDuration(seconds);1166 },1167 'uia.target.get_device_orientation' : function(cmd_id) {1168 /**1169 * 获取设备的方向1170 * Returns1171 * Number1172 * UIA_DEVICE_ORIENTATION_UNKNOWN1173 * UIA_DEVICE_ORIENTATION_PORTRAIT1174 * UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN1175 * UIA_DEVICE_ORIENTATION_LANDSCAPELEFT1176 * UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT1177 * UIA_DEVICE_ORIENTATION_FACEUP1178 * UIA_DEVICE_ORIENTATION_FACEDOWN1179 */1180 return UIATarget.localTarget().deviceOrientation();1181 },1182 'uia.target.tap' : function(cmd_id, point) {1183 /**1184 * 双击1185 * Paramaters:1186 * point - { x: 0.5, y: 0.5 }1187 */1188 var _rect = UIATarget.localTarget().rect();1189 var _point = point ? point : {};1190 _point.x = _point.x ? _rect.size.width * _point.x : _rect.size.width * 0.5;1191 _point.y = _point.y ? _rect.size.height * _point.y : _rect.size.height * 0.5;1192 UIATarget.localTarget().tap(_point);1193 },1194 'uia.target.double_tap' : function(cmd_id, point) {1195 /**1196 * 双击1197 * Paramaters:1198 * point - { x: 100, y: 100 }1199 */1200 var _rect = UIATarget.localTarget().rect();1201 var _point = point ? point : {};1202 _point.x = _point.x ? _point.x : _rect.size.width * 0.5;1203 _point.y = _point.y ? _point.y : _rect.size.height * 0.5;1204 UIATarget.localTarget().doubleTap(_point);1205 },1206 'uia.target.tap_with_options' : function(cmd_id, point, options) {1207 /**1208 * 双击1209 * Paramaters:1210 * point - { x: 100, y: 100 }1211 * options - {1212 * tapCount : 1, 几次,默认1次1213 * touchCount : 1, 几点,默认1个点(例如两个手指则为2)1214 * duration : 0 按住的时间,默认是01215 * }1216 */1217 UIATarget.localTarget().tapWithOptions(point, options);1218 },1219 'uia.target.touch_and_hold' : function(cmd_id, point, duration) {1220 /**1221 * 双击1222 * Paramaters:1223 * point - { x: 100, y: 100 }1224 * duration - 按住多少秒1225 */1226 UIATarget.localTarget().touchAndHold(point, duration);1227 },1228 'uia.target.drag_from_to_for_duration' : function(cmd_id, from_point, to_point, duration, repeat, interval) {1229 /**1230 * 拖拽1231 * Paramaters:1232 * from_point - { x: 0.5, y: 0.9 } // 偏移百分比1233 * to_point - { x: 0.5, y: 0.1 } // 偏移百分比1234 * duration - 持续时间(秒)1235 * repeat - 重复该操作1236 * interval - 重复该操作的间隙时间(秒)1237 */1238 var rect = UIATarget.localTarget().rect();1239 var from_point = {1240 x : Math.floor(rect.size.width * from_point.x),1241 y : Math.floor(rect.size.height * from_point.y)1242 };1243 var to_point = {1244 x : Math.floor(rect.size.width * to_point.x),1245 y : Math.floor(rect.size.height * to_point.y)1246 };1247 var duration = duration ? duration : 0.5;1248 var repeat = repeat ? repeat : 1;1249 var interval = interval ? interval : 0;1250 for (var i = 0; i < repeat; i++) {1251 UIATarget.localTarget().dragFromToForDuration(from_point, to_point, duration);1252 if (repeat > 1 && interval > 0) {1253 UIATarget.localTarget().delay(interval);1254 };1255 };1256 },1257 'uia.target.drag_right_to_left' : function(cmd_id) {1258 /**1259 * 屏幕中央从右向左拖拽(回避屏幕边缘)1260 */1261 var _from_point = {1262 x : 0.5,1263 y : 0.51264 };1265 var _to_point = {1266 x : 0.1,1267 y : 0.51268 };1269 api['uia.target.drag_from_to_for_duration'](cmd_id, _from_point, _to_point);1270 },1271 'uia.target.drag_left_to_right' : function(cmd_id) {1272 /**1273 * 屏幕中央从左向右拖拽(回避屏幕边缘)1274 */1275 var _from_point = {1276 x : 0.5,1277 y : 0.51278 };1279 var _to_point = {1280 x : 0.9,1281 y : 0.51282 };1283 api['uia.target.drag_from_to_for_duration'](cmd_id, _from_point, _to_point);1284 },1285 'uia.target.drag_up_to_down' : function(cmd_id) {1286 /**1287 * 屏幕中央从上向下拖拽(回避屏幕边缘)1288 */1289 var _from_point = {1290 x : 0.5,1291 y : 0.51292 };1293 var _to_point = {1294 x : 0.5,1295 y : 0.91296 };1297 api['uia.target.drag_from_to_for_duration'](cmd_id, _from_point, _to_point);1298 },1299 'uia.target.drag_down_to_up' : function(cmd_id) {1300 /**1301 * 屏幕中央从下向上拖拽(回避屏幕边缘)1302 */1303 var _from_point = {1304 x : 0.5,1305 y : 0.51306 };1307 var _to_point = {1308 x : 0.5,1309 y : 0.11310 };1311 api['uia.target.drag_from_to_for_duration'](cmd_id, _from_point, _to_point);1312 },1313 'uia.target.flick_from_to' : function(cmd_id, from_point, to_point, repeat, interval) {1314 /**1315 * 弹去/拂去1316 * Paramaters:1317 * from_point - { x: 0.5, y: 0.9 } // 偏移百分比1318 * to_point - { x: 0.5, y: 0.1 } // 偏移百分比1319 * repeat - 重复该操作1320 * interval - 重复该操作的间隙时间(秒)1321 */1322 var rect = UIATarget.localTarget().rect();1323 var from_point = {1324 x : Math.floor(rect.size.width * from_point.x),1325 y : Math.floor(rect.size.height * from_point.y)1326 };1327 var to_point = {1328 x : Math.floor(rect.size.width * to_point.x),1329 y : Math.floor(rect.size.height * to_point.y)1330 };1331 var repeat = repeat ? repeat : 1;1332 var interval = interval ? interval : 0;1333 for (var i = 0; i < repeat; i++) {1334 UIATarget.localTarget().flickFromTo(from_point, to_point);1335 if (repeat > 1 && interval > 0) {1336 UIATarget.localTarget().delay(interval);1337 };1338 };1339 },1340 'uia.target.flick_right_to_left' : function(cmd_id) {1341 /**1342 * 屏幕中央从右向左弹去/拂去1343 */1344 var _from_point = {1345 x : 0.5,1346 y : 0.51347 };1348 var _to_point = {1349 x : 0.1,1350 y : 0.51351 };1352 api['uia.target.flick_from_to'](cmd_id, _from_point, _to_point);1353 },1354 'uia.target.flick_left_to_right' : function(cmd_id) {1355 /**1356 * 屏幕中央从左向右弹去/拂去1357 */1358 var _from_point = {1359 x : 0.5,1360 y : 0.51361 };1362 var _to_point = {1363 x : 0.9,1364 y : 0.51365 };1366 api['uia.target.flick_from_to'](cmd_id, _from_point, _to_point);1367 },1368 'uia.target.flick_up_to_down' : function(cmd_id) {1369 /**1370 * 屏幕中央从上向下弹去/拂去1371 */1372 var _from_point = {1373 x : 0.5,1374 y : 0.51375 };1376 var _to_point = {1377 x : 0.5,1378 y : 0.91379 };1380 api['uia.target.flick_from_to'](cmd_id, _from_point, _to_point);1381 },1382 'uia.target.flick_down_to_up' : function(cmd_id) {1383 /**1384 * 屏幕中央从下向上弹去/拂去1385 */1386 var _from_point = {1387 x : 0.5,1388 y : 0.51389 };1390 var _to_point = {1391 x : 0.5,1392 y : 0.11393 };1394 api['uia.target.flick_from_to'](cmd_id, _from_point, _to_point);1395 },1396 'uia.target.lock_for_duration' : function(cmd_id, duration) {1397 /**1398 * 持续锁定一段时间1399 * Paramaters:1400 * duration - 持续多久(秒)1401 */1402 UIATarget.localTarget().lockForDuration(duration);1403 },1404 'uia.target.pinch_close_from_to_for_duration' : function(cmd_id, from_point, to_point, duration) {1405 /**1406 * 捏合1407 * Paramaters:1408 * from_point - { x: 100, y: 100 }1409 * to_point - { x: 200, y: 200 }1410 * duration - 从起点至终点消耗的时间(控制快慢)1411 */1412 UIATarget.localTarget().pinchCloseFromToForDuration(from_point, to_point, duration);1413 },1414 'uia.target.pinch_open_from_to_for_duration' : function(cmd_id, from_point, to_point, duration) {1415 /**1416 * 展开1417 * Paramaters:1418 * from_point - { x: 100, y: 100 }1419 * to_point - { x: 200, y: 200 }1420 * duration - 从起点至终点消耗的时间(控制快慢)1421 */1422 UIATarget.localTarget().pinchOpenFromToForDuration(from_point, to_point, duration);1423 },1424 'uia.target.rotate_with_options' : function(cmd_id, location, options) {1425 /**1426 * 旋转1427 * Paramaters:1428 * location - { x: 100, y: 100 } 中心点1429 * options - {1430 * duration : 1, 持续的时间(秒)1431 * radius : 50, 半径1432 * rotation : 100, 圆周,默认是圆周率PI1433 * touchCount : 2 触摸点数量 2 - 51434 * }1435 */1436 UIATarget.localTarget().rotateWithOptions(location, options);1437 },1438 'uia.target.set_device_orientation' : function(cmd_id, orientation) {1439 /**1440 * 设置设备的方向1441 * Paramaters:1442 * orientation - 代表方向的数值1443 * UIA_DEVICE_ORIENTATION_UNKNOWN1444 * UIA_DEVICE_ORIENTATION_PORTRAIT1445 * UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN1446 * UIA_DEVICE_ORIENTATION_LANDSCAPELEFT1447 * UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT1448 * UIA_DEVICE_ORIENTATION_FACEUP1449 * UIA_DEVICE_ORIENTATION_FACEDOWN1450 */1451 UIATarget.localTarget().setDeviceOrientation(orientation);1452 },1453 'uia.target.set_location' : function(cmd_id, coordinates) {1454 /**1455 * 设置设备的GPS坐标1456 * Paramaters:1457 * coordinates - {1458 * latitude : 100, // 以度为单位的纬度。正值表示纬度赤道以北。负值表示纬度赤道以南。1459 * longitude : 100 // 以度为单位的经度。测量是相对于零子午线,用正值向东延伸的经络及经络的负值西侧延伸。1460 * }1461 */1462 UIATarget.localTarget().setLocation(orientation);1463 },1464 'uia.target.set_location_with_options' : function(cmd_id, coordinates, options) {1465 /**1466 * 设置设备的GPS坐标1467 * Paramaters:1468 * coordinates - {1469 * latitude : 100, // 以度为单位的纬度。正值表示纬度赤道以北。负值表示纬度赤道以南。1470 * longitude : 100 // 以度为单位的经度。测量是相对于零子午线,用正值向东延伸的经络及经络的负值西侧延伸。1471 * }1472 * options - {1473 * altitude : 50, // 海拔高度,以米为单位,相对于海平面。正值表示海拔高度。负值表示低于海平面的高度。1474 * horizontalAccuracy : 10, // 水平半径,不确位置时的范围内,以米为单位。负的值是无效的。1475 * verticalAccuracy : 10, // 垂直半径,不确位置时的范围内,以米为单位。负的值是无效的。1476 * course : 1, // 设备是移动的,不确定移动方向1477 * speed : 1 // 移动速度(米/秒)1478 * }1479 */1480 UIATarget.localTarget().setLocationWithOptions(orientation, options);1481 },1482 'uia.target.shake' : function(cmd_id) {1483 /**1484 * 摇晃设备1485 */1486 UIATarget.localTarget().shake();1487 },1488 'uia.target.unlock' : function(cmd_id) {1489 /**1490 * 解锁设备1491 */1492 UIATarget.localTarget().unlock();1493 },1494 'uia.target.lock' : function(cmd_id) {1495 /**1496 * 锁定设备1497 */1498 UIATarget.localTarget().lock();1499 },1500 'uia.keyboard.sent_keys' : function(cmd_id, keys) {1501 /**1502 * 键盘输入1503 */1504 UIATarget.localTarget().frontMostApp().keyboard().typeString(keys);1505 },1506 };...

Full Screen

Full Screen

FollowWorker.js

Source:FollowWorker.js Github

copy

Full Screen

...726 const random1 = Math.floor(200 + Math.random()*200);727 const random2 = Math.floor(Math.random()*150);728 const random3 = Math.floor(Math.random()*147);729 // console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)730 await element.flick(0, -(random1 + random2), random1 + random3);731 await sleep(0);732 }733 } catch(e) {734 console.log(`나의 피드보기 에러: ${e.name}`);735 }736}737async function myDmView(running, driver) {738 try {739 await gotoMain(running, driver);740 const element = await driver.element("id", "action_bar_inbox_button");741 await element.click();742 const random = Math.floor(Math.random()*10);743 for (let i=0; i<random; i++) {744 const element = await driver.element("id", "inbox_refreshable_thread_list_recyclerview");745 const random1 = Math.floor(200 + Math.random()*200);746 const random2 = Math.floor(Math.random()*150);747 const random3 = Math.floor(Math.random()*147);748 // console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)749 await element.flick(0, -(random1 + random2), random1 + random3);750 await sleep(0);751 }752 const inboxs = await driver.elements("id", "row_inbox_container");753 const inbox = inboxs[Math.floor(Math.random()*inboxs.length)];754 inbox.click();755 const random2 = Math.floor(Math.random()*10);756 // console.log(`랜덤카운트 : ${random2}`);757 for (let i=0; i<random2; i++) {758 const element = await driver.element("id", "message_list");759 const random1 = Math.floor(200 + Math.random()*200);760 const random2 = Math.floor(Math.random()*150);761 const random3 = Math.floor(Math.random()*147);762 // console.log(`${i} - flick(0, ${random1 + random2}, ${random1 + random3});`)763 await element.flick(0, random1 + random2, random1 + random3);764 await sleep(0);765 }766 } catch(e) {767 console.log(`나의 디엠보기 에러: ${e.name}`);768 console.log(e);769 }770}771async function viewStory(running, driver) {772 try {773 await gotoMain(running, driver);774 await sleep(2);775 const element = await driver.elements("id", "outer_container");776 await element[1].click();777 const random = Math.floor(40 + Math.random()*60);778 for (let i=0; i<random; i++) {779 const random1 = Math.floor(Math.random()*100);780 // console.log(`pass number : ${random1}`);781 if (random1 < 50) {782 const element = await driver.element("id", "bottom_sheet_container");783 const random1 = Math.floor(200 + Math.random()*200);784 const random2 = Math.floor(Math.random()*150);785 const random3 = Math.floor(Math.random()*147);786 // console.log(`${i} - flick(${-(random1 + random2)}, 0, ${random1 + random3});`)787 await element.flick(-(random1 + random2), 0, random1 + random3);788 }789 await rsleep(2, 10);790 }791 const back = await driver.element("id", "bottom_sheet_container");792 const random1 = Math.floor(800 + Math.random()*200);793 const random2 = Math.floor(Math.random()*150);794 const val = random1 + random2;795 await back.flick(0, val, Math.floor(val/10));796 } catch(e) {797 // console.log(`나의 viewStory 에러: ${e.name}`);798 console.log(e);799 }800}801async function myProfileView(running, driver) {802 try {803 await gotoMain(running, driver);804 const bottomBar = await driver.elements("id", "tab_icon");805 await bottomBar[4].click();806 const random = Math.floor(1 + Math.random()*10);807 for (let i=0; i<random; i++) {808 const element = await driver.element("id", "coordinator_root_layout");809 const random1 = Math.floor(200 + Math.random()*200);810 const random2 = Math.floor(Math.random()*150);811 const random3 = Math.floor(Math.random()*147);812 // console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)813 await element.flick(0, -(random1 + random2), random1 + random3);814 await sleep(0);815 }816 } catch(e) {817 console.log(`나의 피드보기 에러: ${e.name}`);818 }819}820async function myProfileFollowerView(running, driver) {821 try {822 await gotoMain(running, driver);823 const bottomBar = await driver.elements("id", "tab_icon");824 await bottomBar[4].click();825 await sleep(2);826 const element2 = await driver.element("id", "row_profile_header_followers_container");827 await element2.click();828 const random = Math.floor(1 + Math.random()*20);829 for (let i=0; i<random; i++) {830 const element = await driver.element("id", "layout_listview_parent_container");831 const random1 = Math.floor(10 + Math.random()*2000);832 const random2 = Math.floor(Math.random()*169);833 const random3 = Math.floor(Math.random()*152);834 // console.log(`${i} - flick(0, ${-(random1 + random2)}, ${Math.floor((random1 + random3)/10)});`)835 await element.flick(0, -(random1 + random2), Math.floor((random1 + random3)/10));836 await sleep(0);837 }838 } catch(e) {839 console.log(`나의 myProfileFollowerView 에러: ${e.name}`);840 console.log(e);841 }842}843async function myProfileFollowingView(running, driver) {844 try {845 await gotoMain(running, driver);846 const bottomBar = await driver.elements("id", "tab_icon");847 await bottomBar[4].click();848 await sleep(2);849 const element2 = await driver.element("id", "row_profile_header_following_container");850 await element2.click();851 const random = Math.floor(1 + Math.random()*20);852 for (let i=0; i<random; i++) {853 const element = await driver.element("id", "layout_listview_parent_container");854 const random1 = Math.floor(10 + Math.random()*2000);855 const random2 = Math.floor(Math.random()*179);856 const random3 = Math.floor(Math.random()*163);857 // console.log(`${i} - flick(0, ${-(random1 + random2)}, ${Math.floor((random1 + random3)/10)});`)858 await element.flick(0, -(random1 + random2), Math.floor((random1 + random3)/10));859 await sleep(0);860 }861 } catch(e) {862 console.log(`나의 myProfileFollowingView 에러: ${e.name}`);863 console.log(e);864 }865}866async function myActiveView(running, driver) {867 try {868 await gotoMain(running, driver);869 const bottomBar = await driver.elements("id", "tab_icon");870 await bottomBar[3].click();871 const random = Math.floor(5 + Math.random()*30);872 for (let i=0; i<random; i++) {873 const element = await driver.element("id", "newsfeed_pager");874 const random1 = Math.floor(200 + Math.random()*200);875 const random2 = Math.floor(Math.random()*150);876 const random3 = Math.floor(Math.random()*147);877 // console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)878 await element.flick(0, -(random1 + random2), random1 + random3);879 await sleep(0);880 }881 } catch(e) {882 console.log(`나의 myActiveView 에러: ${e.name}`);883 console.log(e);884 }885} 886async function searchView(running, driver) {887 try {888 await gotoMain(running, driver);889 const bottomBar = await driver.elements("id", "tab_icon");890 await bottomBar[1].click();891 const random = Math.floor(10 + Math.random()*60);892 for (let i=0; i<random; i++) {893 const element = await driver.element("id", "recycler_view");894 const random1 = Math.floor(200 + Math.random()*200);895 const random2 = Math.floor(Math.random()*150);896 const random3 = Math.floor(Math.random()*147);897 // console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)898 await element.flick(0, -(random1 + random2), random1 + random3);899 await rsleep(0, 4);900 }901 } catch(e) {902 console.log(`나의 searchView 에러: ${e.name}`);903 }904}905async function searchImageView(running, driver) {906 try {907 await gotoMain(running, driver);908 const bottomBar = await driver.elements("id", "tab_icon");909 await bottomBar[1].click();910 await sleep(2);911 const imageElements = await driver.elements("id", "image_button");912 const key = Math.floor(Math.random()*imageElements.length);913 await imageElements[key].click();914 const random = Math.floor(10 + Math.random()*60);915 for (let i=0; i<random; i++) {916 const element = await driver.element("id", "sticky_header_list");917 const random1 = Math.floor(200 + Math.random()*200);918 const random2 = Math.floor(Math.random()*151);919 const random3 = Math.floor(Math.random()*148);920 // console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)921 await element.flick(0, -(random1 + random2), random1 + random3);922 await rsleep(0, 2);923 }924 } catch(e) {925 console.log(`나의 searchImageView 에러: ${e.name}`);926 console.log(e);927 }928}929async function randomProfileView(running, driver) {930 try {931 await gotoMain(running, driver);932 const bottomBar = await driver.elements("id", "tab_icon");933 await bottomBar[1].click();934 await rsleep(2, 3);935 const imageElements = await driver.elements("id", "image_button");936 const key = Math.floor(Math.random()*imageElements.length);937 await imageElements[key].click();938 await rsleep(0, 1);939 const profileName = await driver.elements("id", "row_feed_photo_profile_name");940 await profileName[0].click();941 const random = Math.floor(1 + Math.random()*10);942 for (let i=0; i<random; i++) {943 const element = await driver.element("id", "coordinator_root_layout");944 const random1 = Math.floor(200 + Math.random()*200);945 const random2 = Math.floor(Math.random()*155);946 const random3 = Math.floor(Math.random()*152);947 // console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)948 await element.flick(0, -(random1 + random2), random1 + random3);949 await sleep(0);950 }951 } catch(e) {952 console.log(`나의 randomProfileView 에러: ${e.name}`);953 console.log(e);954 }955}956async function gotoMain(running, driver) {957 let count = 0;958 while(running.state) {959 if (count > 10) {960 break;961 }962 try {963 let backButton1 = await driver.elements("id", "action_bar_button_back");964 let backButton2 = await driver.elements("id", "action_bar_cancel");965 let backButton3 = await driver.elements("id", "close_button");966 if (backButton1[0]) {967 await backButton1[0].click();968 } else if(backButton2[0]) {969 await backButton2[0].click();970 } else if(backButton3[0]) {971 await backButton3[0].click();972 } else {973 const element = await driver.elements("id", "tab_icon");974 if (element.length > 3) {975 break;976 } else {977 await driver.back();978 }979 }980 } catch(e) { break; }981 count += 1;982 await sleep(1);983 }984}985async function recentPost(running, driver, hashtag) {986 while(running.state) {987 let count = 0;988 try {989 await gotoMain(running, driver);990 const elementTwo = await driver.elements("id", "tab_icon");991 await elementTwo[1].click();992 let searchEditText = await driver.element("id", "action_bar_search_edit_text");993 await searchEditText.click();994 await searchEditText.type(hashtag);995 await driver.hideDeviceKeyboard();996 let searchHashs = await driver.elements("id", "row_hashtag_textview_tag_name");997 let searchTag = null;998 for (let searchHash of searchHashs) {999 let name = await searchHash.text();1000 if (name === `#${hashtag}`) {1001 searchTag = searchHash;1002 break;1003 }1004 }1005 await searchTag.click();1006 break;1007 } catch(e) {1008 count += 1;1009 if (count > 10) {1010 throw {name: 'No SearchHash'};1011 }1012 await sleep(1);1013 }1014 }1015 1016 await sleep(3);1017 while(running.state) {1018 let count = 0;1019 try {1020 let tabButtons = await driver.elements("class name", "android.widget.TextView");1021 let recentButton = null;1022 1023 for (let tabButton of tabButtons) {1024 let name = await tabButton.text();1025 if (name === '최근 게시물') {1026 recentButton = tabButton;1027 break;1028 }1029 }1030 await recentButton.click();1031 break;1032 } catch(e) {1033 count += 1;1034 if (count > 10) {1035 throw {name: 'Not Found RecentButton'};1036 }1037 await sleep(1);1038 }1039 }1040 await rsleep(2,4);1041 1042 while(running.state) {1043 let count = 0;1044 try {1045 let imageViews = await driver.elements("class name", "android.widget.ImageView");1046 let imageElements = [];1047 for(let imageView of imageViews) {1048 const desc = await imageView.getAttribute("content-desc");1049 if (desc && desc.includes('사진')) {1050 imageElements.push(imageView);1051 }1052 }1053 console.log(imageViews.length);1054 console.log(imageElements.length);1055 if (imageElements.length < 1) {1056 throw {name: 'Not Load imageViews'};1057 } 1058 const key = Math.floor(Math.random()*imageElements.length);1059 await imageElements[key].click();1060 break;1061 } catch(e) {1062 console.log('eerrrr');1063 console.log(e);1064 count += 1;1065 if (count > 10) {1066 throw {name: 'Not Found imageViews'};1067 }1068 await sleep(1);1069 }1070 }1071}1072function run(store, http, option, worklog, devOption, count) {1073 console.log(count);1074 const wd = require("wd");1075 const running = {1076 state: true,1077 }1078 let driver;1079 // let appiumServer;1080 let setting = option.instagramOption;1081 let work = {1082 logs: [],1083 instagramWork: [],1084 unfollowUser: [],1085 friends: {1086 date: null,1087 value: [],1088 },1089 beforeText: '',1090 }1091 const opts2 = {1092 platformName: "Android",1093 platformVersion: option.platformVersion,1094 deviceName: option.deviceName,1095 appPackage: "com.instagram.android",1096 appActivity: "com.instagram.mainactivity.MainActivity",1097 systemPort: 8200 + count,1098 fullReset: "false",1099 noReset: "true",1100 };1101 1102 logMessage(http, work, option, '작업을 시작합니다.');1103 setTimeout(async () => {1104 let beforeTime = 0;1105 while(running.state) {1106 try {1107 if (checkActiveTime(setting.activeTimes)) {1108 const currentTime = new Date().getTime();1109 if (currentTime > new Date(option.expired).getTime()) {1110 break;1111 }1112 if (setting.followType === 1) {1113 if(setting.targetTags.length < 1) {1114 break;1115 }1116 if (checkOmit(devOption, worklog)) {1117 logMessage(http, work, option, '액션누락발생 작업을 1일간 중지합니다. ');1118 await sleep(60);1119 continue;1120 }1121 // if (currentTime - beforeTime >= CHECK_TIME) {1122 // await saveAccountLogAndProfile(http, driver, option);1123 // beforeTime = currentTime;1124 // }1125 for (let hashtag of shuffle(setting.targetTags)) {1126 if (!running.state) break;1127 if (checkOmit(devOption, worklog)) break;1128 try { await driver.quit(); } catch (e) { };1129 driver = await wd.promiseChainRemote({1130 host: '127.0.0.1',1131 port: option.appiumPort,1132 });1133 await driver.init(opts2);1134 console.log(hashtag);1135 let sleepTime = 0;1136 // 활동시간 체크 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@1137 1138 let dummyAction = [myFeedView, myDmView, viewStory, myProfileView, myProfileFollowerView, myProfileFollowingView, myActiveView, searchView, searchImageView, randomProfileView];1139 dummyAction = shuffle(dummyAction);1140 let _tempPercent = Math.random()*100;1141 if (_tempPercent < 40) {1142 console.log(`before-DummyAction : ${dummyAction[0].name} - START`);1143 logMessage(http, work, option, `before-DummyAction:${dummyAction[0].name}`);1144 await dummyAction[0](running, driver);1145 console.log(`before-DummyAction : ${dummyAction[0].name} - END`);1146 } else {1147 console.log(`before-DummyAction:PASS (${_tempPercent})`);1148 logMessage(http, work, option, `before-DummyAction:PASS`);1149 }1150 _tempPercent = Math.random()*100;1151 if (_tempPercent < 85) {1152 if (checkActiveTime(setting.activeTimes)) {1153 if (checkFollowLimit(worklog, setting) || checkLikeLimit(worklog, setting) || checkCommentLimit(worklog, setting)) {1154 await sleep(Math.random()*5 + 3);1155 console.log('log 1');1156 if (currentTime - beforeTime >= CHECK_TIME) {1157 await saveAccountLogAndProfile(http, driver, option);1158 beforeTime = currentTime;1159 }1160 // try {1161 await recentPost(running, driver, hashtag);1162 // } catch(e) {1163 // console.log(e);1164 // continue;1165 // }1166 1167 const randomCount = 10 + Math.floor(Math.random() * 150);1168 // const randomCount = 5;1169 for (let i = 0; i < randomCount; i++) {1170 if (!running.state) break;1171 if (checkOmit(devOption, worklog)) break;1172 if (checkFollowLimit(worklog, setting) || checkLikeLimit(worklog, setting) || checkCommentLimit(worklog, setting)) {1173 try {1174 let feedHeader = await driver.element("id", "row_feed_profile_header");1175 let feedFooter = await driver.element("id", "row_feed_view_group_buttons");1176 if (feedHeader && feedFooter) {1177 let headerY = (await feedHeader.getLocation()).y;1178 let footerY = (await feedFooter.getLocation()).y;1179 for(let i = 0; headerY < 160 && i < 10; i++) {1180 try {1181 const element = await driver.element("id", "sticky_header_list");1182 const random1 = Math.floor(10 + Math.random()*100);1183 const random2 = Math.floor(Math.random()*50);1184 // console.log(`${i} - flick(0, ${random1 + random2}, ${random1 + random2});`)1185 await element.flick(0, random1 + random2, random1 + random2);1186 headerY = (await feedHeader.getLocation()).y;1187 } catch(e) {1188 console.log(e);1189 await recentPost(running, driver, hashtag);1190 }1191 }1192 if (headerY < footerY) {1193 let followButton = feedHeader.element("id", "button");1194 let buttonText = await followButton.text();1195 if (buttonText === '팔로우') {1196 let commentButton = await feedFooter.element("id", "row_feed_button_comment");1197 if (commentButton && checkCommentLimit(worklog, setting)) {1198 await submitComment(running, driver, setting, option, hashtag, work, worklog)1199 feedHeader = await driver.element("id", "row_feed_profile_header");1200 feedFooter = await driver.element("id", "row_feed_view_group_buttons");1201 }1202 if (checkLikeLimit(worklog, setting)) {1203 const likeButton = await feedFooter.element("id", "row_feed_button_like");1204 await clickLike(likeButton, option, work, worklog);1205 }1206 console.log(1);1207 console.log(checkFollowLimit(worklog, setting));1208 if (checkFollowLimit(worklog, setting)) {1209 console.log(11);1210 let followButton = null;1211 for(let i = 0; !followButton && i < 10; i++) {1212 try {1213 feedHeader = await driver.element("id", "row_feed_profile_header");1214 feedFooter = await driver.element("id", "row_feed_view_group_buttons");1215 headerY = (await feedHeader.getLocation()).y;1216 footerY = (await feedFooter.getLocation()).y;1217 if (headerY > footerY) {1218 throw 'nop!';1219 }1220 followButton = await feedHeader.element("id", "button");1221 } catch(e) {1222 console.log(e);1223 try {1224 console.log('action2');1225 let action = new wd.TouchAction(driver);1226 const random = 200 + Math.random()*500;1227 action.press({x: 200, y: random})1228 .moveTo({x: 200, y: random + 150})1229 .release();1230 await action.perform();1231 } catch(e) {1232 console.log(e);1233 }1234 }1235 }1236 const user = (await (await feedHeader.element("id", "row_feed_photo_profile_name")).text()).replace(/[ •]/g, '');1237 await clickFollow(followButton, option, work, worklog, setting, user, hashtag);1238 } 1239 sleepTime += (Math.random()*90 + 90);1240 console.log(`sleepTime: ${sleepTime}`);1241 }1242 }1243 }1244 } catch(e) { }1245 try {1246 const element = await driver.element("id", "sticky_header_list");1247 const random1 = Math.floor(200 + Math.random()*240);1248 const random2 = Math.floor(Math.random()*139);1249 const random3 = Math.floor(Math.random()*128);1250 // console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)1251 await element.flick(0, -(random1 + random2), random1 + random3);1252 } catch(e) {1253 console.log(e);1254 await recentPost(running, driver, hashtag);1255 }1256 }1257 saveLogDetail(http, work);1258 }1259 } else {1260 saveLogDetail(http, work);1261 await sleep(120);1262 }1263 saveLogDetail(http, work);1264 } else {1265 await sleep(120);...

Full Screen

Full Screen

Test.js

Source:Test.js Github

copy

Full Screen

...87 const random1 = Math.floor(200 + Math.random()*200);88 const random2 = Math.floor(Math.random()*150);89 const random3 = Math.floor(Math.random()*147);90 console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)91 await element.flick(0, -(random1 + random2), random1 + random3);92 await sleep(0);93 }94 } catch(e) {95 console.log(`나의 피드보기 에러: ${e.name}`);96 }97}98async function myDmView(driver) {99 try {100 await gotoMain(driver);101 console.log('나의 디엠보기 시작');102 const element = await driver.element("id", "action_bar_inbox_button");103 await element.click();104 const random = Math.floor(Math.random()*10);105 console.log(`랜덤카운트 : ${random}`);106 for (let i=0; i<random; i++) {107 const element = await driver.element("id", "inbox_refreshable_thread_list_recyclerview");108 const random1 = Math.floor(200 + Math.random()*200);109 const random2 = Math.floor(Math.random()*150);110 const random3 = Math.floor(Math.random()*147);111 console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)112 await element.flick(0, -(random1 + random2), random1 + random3);113 await sleep(0);114 }115 const inboxs = await driver.elements("id", "row_inbox_container");116 const inbox = inboxs[Math.floor(Math.random()*inboxs.length)];117 inbox.click();118 const random2 = Math.floor(Math.random()*10);119 console.log(`랜덤카운트 : ${random2}`);120 for (let i=0; i<random2; i++) {121 const element = await driver.element("id", "message_list");122 const random1 = Math.floor(200 + Math.random()*200);123 const random2 = Math.floor(Math.random()*150);124 const random3 = Math.floor(Math.random()*147);125 console.log(`${i} - flick(0, ${random1 + random2}, ${random1 + random3});`)126 await element.flick(0, random1 + random2, random1 + random3);127 await sleep(0);128 }129 } catch(e) {130 console.log(`나의 디엠보기 에러: ${e.name}`);131 console.log(e);132 }133}134async function viewStory(driver) {135 try {136 await gotoMain(driver);137 console.log('viewStory Start;')138 await sleep(2);139 const element = await driver.elements("id", "outer_container");140 await element[1].click();141 const random = Math.floor(40 + Math.random()*60);142 console.log(`randomCount: ${random}`);143 for (let i=0; i<random; i++) {144 const random1 = Math.floor(Math.random()*100);145 console.log(`pass number : ${random1}`);146 if (random1 < 50) {147 const element = await driver.element("id", "bottom_sheet_container");148 const random1 = Math.floor(200 + Math.random()*200);149 const random2 = Math.floor(Math.random()*150);150 const random3 = Math.floor(Math.random()*147);151 console.log(`${i} - flick(${-(random1 + random2)}, 0, ${random1 + random3});`)152 await element.flick(-(random1 + random2), 0, random1 + random3);153 }154 await rsleep(2, 10);155 }156 const back = await driver.element("id", "bottom_sheet_container");157 const random1 = Math.floor(800 + Math.random()*200);158 const random2 = Math.floor(Math.random()*150);159 const val = random1 + random2;160 await back.flick(0, val, Math.floor(val/10));161 } catch(e) {162 console.log(`나의 viewStory 에러: ${e.name}`);163 console.log(e);164 }165}166async function myProfileView(driver) {167 try {168 await gotoMain(driver);169 console.log('나의 피드보기 시작');170 const bottomBar = await driver.elements("id", "tab_icon");171 await bottomBar[4].click();172 const random = Math.floor(1 + Math.random()*10);173 console.log(`랜덤카운트 : ${random}`);174 for (let i=0; i<random; i++) {175 const element = await driver.element("id", "coordinator_root_layout");176 const random1 = Math.floor(200 + Math.random()*200);177 const random2 = Math.floor(Math.random()*150);178 const random3 = Math.floor(Math.random()*147);179 console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)180 await element.flick(0, -(random1 + random2), random1 + random3);181 await sleep(0);182 }183 } catch(e) {184 console.log(`나의 피드보기 에러: ${e.name}`);185 }186}187async function myProfileFollowerView(driver) {188 try {189 await gotoMain(driver);190 console.log('나의 myProfileFollowerView 시작');191 const bottomBar = await driver.elements("id", "tab_icon");192 await bottomBar[4].click();193 await sleep(2);194 const element2 = await driver.element("id", "row_profile_header_followers_container");195 await element2.click();196 const random = Math.floor(1 + Math.random()*20);197 console.log(`랜덤카운트 : ${random}`);198 for (let i=0; i<random; i++) {199 const element = await driver.element("id", "layout_listview_parent_container");200 const random1 = Math.floor(10 + Math.random()*2000);201 const random2 = Math.floor(Math.random()*169);202 const random3 = Math.floor(Math.random()*152);203 console.log(`${i} - flick(0, ${-(random1 + random2)}, ${Math.floor((random1 + random3)/10)});`)204 await element.flick(0, -(random1 + random2), Math.floor((random1 + random3)/10));205 await sleep(0);206 }207 } catch(e) {208 console.log(`나의 myProfileFollowerView 에러: ${e.name}`);209 console.log(e);210 }211}212async function myProfileFollowingView(driver) {213 try {214 await gotoMain(driver);215 console.log('나의 myProfileFollowingView 시작');216 const bottomBar = await driver.elements("id", "tab_icon");217 await bottomBar[4].click();218 await sleep(2);219 const element2 = await driver.element("id", "row_profile_header_following_container");220 await element2.click();221 const random = Math.floor(1 + Math.random()*20);222 console.log(`랜덤카운트 : ${random}`);223 for (let i=0; i<random; i++) {224 const element = await driver.element("id", "layout_listview_parent_container");225 const random1 = Math.floor(10 + Math.random()*2000);226 const random2 = Math.floor(Math.random()*179);227 const random3 = Math.floor(Math.random()*163);228 console.log(`${i} - flick(0, ${-(random1 + random2)}, ${Math.floor((random1 + random3)/10)});`)229 await element.flick(0, -(random1 + random2), Math.floor((random1 + random3)/10));230 await sleep(0);231 }232 } catch(e) {233 console.log(`나의 myProfileFollowingView 에러: ${e.name}`);234 console.log(e);235 }236}237async function myActiveView(driver) {238 try {239 await gotoMain(driver);240 console.log('나의 myActiveView 시작');241 const bottomBar = await driver.elements("id", "tab_icon");242 await bottomBar[3].click();243 const random = Math.floor(5 + Math.random()*30);244 console.log(`랜덤카운트 : ${random}`);245 for (let i=0; i<random; i++) {246 const element = await driver.element("id", "newsfeed_pager");247 const random1 = Math.floor(200 + Math.random()*200);248 const random2 = Math.floor(Math.random()*150);249 const random3 = Math.floor(Math.random()*147);250 console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)251 await element.flick(0, -(random1 + random2), random1 + random3);252 await sleep(0);253 }254 } catch(e) {255 console.log(`나의 myActiveView 에러: ${e.name}`);256 console.log(e);257 }258} 259async function searchView(driver) {260 try {261 await gotoMain(driver);262 console.log('나의 searchView 시작');263 const bottomBar = await driver.elements("id", "tab_icon");264 await bottomBar[1].click();265 const random = Math.floor(10 + Math.random()*60);266 console.log(`랜덤카운트 : ${random}`);267 for (let i=0; i<random; i++) {268 const element = await driver.element("id", "recycler_view");269 const random1 = Math.floor(200 + Math.random()*200);270 const random2 = Math.floor(Math.random()*150);271 const random3 = Math.floor(Math.random()*147);272 console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)273 await element.flick(0, -(random1 + random2), random1 + random3);274 await rsleep(0, 4);275 }276 } catch(e) {277 console.log(`나의 searchView 에러: ${e.name}`);278 }279}280async function searchImageView(driver) {281 try {282 await gotoMain(driver);283 console.log('나의 searchImageView 시작');284 const bottomBar = await driver.elements("id", "tab_icon");285 await bottomBar[1].click();286 await sleep(2);287 const imageElements = await driver.elements("id", "image_button");288 console.log(imageElements);289 const key = Math.floor(Math.random()*imageElements.length);290 console.log(key);291 await imageElements[key].click();292 const random = Math.floor(10 + Math.random()*60);293 console.log(`랜덤카운트 : ${random}`);294 for (let i=0; i<random; i++) {295 const element = await driver.element("id", "sticky_header_list");296 const random1 = Math.floor(200 + Math.random()*200);297 const random2 = Math.floor(Math.random()*151);298 const random3 = Math.floor(Math.random()*148);299 console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)300 await element.flick(0, -(random1 + random2), random1 + random3);301 await rsleep(0, 2);302 }303 } catch(e) {304 console.log(`나의 searchImageView 에러: ${e.name}`);305 console.log(e);306 }307}308async function randomProfileView(driver) {309 try {310 await gotoMain(driver);311 console.log('나의 randomProfileView 시작');312 const bottomBar = await driver.elements("id", "tab_icon");313 await bottomBar[1].click();314 await rsleep(2, 3);315 const imageElements = await driver.elements("id", "image_button");316 console.log(imageElements);317 const key = Math.floor(Math.random()*imageElements.length);318 console.log(key);319 await imageElements[key].click();320 await rsleep(0, 1);321 const profileName = await driver.elements("id", "row_feed_photo_profile_name");322 await profileName[0].click();323 const random = Math.floor(1 + Math.random()*10);324 console.log(`랜덤카운트 : ${random}`);325 for (let i=0; i<random; i++) {326 const element = await driver.element("id", "coordinator_root_layout");327 const random1 = Math.floor(200 + Math.random()*200);328 const random2 = Math.floor(Math.random()*155);329 const random3 = Math.floor(Math.random()*152);330 console.log(`${i} - flick(0, ${-(random1 + random2)}, ${random1 + random3});`)331 await element.flick(0, -(random1 + random2), random1 + random3);332 await sleep(0);333 }334 } catch(e) {335 console.log(`나의 randomProfileView 에러: ${e.name}`);336 console.log(e);337 }338}339async function gotoMain(driver) {340 while(true) {341 try {342 let backButton1 = await driver.elements("id", "action_bar_button_back");343 let backButton2 = await driver.elements("id", "action_bar_cancel");344 let backButton3 = await driver.elements("id", "close_button");345 if (backButton1[0]) {...

Full Screen

Full Screen

basic.js

Source:basic.js Github

copy

Full Screen

1/**2 * User: dengwei3 * Date: 16-7-184 * Time: 下午4:145 * Author: dw1130736 * Description: 基础类7 */8var basic = {9 init: function () {//唤起app,并打印测试信息10 var targetName = this.target().name();11 var appName = this.target().frontMostApp().name();12 var deviceModel = this.target().model();13 var osVersion = this.target().systemVersion();14 var osName = this.target().systemName();15 var appVersion = this.target().frontMostApp().bundleID();16 UIALogger.logStart("UI驱动开始...");17 UIALogger.logMessage("调试包名称:" + appName);18 UIALogger.logMessage("测试包版本:" + appVersion);19 UIALogger.logMessage("设备名称:" + targetName);20 UIALogger.logMessage("设备型号:" + deviceModel);21 UIALogger.logMessage("系统版本:" + osVersion);22 UIALogger.logMessage("操作系统类型:" + osName);23 UIALogger.logMessage("monkeyInfoLabel: " + UIATarget.localTarget().systemVersion() + " " + UIATarget.localTarget().name());24 },25 isNewMain:function(){26 return true;27 },28 appVersion: function(){29 return this.target().frontMostApp().bundleID();30 },31 screenRect: function () {//获取当前app的主window32 return this.target().rect();33 },34 body: function () {//获取当前app的主window35 return this.target().frontMostApp().mainWindow();36 },37 app: function () {//获取当前设备的frontMostApp38 return this.target().frontMostApp();39 },40 target: function () {//获取当前设备的localTargetjj41 return UIATarget.localTarget();42 },43 /**44 * 获取当前设备的mainWindow45 * @returns {*}46 */47 window: function () {//获取当前设备的localTargetjj48 return UIATarget.localTarget().frontMostApp().mainWindow();49 },50 /**51 * 调用shell,key是对应.sh文件的绝对路径。不能执行sudo权限的脚本。52 * @param key53 */54 shell: function (key) {55 var result = this.target().host().performTaskWithPathArgumentsTimeout("/bin/sh", [key], 5);56 // basic.say("exitCode: " + result.exitCode);57 basic.say("stdout: " + result.stdout);58 // basic.say("stderr: " + result.stderr);59 },60 wait: function (seconds) {//等待数秒。seconds是秒数。61 this.target().delay(seconds);62 },63 // tap: function(ele){//根据位置信息,强行点击一个控件.64 // if(ele==null){65 // this.warning('basic.tap()并没有受到合法参数!');66 // return null;67 // }68 // var tapPointHorizontal =parseFloat(ele.rect().origin.x+(0.5*ele.rect().size.width));69 // var tapPointVertical =parseFloat(ele.rect().origin.y+(0.5*ele.rect().size.height));70 // // basic.say(''+ele.rect().origin.x);71 // // basic.say(''+ele.rect().origin.y);72 // // basic.say(''+ele.rect().size.width);73 // // basic.say(''+ele.rect().size.height);74 //75 // // this.say("the x is "+tapPointHorizontal+" and the y is "+tapPointVertical);76 // this.target().tap({x:tapPointHorizontal,y:tapPointVertical});77 // },78 tree: function () {//在log中打印控件树.79 this.target().logElementTree();80 },81 longTap: function (tmpX, tmpY) {//长按某点。tmpX和tmpY分别是某点的xy坐标。82 this.target().tapWithOptions(83 {x: tmpX, y: tmpY},84 {85 duration: 286 }87 );88 this.wait(miniSleep);89 },90 flickUp: function (element) {//向上滑动控件。rate滑动对比控件本身比例91 element.flickInsideWithOptions({startOffset: {x: 0.5, y: 0.8}, endOffset: {x: 0.5, y: 0.2}});92 this.wait(miniSleep);93 },94 flickDown: function (element) {//向下滑动控件。rate滑动对比控件本身比例95 element.flickInsideWithOptions({startOffset: {x: 0.5, y: 0.2}, endOffset: {x: 0.5, y: 0.8}});96 this.wait(miniSleep);97 },98 flickLeft: function (element) {//向左滑动控件。rate滑动对比控件本身比例99 element.flickInsideWithOptions({startOffset: {x: 0.8, y: 0.5}, endOffset: {x: 0.2, y: 0.5}});100 this.wait(miniSleep);101 },102 flickRight: function (element) {//向右滑动控件。rate滑动对比控件本身比例103 element.flickInsideWithOptions({startOffset: {x: 0.2, y: 0.5}, endOffset: {x: 0.8, y: 0.5}});104 this.wait(miniSleep);105 },106 rollUp: function (key) {//向上划动。key为空时,在屏幕中间向上划。key不为空时,则在数字key标定的横坐标向上划107 var position;108 if (key == null) {109 position = this.target().rect().size.width * 0.5;110 } else {111 position = key;112 }113 this.target().dragFromToForDuration(114 {x: position, y: this.target().rect().size.height * 0.7},115 {x: position, y: this.target().rect().size.height * 0.3},116 0.5117 );118 this.wait(miniSleep);119 },120 rollWithPosition: function (startX,startY,endX,endY) {121 this.target().dragFromToForDuration(122 {x: startX, y: startY},123 {x: endX, y: endY},124 0.5125 );126 this.wait(miniSleep);127 },128 rollDown: function (key) {//向下划动。key为空时,在屏幕中间向上划。key不为空时,则在数字key标定的横坐标向上划129 var position;130 if (key == null) {131 position = this.target().rect().size.width * 0.5;132 } else {133 position = key;134 }135 this.target().dragFromToForDuration(136 {x: position, y: this.target().rect().size.height * 0.3},137 {x: position, y: this.target().rect().size.height * 0.7},138 0.5139 );140 this.wait(miniSleep);141 },142 rollLeft: function (key) {//向左划动。key为空时,在屏幕中间向左划。key不为空时,则在数字key标定的纵坐标向左划143 var position;144 if (key == null) {145 position = this.target().rect().size.height * 0.5;146 } else {147 position = key;148 }149 this.target().dragFromToForDuration(150 {x: this.target().rect().size.width * 0.7, y: position},151 {x: this.target().rect().size.width * 0.3, y: position},152 0.5153 );154 this.wait(miniSleep);155 },156 longRollLeft: function (key) {//向左划动。key为空时,在屏幕中间向左划。key不为空时,则在数字key标定的纵坐标向左划157 var position;158 if (key == null) {159 position = this.target().rect().size.height * 0.5;160 } else {161 position = key;162 }163 this.target().dragFromToForDuration(164 {x: this.target().rect().size.width * 0.9, y: position},165 {x: this.target().rect().size.width * 0.1, y: position},166 0.5167 );168 this.wait(miniSleep);169 },170 rollRight: function (key) {//向右划动。key为空时,在屏幕中间向右划。key不为空时,则在数字key标定的纵坐标向右划171 var position;172 if (key == null) {173 position = this.target().rect().size.height * 0.5;174 } else {175 position = key;176 }177 this.target().dragFromToForDuration(178 {x: this.target().rect().size.width * 0.3, y: position},179 {x: this.target().rect().size.width * 0.7, y: position},180 0.5181 );182 this.wait(miniSleep);183 },184 rotate: function () {//旋转地图180度185 this.target().rotateWithOptions(186 {x: this.target().rect().size.width * 0.5, y: this.target().rect().size.height * 0.5},//手势中心点坐标187 {188 duration: 1, //手势时长189 radius: this.target().rect().size.width * 0.1, //半径190 rotation: Math.PI, //旋转角度191 touchCount: 2192 }//手势手指个数193 );194 this.wait(miniSleep);195 },196 photo: function (key) {//截图,key是图片名称197 this.target().captureRectWithName({198 origin: {x: 0, y: 20},199 size: {width: this.target().rect().size.width, height: this.target().rect().size.height - 20}200 }, key);201 },202 /**203 * 点击屏幕坐标204 * @param x205 * @param y206 */207 tap: function (x, y) {208 this.target().tap({x: x, y: y});209 },210 /**211 * 点击一个横向控件的一部分。key1是块数,key2是第几块212 * @param ele213 * @param key1214 * @param key2215 */216 tapPart: function (ele, key1, key2) {217 var step = (1 / key1) * ele.rect().size.width;218 var tapPointHorizontal = parseFloat(ele.rect().origin.x + (key2 - 0.5) * step);219 var tapPointVertical = parseFloat(ele.rect().origin.y + (0.5 * ele.rect().size.height));220 this.target().tap({x: tapPointHorizontal, y: tapPointVertical});221 },222 randomItem: function (arr) {//输入一个数组,返回数组中的随机一个成员223 var i = Math.round(Math.random() * (arr.length - 1));224 return arr[i];225 },226 randomNum: function (min, max) {//给出一个随机整数,取值范围是[min,max]227 return Math.round(Math.random() * (max - min)) + min;228 },229 /**230 * 锁屏231 * @param times : 单位为秒232 */233 lock: function (times) {//锁屏key秒后再解锁。若key为空则默认锁2秒。234 var seconds;235 if (key == null) {236 seconds = 2;237 } else {238 seconds = key;239 }240 basic.target().lockForDuration(seconds);241 },242 /**243 * app置后台244 * @param times: 单位为秒245 */246 home: function (times) {//点击home键把app切后台,key秒后再切回来。key为空则默认2秒后切回来。247 var seconds;248 if (key == null) {249 seconds = 2;250 } else {251 seconds = key;252 }253 basic.target().deactivateApp(seconds);254 },255 setDeviceOrientationUp: function () {//调整手机的重力感应,让手机以为自己是正向摆放的。256 basic.target().setDeviceOrientation(UIA_DEVICE_ORIENTATION_PORTRAIT);257 },258 setDeviceOrientationDown: function () {//调整手机的重力感应,让手机以为自己是倒立摆放的。259 basic.target().setDeviceOrientation(UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN);260 },261 setDeviceOrientationLeft: function () {//调整手机的重力感应,让手机以为自己是左边向下摆放的。262 basic.target().setDeviceOrientation(UIA_DEVICE_ORIENTATION_LANDSCAPELEFT);263 },264 setDeviceOrientationRight: function () {//调整手机的重力感应,让手机以为自己是右边向下摆放的。265 basic.target().setDeviceOrientation(UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT);266 },267 voiceUp: function (key) {//点击音量增大按钮。key是点击次数,key为空时默认点一下。268 var times;269 if (key == null) {270 times = 1;271 } else {272 times = key;273 }274 for (var i = 0; i < times; i++) {275 this.target().clickVolumeUp();276 this.wait(0.3);277 }278 },279 voiceDown: function (key) {//点击音量减小按钮。key是点击次数,key为空时默认点一下。280 var times;281 if (key == null) {282 times = 1;283 } else {284 times = key;285 }286 for (var i = 0; i < times; i++) {287 this.target().clickVolumeDown();288 this.wait(0.3);289 }290 },291 back: function () {//点击左上角返回按钮292 this.target().tap({x: 27, y: 45});293 this.wait(miniSleep);294 }295}296var eleObject = {297 info: {298 name: '未命名控件',299 part: 1,300 },301 name: function () {302 return this.info.name;303 },304 head: function () {305 basic.say("将要操作\"" + this.info.name + "\"控件了哦");306 },307 tail: function () {308 basic.say("已经操作过\"" + this.info.name + "\"控件了哦");309 },310 part: function () {311 return this.info.part;312 },...

Full Screen

Full Screen

Tester.js

Source:Tester.js Github

copy

Full Screen

1const { Session } = require('./Session');2class Tester {3 static get Session() {4 return Session;5 }6 constructor(options) {7 const Session = this.constructor.Session;8 this.session = options.session || new Session(options);9 this.currentElements = [];10 this.currentElementIndex = 0;11 this.currentElementsSelector = null;12 this.executeChain = null;13 this.timeout = 10000;14 this.promise = new Promise((resolve, reject) => {15 this.executeChain = resolve;16 });17 }18 get currentElement() {19 if (this.currentElementIndex >= this.currentElements.length) {20 throw new Error(`could not find element "${this.currentElementsSelector}[${this.currentElementIndex}]"`);21 } else {22 return this.currentElements[this.currentElementIndex];23 }24 }25 /**26 * Set how long to wait for various things to happen before throwing an error.27 * 28 * For example if no elements are found for a specific selector an error is thrown29 * after trying to find them for `timeout` milliseconds.30 * 31 * @param {number} timeout32 * Timeout in milliseconds.33 */34 setImplicitWaitTimeout(timeout) {35 return this.then(() => {36 this.timeout = value(timeout);37 return this.session.setImplicitWaitTimeout(this.timeout);38 });39 }40 /**41 * Select the `index`th result element of the previous `elements` call as the current element.42 * 43 * @returns {WebDriverChain}44 */45 at(index) {46 return this.then(() => {47 this.currentElementIndex = value(index);48 });49 }50 /**51 * Select the `index`th last result element of the previous `elements` call as the current element.52 * 53 * @returns {WebDriverChain}54 */55 reverseAt(index) {56 return this.then(() => {57 this.currentElementIndex = this.currentElements.length - value(index) - 1;58 });59 }60 /**61 * This must be called once to start things off.62 * 63 * @returns {Promise}64 * When this promise is resolved, the test chain execution is started.65 */66 init() {67 return this.session.create().then(() => this.executeChain());68 }69 /**70 * This must be called once after the tests to release resources.71 * 72 * @returns {Promise}73 */74 quit() {75 return this.then(() => this.session.destroy());76 }77 /**78 * Finds elements.79 * 80 * @param {string} using81 * The algorithm to use. Must be one of ['xpath', 'class name', 'id'].82 * 83 * @param {string} selector84 * The element selector.85 * 86 * @returns {WebDriverChain}87 */88 elements({using, selector}) {89 return this.then(() => {90 return this.session.elements({using: value(using), selector: value(selector)}).then(elements => {91 this.currentElements = elements;92 this.currentElementIndex = 0;93 this.currentElementsSelector = selector;94 return elements;95 });96 });97 }98 /**99 * Find elements using xpath selector.100 * 101 * @param {string} selector 102 * @returns {WebDriverChain}103 */104 elementsByXpath(selector) {105 return this.elements({using: 'xpath', selector});106 }107 /**108 * Find elements using id.109 * 110 * @param {string} selector 111 * @returns {WebDriverChain}112 */113 elementsById(selector) {114 return this.elements({using: 'id', selector});115 }116 /**117 * Find elements using class name.118 * 119 * @param {string} selector 120 * @returns {WebDriverChain}121 */122 elementsByClassName(selector) {123 return this.elements({using: 'class name', selector});124 }125 /**126 * Click the current element.127 */128 click() {129 return this.then(() => this.currentElement.click());130 }131 /**132 * Send text to the current element.133 */134 setValue(val) {135 return this.then(() => this.currentElement.setValue(value(val)));136 }137 /**138 * Clear text from the current element.139 */140 clear() {141 return this.then(() => this.currentElement.clear());142 }143 /**144 * Return the text of the current element145 */146 text() {147 return this.then(() => this.currentElement.text());148 }149 /**150 * Return the bounding box of the current element151 */152 rect() {153 return this.then(() => this.currentElement.rect());154 }155 /**156 * Flick the current element.157 */158 flick({xoffset, yoffset, speed}) {159 return this.then(() => {160 return this.currentElement.flick({161 xoffset: value(xoffset), 162 yoffset: value(yoffset), 163 speed: value(speed)164 });165 });166 }167 /**168 * Flick the current element up.169 */170 flickUp(offset, speed) {171 return this.then(() => this.currentElement.flickUp(value(offset), value(speed)));172 }173 /**174 * Flick the current element down.175 */176 flickDown(offset, speed) {177 return this.then(() => this.currentElement.flickDown(value(offset), value(speed)));178 }179 /**180 * Flick the current left.181 */182 flickLeft(offset, speed) {183 return this.then(() => this.currentElement.flickLeft(value(offset), value(speed)));184 }185 /**186 * Flick the current right.187 */188 flickRight(offset, speed) {189 return this.then(() => this.currentElement.flickRight(value(offset), value(speed)));190 }191 /**192 * Assert that the current element is visible.193 */194 isDisplayed() {195 return this.then(() => this._assertDisplayed(true));196 }197 /**198 * Assert that the current element is visible.199 */200 isNotDisplayed() {201 return this.then(() => this._assertDisplayed(false));202 }203 /**204 * @private205 */206 _assertDisplayed(expectedValue) {207 // If the element is not found at all, it is not visible.208 if (!expectedValue && this.currentElements.length === 0) {209 return true;210 }211 return this.currentElement212 .isDisplayed()213 .then(isDisplayed => {214 if (isDisplayed !== expectedValue) {215 throw new Error(`element "${this.currentElementsSelector}[${this.currentElementIndex}]" is${expectedValue ? ' not ' : ' '}displayed`);216 } else {217 return true;218 }219 });220 }221 /**222 * Wait until the current element is visible. An error is thrown if the element is not223 * visible after the implicit wait timeout. See `setImplicitWaitTimeout` method.224 */225 waitDisplayed(timeout) {226 return this.then(() => {227 return this.poll(() => {228 return this._assertDisplayed(true);229 }, value(timeout));230 });231 }232 /**233 * Wait until the current element is not visible. An error is thrown if the element is234 * visible after the implicit wait timeout. See `setImplicitWaitTimeout` method.235 */236 waitNotDisplayed(timeout) {237 return this.then(() => {238 return this.poll(() => {239 return this._assertDisplayed(false);240 }, value(timeout));241 });242 }243 /**244 * Assert that the current element is enabled.245 */246 isEnabled() {247 return this.then(() => this._assertEnabled(true));248 }249 /**250 * Assert that the current element is not enabled.251 */252 isDisabled() {253 return this.then(() => this._assertEnabled(false));254 }255 /**256 * @private257 */258 _assertEnabled(expectedValue) {259 return this.currentElement260 .isEnabled()261 .then(isEnbaled => {262 if (isEnbaled !== expectedValue) {263 throw new Error(`element "${this.currentElementsSelector}[${this.currentElementIndex}]" is${expectedValue ? ' not ' : ' '}enabled`);264 } else {265 return true;266 }267 });268 }269 /**270 * Wait until the current element is enabled. An error is thrown if the element is not271 * enabled after the implicit wait timeout. See `setImplicitWaitTimeout` method.272 */273 waitEnabled(timeout) {274 return this.then(() => {275 return this.poll(() => {276 return this._assertEnabled(true);277 }, value(timeout));278 });279 }280 /**281 * Wait until the current element is disabled. An error is thrown if the element is not282 * disabled after the implicit wait timeout. See `setImplicitWaitTimeout` method.283 */284 waitDisabled(timeout) {285 return this.then(() => {286 return this.poll(() => {287 return this._assertEnabled(false);288 }, value(timeout));289 });290 }291 /**292 * Assert that the current element is selected.293 */294 isSelected() {295 return this.then(() => this._assertSelected(true));296 }297 /**298 * Assert that the current element is not selected.299 */300 isNotSelected() {301 return this.then(() => this._assertSelected(false));302 }303 /**304 * @private305 */306 _assertSelected(expectedValue) {307 return this.currentElement308 .isSelected()309 .then(isSelected => {310 if (isSelected !== expectedValue) {311 throw new Error(`element "${this.currentElementsSelector}[${this.currentElementIndex}]" is${expectedValue ? ' not ' : ' '}selected`);312 } else {313 return true;314 }315 });316 }317 /**318 * Wait until the current element is selected. An error is thrown if the element is not319 * selected after the implicit wait timeout. See `setImplicitWaitTimeout` method.320 */321 waitSelected(timeout) {322 return this.then(() => {323 return this.poll(() => {324 return this._assertSelected(true);325 }, value(timeout));326 });327 }328 /**329 * Wait until the current element is not selected. An error is thrown if the element is330 * selected after the implicit wait timeout. See `setImplicitWaitTimeout` method.331 */332 waitNotSelected(timeout) {333 return this.then(() => {334 return this.poll(() => {335 return this._assertSelected(false);336 }, value(timeout));337 });338 }339 /**340 * Wait until the current element stops moving.341 */342 waitStop(timeout) {343 return this.then(() => {344 let prevRect = null;345 346 return this.poll(() => {347 return this.currentElement.rect().then(rect => {348 if (prevRect === null || prevRect.x !== rect.x || prevRect.y !== rect.y) {349 prevRect = rect;350 // Retry.351 throw new Error(`element "${this.currentElementsSelector}[${this.currentElementIndex}]" did not stop moving`);352 }353 });354 }, value(timeout));355 });356 }357 sleep(time) {358 return this.then(() => new Promise(resolve => setTimeout(resolve, value(time))));359 }360 windowRect() {361 return this.then(() => this.session.windowRect());362 }363 resetApp() {364 return this.then(() => this.session.resetApp());365 }366 hideKeyboard() {367 return this.then(() => this.session.hideKeyboard());368 }369 then(...args) {370 this.promise = this.promise.then(...args);371 return this;372 }373 catch(...args) {374 this.promise = this.promise.catch(...args);375 return this;376 }377 poll(op, timeout) {378 const pollInterval = 50;379 const startTime = Date.now();380 const doPoll = () => {381 return op().catch(err => {382 const theTimeout = timeout || this.timeout;383 if (Date.now() - startTime < theTimeout) {384 return delay(pollInterval).then(doPoll);385 } else {386 throw err;387 }388 });389 };390 return doPoll();391 }392}393function delay(delay) {394 return new Promise(resolve => setTimeout(resolve, delay));395}396function value(val) {397 if (typeof val === 'function') {398 return val();399 } else {400 return val;401 }402}403module.exports = {404 Tester...

Full Screen

Full Screen

iOSMonkey2.js

Source:iOSMonkey2.js Github

copy

Full Screen

1/*2 *3 *4 */5function iOSMonkey2(){6 this.elementArray = null;7 this._addToArray = function(root,len){8 var rootname = root.name()+""9 rootname = rootname.toLowerCase();10 if( !this._isIndicator(root) && root.toString() != "[object UIAKey]" && rootname.match("notap"+"$") !="notap" ){11 if(root.isEnabled() && root.isVisible()){12 if(len==0){13 if(root.hitpoint() != null){14 var rect = root.hitpoint();15 if(rect.y>20){16 this.elementArray.push(root);17 }18 }19 }20 if(this._toFlick(root) || this._toType(root)){21 this.elementArray.push(root);22 }23 }24 }25 }26 this._iterator = function(root){27 var eleArray = null;28 if(root.toString() !="[object UIAWebView]" && root.toString() != "[object UIAKeyboard]"){29 eleArray = root.elements();30 this._addToArray(root,eleArray.length);31 if(eleArray.length != 0 && eleArray != null){32 for(var i = 0; i< eleArray.length; i++){33 this._iterator(eleArray[i]);34 }35 }36 }37 }38 this._isIndicator = function(element){39 return element.toString().match("Indicator"+"$")=="Indicator";40 }41 this._findIndicator = function(root){42 var elements = root.elements();43 if(elements.length !=0 && elements != null){44 for(var i =0; i<elements.length;i++){45 if(this._isIndicator(elements[i])){46 return 1;47 }48 this._findIndicator(elements[i]);49 }50 }51 }52 this._getAllElements = function(){53 var app = UIATarget.localTarget().frontMostApp();54 this.elementArray = null;55 this.elementArray = new Array();56 this._iterator(app);57 }58 this._getElementAncestry = function(element){59 var arr = element.ancestry();60 var tmp = ""61 for(var i = 0; i< arr.length; i++){62 tmp += arr[i].toString()+"->"63 }64 return tmp;65 }66 this._selector = function(){67 this._getAllElements();68 var len = this.elementArray.length;69 //UIALogger.logMessage(len+"");70 var random = Math.round(Math.random() * len);71 if (random == len){72 random = random-1;73 }74 return this.elementArray[random];75 }76 this._toFlick = function(element){77 if(element.toString()=="[object UIATableView]" || element.toString()=="[object UIAScrollView]" || element.toString()=="[object UIATableCell]"){78 return 1;79 }80 return 0;81 }82 this._toType = function(element){83 if(element.toString()=="[object UIATextField]" || element.toString()=="[object UIASecureTextField]" || element.toString()=="[object UIATextView]"){84 return 1;85 }86 return 0;87 }88 this._tap = function(element){89 if(element.toString()=="[object UIASwitch]"){90 if(element.value() != "" && element.value() != null){91 element.setValue(this._falseString(element.value()));92 }93 }else{94 var x = Math.random().toFixed(2);95 var y = Math.random().toFixed(2);96 element.tapWithOptions({tapOffset:{x:x,y:y}});97 }98 }99 this._flick = function(element){100 //element.scrollToVisible();101 var x = Math.random().toFixed(2);102 var y = Math.random().toFixed(2);103 element.flickInsideWithOptions({startOffset:{x:0.5, y:0.5}, endOffset:{x:x,y:y}});104 }105 this._getAppSize = function(){106 var rect = UIATarget.localTarget().frontMostApp().rect();107 return rect;108 }109 this._type = function(element){110 var len = Math.round(Math.random()*100);111 var value = this._randomChar(len);112 element.setValue(value);113 }114 this._falseString = function(value){115 if(value=="0"){116 return "1";117 }else{118 return "0";119 }120 }121 this._randomChar = function(len){122 var x="0123456789qwertyuioplkjhgfdsazxcvbnm";123 var tmp="";124 for(var i = 0;i < len;i++){125 tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);126 }127 return tmp;128 }129 this.operator = function(){130 var element = this._selector();131 UIALogger.logMessage("本次操作的对象的类型是:"+element.toString());132 var ancestry = this. _getElementAncestry(element);133 UIALogger.logMessage(ancestry+element.toString()+"->name:"+element.name());134 if (this._toFlick(element)){135 this._flick(element);136 }else if(this._toType(element)){137 this._type(element);138 }else{139 if(element.hitpoint() != null){140 this._tap(element);141 }142 }143 }144 this.screenShoot = function(imageName){145 var target = UIATarget.localTarget();146 var app = target.frontMostApp();147 target.captureRectWithName(target.frontMostApp().rect(),imageName);148 }149 this.waitForLoad = function(preDelay) { 150 var target = UIATarget.localTarget();151 if (!preDelay) {152 target.delay(0);153 }154 else {155 target.delay(preDelay);156 }157 var done = false;158 var counter = 0; 159 while ((!done) && (counter < 60)) {160 var progressIndicator = UIATarget.localTarget().frontMostApp().windows()[0].activityIndicators()[0];161 var indicator = this._findIndicator(UIATarget.localTarget().frontMostApp());162 if (indicator == 1) {163 UIALogger.logMessage("来到这里等待一下")164 target.delay(0.5);165 counter++; 166 }167 else {168 done = true; 169 }170 }171 target.delay(0.5);172 }173}174mon = new iOSMonkey2();175UIATarget.localTarget().setTimeout(0);176for(var i = 0; i< 1000; i++){177 try{178 mon.operator();179 }catch(err){180 UIALogger.logMessage("这里有一个异常");181 UIALogger.logMessage(err.toString()+"");182 }183 mon.screenShoot("test");184 mon.waitForLoad(1);185 //UIATarget.localTarget().delay(2);...

Full Screen

Full Screen

widget.js

Source:widget.js Github

copy

Full Screen

1class TimberWidget {2 constructor(element) {3 this._element = document.getElementById('timber-element')4 this._body = document.body5 this._timberElement = document.getElementsByClassName('TimberWidget')[0]6 }7 get element() {8 return this._element9 }10 get documentBody() {11 return this._body12 }13 get timberElement() {14 return this._timberElement15 }16 returnOffset(element) {17 let _x = 018 let _y = 019 while (element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) {20 _x += element.offsetLeft - element.scrollLeft21 _y += element.offsetTop - element.scrollTop22 element = element.offsetParent23 }24 return {25 left: _x,26 top: _y27 }28 }29 appendStyles() {30 let styles = `31 .TimberWidget {32 position: absolute;33 top: 50px;34 left: 200px;35 z-index: 999;36 width: 100%;37 max-width: 320px;38 height: 400px;39 background-color: #fff;40 box-shadow: 0 0 1px rgba(0, 0, 0, 0.4), 0 10px 30px rgba(0, 0, 0, 0.1);41 border-radius: 5px;42 overflow: hidden;43 }44 .TimberWidget-frame {45 position: relative;46 border: 0;47 outline: 0;48 overflow: hidden;49 border-radius: 5px;50 width: 100%;51 height: 100%;52 }53 `54 document.write(`<style type="text/css">${styles}</style>`)55 }56 createElement() {57 let elementFlickPosition = this.returnOffset(this.element)58 let twContainer = document.createElement('div')59 twContainer.classList.add('TimberWidget')60 twContainer.style.left = elementFlickPosition.left + 'px'61 twContainer.style.top = (elementFlickPosition.top + 20) + 'px'62 twContainer.style.transform = "translateX(-50%)"63 let twFrame = document.createElement('iframe')64 twFrame.src = 'https://alexpate.uk'65 twFrame.classList.add('TimberWidget-frame')66 twContainer.appendChild(twFrame)67 this.documentBody.appendChild(twContainer)68 }69 init() {70 this.appendStyles()71 this.createElement()72 console.log(this.returnOffset(this.element))73 }74}75var timberWidget = new TimberWidget()...

Full Screen

Full Screen

flicking.test.js

Source:flicking.test.js Github

copy

Full Screen

1describe('flicking flow test', function() {2 var flick,3 flick1,4 data;5 jasmine.getFixtures().fixturesPath = "base/";6 jasmine.getStyleFixtures().fixturesPath = "base/";7 beforeEach(function() {8 loadFixtures("test/fixtures/flick.html");9 loadStyleFixtures('test/fixtures/flick.css');10 data = [11 '<span>flick 1</span>',12 '<span>flick 2</span>',13 '<span>flick 3</span>',14 '<span>flick 4</span>',15 '<span>flick 5</span>'16 ];17 flick = new ne.component.m.Flicking({18 element: document.getElementById('flick'),19 wrapper: document.getElementById('flick-wrap1'),20 isMagnetic: false,21 data: data,22 flow: 'horizontal'23 });24 flick1 = new ne.component.m.Flicking({25 element: document.getElementById('flick2'),26 wrapper: document.getElementById('flick-wrap2')27 });28 });29 it('flicking is defined', function() {30 expect(flick).toBeDefined();31 expect(flick1).toBeDefined();32 var child = flick.wrapper.childNodes;33 expect(child.length).toBe(5);34 });35 describe('set resize for orientation', function() {36 it('resize element', function() {37 flick.setWidth(150);38 var element = flick.element;39 expect(parseInt(element.style.width, 10)).toBe(150);40 });41 });42 describe('drag flow test', function() {43 // todo drag simulation with point44 });45 describe('test magnetic after drag.', function() {46 // todo when touchend/mouseup uprise, check using magnetic47 it('magnetic case', function() {48 });49 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('chrome')5 .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10var webdriver = require('selenium-webdriver'),11 until = webdriver.until;12var driver = new webdriver.Builder()13 .forBrowser('chrome')14 .build();15driver.findElement(By.name('q')).sendKeys('webdriver');16driver.findElement(By.name('btnG')).click();17driver.wait(until.titleIs('webdriver - Google Search'), 1000);18driver.quit();19var webdriver = require('selenium-webdriver'),20 until = webdriver.until;21var driver = new webdriver.Builder()22 .forBrowser('chrome')23 .build();24driver.findElement(By.name('q')).sendKeys('webdriver');25driver.findElement(By.name('btnG')).click();26driver.wait(until.titleIs('webdriver - Google Search'), 1000);27driver.quit();28var webdriver = require('selenium-webdriver'),29 until = webdriver.until;30var driver = new webdriver.Builder()31 .forBrowser('chrome')32 .build();33driver.findElement(By.name('q')).sendKeys('webdriver');34driver.findElement(By.name('btnG')).click();35driver.wait(until.titleIs('webdriver - Google Search'), 1000);36driver.quit();37var webdriver = require('selenium-webdriver'),38 until = webdriver.until;39var driver = new webdriver.Builder()40 .forBrowser('chrome')41 .build();

Full Screen

Using AI Code Generation

copy

Full Screen

1element.flick(100, 100, 100, 100);2element.flick(100, 100, 100, 100, 100);3element.flick(100, 100, 100, 100, 100, 100);4element.flick(100, 100, 100, 100, 100, 100, 100);5element.flick(100, 100, 100, 100, 100, 100, 100, 100);6element.flick(100, 100, 100, 100, 100, 100, 100, 100, 100);7element.flick(100, 100, 100, 100, 100, 100, 100, 100, 100, 100);8element.flick(100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100);

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Flicking', function() {2 it('should flick the element', function() {3 var el = element(by.id('myElement'));4 el.flick(0, -100);5 });6});7describe('Flicking', function() {8 it('should flick the element', function() {9 var el = element(by.id('myElement'));10 el.flick(0, -100);11 });12});13describe('Flicking', function() {14 it('should flick the element', function() {15 var el = element(by.id('myElement'));16 el.flick(0, -100);17 });18});19describe('Flicking', function() {20 it('should flick the element', function() {21 var el = element(by.id('myElement'));22 el.flick(0, -100);23 });24});25describe('Flicking', function() {26 it('should flick the element', function() {27 var el = element(by.id('myElement'));28 el.flick(0, -100);29 });30});31describe('Flicking', function() {32 it('should flick the element', function() {33 var el = element(by.id('myElement'));34 el.flick(0, -100);35 });36});37describe('Flicking', function() {38 it('should flick the element', function() {39 var el = element(by.id('myElement'));40 el.flick(0, -100);41 });42});43describe('Flicking', function() {44 it('should flick the element', function() {45 var el = element(by.id('myElement'));46 el.flick(0, -100);47 });48});49describe('F

Full Screen

Using AI Code Generation

copy

Full Screen

1public void swipeLeft() {2 int startX = (int) (driver.manage().window().getSize().width * 0.9);3 int endX = (int) (driver.manage().window().getSize().width * 0.1);4 int Y = driver.manage().window().getSize().height / 2;5 TouchAction action = new TouchAction(driver);6 action.press(startX, Y).waitAction(1000).moveTo(endX, Y).release().perform();7}8public void swipeRight() {9 int startX = (int) (driver.manage().window().getSize().width * 0.1);10 int endX = (int) (driver.manage().window().getSize().width * 0.9);11 int Y = driver.manage().window().getSize().height / 2;12 TouchAction action = new TouchAction(driver);13 action.press(startX, Y).waitAction(1000).moveTo(endX, Y).release().perform();14}15public void swipeLeftOnElement(MobileElement element) {16 int startX = (int) (element.getSize().getWidth() * 0.9);17 int endX = (int) (element.getSize().getWidth() * 0.1);18 int Y = element.getSize().getHeight() / 2;19 TouchAction action = new TouchAction(driver);20 action.press(startX, Y).waitAction(1000).moveTo(endX, Y).release().perform();21}22public void swipeRightOnElement(MobileElement element) {23 int startX = (int) (element.getSize().getWidth() * 0.1);24 int endX = (int) (element.getSize().getWidth() * 0.9);25 int Y = element.getSize().getHeight() / 2;26 TouchAction action = new TouchAction(driver);27 action.press(startX, Y

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful