How to use touch_method method in Airtest

Best Python code snippet using Airtest

touch_proxy.py

Source:touch_proxy.py Github

copy

Full Screen

1# encoding=utf-82import warnings3from collections import OrderedDict4from airtest.core.android.constant import TOUCH_METHOD5from airtest.core.android.touch_methods.maxtouch import Maxtouch6from airtest.core.android.touch_methods.minitouch import Minitouch7from airtest.utils.logger import get_logger8LOGGING = get_logger(__name__)9class TouchProxy(object):10 """11 Perform touch operation according to the specified method12 """13 TOUCH_METHODS = OrderedDict()14 def __init__(self, touch_method):15 self.touch_method = touch_method16 def __getattr__(self, name):17 if name == "method_name":18 return self.touch_method.METHOD_NAME19 method = getattr(self.touch_method, name, getattr(self.touch_method.base_touch, name, None))20 if method:21 return method22 else:23 raise NotImplementedError("%s does not support %s method" %24 (getattr(self.touch_method, "METHOD_NAME", ""), name))25 @classmethod26 def check_touch(cls, touch_impl):27 try:28 touch_impl.base_touch.install_and_setup()29 except Exception as e:30 LOGGING.error(e)31 LOGGING.warning("%s setup up failed!" % touch_impl.METHOD_NAME)32 return False33 else:34 return True35 @classmethod36 def auto_setup(cls, adb, default_method=None, ori_transformer=None, size_info=None, input_event=None):37 """38 Args:39 adb: :py:mod:`airtest.core.android.adb.ADB`40 default_method: The default click method, such as "MINITOUCH"41 ori_transformer: dev._touch_point_by_orientation42 size_info: the result of dev.get_display_info()43 input_event: dev.input_event44 *args:45 **kwargs:46 Returns: TouchProxy object47 Examples:48 >>> dev = Android()49 >>> touch_proxy = TouchProxy.auto_setup(dev.adb, ori_transformer=dev._touch_point_by_orientation)50 >>> touch_proxy.touch((100, 100))51 """52 if default_method and default_method in cls.TOUCH_METHODS:53 touch_method = cls.TOUCH_METHODS[default_method].METHOD_CLASS(adb, size_info=size_info,54 input_event=input_event)55 impl = cls.TOUCH_METHODS[default_method](touch_method, ori_transformer)56 if cls.check_touch(impl):57 return TouchProxy(impl)58 # cls.TOUCH_METHODS中不包含ADBTOUCH,因此即使指定了default_method=ADBTOUCH,也优先尝试初始化其他点击方法59 for name, touch_impl in cls.TOUCH_METHODS.items():60 if default_method == name:61 continue62 touch_method = touch_impl.METHOD_CLASS(adb, size_info=size_info, input_event=input_event)63 impl = touch_impl(touch_method, ori_transformer)64 if cls.check_touch(impl):65 return TouchProxy(impl)66 # If both minitouch and maxtouch fail to initialize, use adbtouch67 # 如果minitouch和maxtouch都初始化失败,使用adbtouch68 adb_touch = AdbTouchImplementation(adb)69 warnings.warn("Currently using ADB touch, the efficiency may be very low.")70 return TouchProxy(adb_touch)71def register_touch(cls):72 TouchProxy.TOUCH_METHODS[cls.METHOD_NAME] = cls73 return cls74class AdbTouchImplementation(object):75 METHOD_NAME = TOUCH_METHOD.ADBTOUCH76 def __init__(self, base_touch):77 """78 :param base_touch: :py:mod:`airtest.core.android.adb.ADB`79 """80 self.base_touch = base_touch81 def touch(self, pos, duration=0.01):82 if duration <= 0.01:83 self.base_touch.touch(pos)84 else:85 self.swipe(pos, pos, duration=duration)86 def swipe(self, p1, p2, duration=0.5, *args, **kwargs):87 duration *= 100088 self.base_touch.swipe(p1, p2, duration=duration)89@register_touch90class MinitouchImplementation(AdbTouchImplementation):91 METHOD_NAME = TOUCH_METHOD.MINITOUCH92 METHOD_CLASS = Minitouch93 def __init__(self, minitouch, ori_transformer):94 """95 :param minitouch: :py:mod:`airtest.core.android.touch_methods.minitouch.Minitouch`96 :param ori_transformer: Android._touch_point_by_orientation()97 """98 super(MinitouchImplementation, self).__init__(minitouch)99 self.ori_transformer = ori_transformer100 def touch(self, pos, duration=0.01):101 pos = self.ori_transformer(pos)102 self.base_touch.touch(pos, duration=duration)103 def swipe(self, p1, p2, duration=0.5, steps=5, fingers=1):104 p1 = self.ori_transformer(p1)105 p2 = self.ori_transformer(p2)106 if fingers == 1:107 self.base_touch.swipe(p1, p2, duration=duration, steps=steps)108 elif fingers == 2:109 self.base_touch.two_finger_swipe(p1, p2, duration=duration, steps=steps)110 else:111 raise Exception("param fingers should be 1 or 2")112 def pinch(self, center=None, percent=0.5, duration=0.5, steps=5, in_or_out='in'):113 if center:114 center = self.ori_transformer(center)115 self.base_touch.pinch(center=center, percent=percent, duration=duration, steps=steps, in_or_out=in_or_out)116 def swipe_along(self, coordinates_list, duration=0.8, steps=5):117 pos_list = [self.ori_transformer(xy) for xy in coordinates_list]118 self.base_touch.swipe_along(pos_list, duration=duration, steps=steps)119 def two_finger_swipe(self, tuple_from_xy, tuple_to_xy, duration=0.8, steps=5, offset=(0, 50)):120 tuple_from_xy = self.ori_transformer(tuple_from_xy)121 tuple_to_xy = self.ori_transformer(tuple_to_xy)122 self.base_touch.two_finger_swipe(tuple_from_xy, tuple_to_xy, duration=duration, steps=steps, offset=offset)123 def perform(self, motion_events, interval=0.01):124 self.base_touch.perform(motion_events, interval)125@register_touch126class MaxtouchImplementation(MinitouchImplementation):127 METHOD_NAME = TOUCH_METHOD.MAXTOUCH128 METHOD_CLASS = Maxtouch129 def __init__(self, maxtouch, ori_transformer):130 """131 New screen click scheme, support Android10132 新的屏幕点击方案,支持Android10以上版本133 :param maxtouch: :py:mod:`airtest.core.android.touch_methods.maxtouch.Maxtouch`134 :param ori_transformer: Android._touch_point_by_orientation()135 """136 super(MaxtouchImplementation, self).__init__(maxtouch, ori_transformer)137 def perform(self, motion_events, interval=0.01):...

Full Screen

Full Screen

test_android.py

Source:test_android.py Github

copy

Full Screen

1# encoding=utf-82import os3import time4import numpy5import unittest6from airtest.core.android.android import Android, ADB, Minicap, Minitouch, IME_METHOD, CAP_METHOD, TOUCH_METHOD7from airtest.core.error import AirtestError8from testconf import APK, PKG, try_remove9class TestAndroid(unittest.TestCase):10 @classmethod11 def setUpClass(self):12 self.android = Android()13 @classmethod14 def tearDownClass(self):15 try_remove('screen.mp4')16 def _install_test_app(self):17 if PKG not in self.android.list_app():18 self.android.install_app(APK)19 def test_serialno(self):20 self.assertIsNotNone(self.android.serialno)21 def test_adb(self):22 self.assertIsInstance(self.android.adb, ADB)23 def test_display_info(self):24 self.assertIs(self.android.display_info, self.android.adb.display_info)25 self.assertIn("width", self.android.display_info)26 self.assertIn("height", self.android.display_info)27 self.assertIn("orientation", self.android.display_info)28 self.assertIn("rotation", self.android.display_info)29 def test_minicap(self):30 minicap = self.android.minicap31 self.assertIsInstance(minicap, Minicap)32 self.assertIs(minicap.adb.display_info, self.android.display_info)33 def test_minitouch(self):34 self.assertIsInstance(self.android.minitouch, Minitouch)35 def test_list_app(self):36 self._install_test_app()37 self.assertIn(PKG, self.android.list_app())38 self.assertIn(PKG, self.android.list_app(third_only=True))39 def test_path_app(self):40 self._install_test_app()41 app_path = self.android.path_app(PKG)42 self.assertIn(PKG, app_path)43 self.assertTrue(app_path.startswith("/"))44 with self.assertRaises(AirtestError):45 self.android.path_app('com.netease.this.is.error')46 def test_check_app(self):47 self._install_test_app()48 self.assertTrue(self.android.check_app(PKG))49 with self.assertRaises(AirtestError):50 self.android.check_app('com.netease.this.is.error')51 def test_snapshot(self):52 self._install_test_app()53 for i in (CAP_METHOD.ADBCAP, CAP_METHOD.MINICAP, CAP_METHOD.MINICAP_STREAM, CAP_METHOD.JAVACAP):54 filename = "./screen.png"55 if os.path.exists(filename):56 os.remove(filename)57 self.android.cap_method = i58 self.android.wake()59 screen = self.android.snapshot(filename=filename)60 self.assertIsInstance(screen, numpy.ndarray)61 self.assertTrue(os.path.exists(filename))62 os.remove(filename)63 def test_shell(self):64 self.assertEqual(self.android.shell('echo nimei').strip(), 'nimei')65 def test_keyevent(self):66 self.android.keyevent("BACK")67 def test_wake(self):68 self.android.wake()69 def test_screenon(self):70 self.assertIn(self.android.is_screenon(), (True, False))71 def test_home(self):72 self.android.home()73 def test_text(self):74 self.android.ime_method = IME_METHOD.ADBIME75 self.android.text('test text')76 self.android.ime_method = IME_METHOD.YOSEMITEIME77 self.android.text(u'你好')78 def test_touch(self):79 for i in (TOUCH_METHOD.ADBTOUCH, TOUCH_METHOD.MINITOUCH):80 self.android.touch_method = i81 self.android.touch((100, 100))82 def test_swipe(self):83 for i in (TOUCH_METHOD.ADBTOUCH, TOUCH_METHOD.MINITOUCH):84 self.android.touch_method = i85 self.android.swipe((100, 100), (300, 300))86 self.android.swipe((100, 100), (300, 300), fingers=1)87 self.android.swipe((100, 100), (300, 300), fingers=2) 88 self.android.touch_method = TOUCH_METHOD.ADBTOUCH89 self.android.swipe((100, 100), (300, 300), fingers=3)90 self.android.touch_method = TOUCH_METHOD.MINITOUCH91 with self.assertRaises(Exception):92 self.android.swipe((100, 100), (300, 300), fingers=3)93 def test_recording(self):94 if self.android.sdk_version >= 19:95 filepath = "screen.mp4"96 if os.path.exists(filepath):97 os.remove(filepath)98 self.android.start_recording(max_time=30, bit_rate=500000, vertical=False)99 time.sleep(3)100 self.android.stop_recording()101 self.assertTrue(os.path.exists("screen.mp4"))102 def test_start_recording_error(self):103 if self.android.sdk_version >= 19:104 with self.assertRaises(AirtestError):105 self.android.start_recording(max_time=30)106 time.sleep(3)107 self.android.start_recording(max_time=30)108 self.android.stop_recording()109 def test_stop_recording_error(self):110 with self.assertRaises(AirtestError):111 self.android.stop_recording()112 def test_interrupt_recording(self):113 filepath = "screen.mp4"114 if os.path.exists(filepath):115 os.remove(filepath)116 self.android.start_recording(max_time=30)117 time.sleep(3)118 self.android.stop_recording(is_interrupted=True)119 self.assertFalse(os.path.exists(filepath))120 def test_get_top_activity(self):121 self._install_test_app()122 self.android.start_app(PKG)123 pkg, activity, pid = self.android.get_top_activity()124 self.assertEqual(pkg, PKG)125 self.assertEqual(activity, 'org.cocos2dx.javascript.AppActivity')126 self.assertIsInstance(int(pid), int)127 def test_is_keyboard_shown(self):128 self.android.is_keyboard_shown()129 def test_is_locked(self):130 self.android.is_locked()131 def test_unlock(self):132 self.android.unlock()133 def test_pinch(self):134 self.android.pinch(in_or_out='in')135 self.android.pinch(in_or_out='out')136if __name__ == '__main__':...

Full Screen

Full Screen

run.py

Source:run.py Github

copy

Full Screen

...88 except RuntimeError:89 # Even if minicap execution fails, use adb instead90 return self.adb.get_display_info()91 return self.adb.get_display_info()92 def _get_touch_method(self):93 if self.touch_method == TOUCH_METHOD.MAXTOUCH:94 return self.maxtouch95 elif self.touch_method == TOUCH_METHOD.MINITOUCH:96 return self.minitouch97 elif self.touch_method == TOUCH_METHOD.ADBTOUCH:98 return self.EVENTTOUCH99 def _get_cap_func(self):100 if self.cap_method == CAP_METHOD.MINICAP:101 return self.minicap102 elif self.cap_method == CAP_METHOD.JAVACAP:103 return self.javacap104 elif self.cap_method == CAP_METHOD.ADBCAP:105 return self.adb.screenshot106 def _register_rotation_watcher(self):107 self.rotation_watcher.reg_callback(lambda x: self._get_touch_method().update_rotation(x * 90))108 if self.cap_method == CAP_METHOD.MINICAP:...

Full Screen

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 Airtest 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