def poco(request): """相当于setup""" logger.info('===conftest poco===') logger.debug(f'设置logger(airtest.*)的level为{SD.AIRTEST_LOG_LEVEL}') get_logger("airtest").setLevel(SD.AIRTEST_LOG_LEVEL) random_time = random.choice(range(1, 5)) * 1 + random.choice(range(10)) * 0.1 logger.debug(f'random_time={random_time}') sleep(random_time) dev = init_app() logger.debug('初始化poco') poco = UnityPoco(addr=("localhost", SD.POCO_PORT)) request.cls.poco = poco yield request.cls.poco logger.info('===teardown===') logger.debug('结束前截图') allure_snap() if SD.PLAT == 'android': logger.debug('整个测试session结束后,关闭app') stop_app(SD.PACKAGE_NAME) if SD.USE_ATX_SERVER2: atx_server2 = AtxServer2() ret = atx_server2.release_device(SD.UDID) elif SD.PLAT.find('pc') >= 0: pid = dev.stop_app.process logger.debug(f'PC平台是结束进程,进程id:{pid}') Windows().stop_app(pid)
class G(object): """Represent the globals variables""" BASEDIR = None LOGGER = AirtestLogger(None) LOGGING = get_logger("airtest.core.api") SCREEN = None DEVICE = None DEVICE_LIST = [] RECENT_CAPTURE = None RECENT_CAPTURE_PATH = None CUSTOM_DEVICES = {} @classmethod def add_device(cls, dev): """ Add device instance in G and set as current device. Examples: G.add_device(Android()) Args: dev: device to init Returns: None """ cls.DEVICE = dev cls.DEVICE_LIST.append(dev) @classmethod def register_custom_device(cls, device_cls): cls.CUSTOM_DEVICES[device_cls.__name__.lower()] = device_cls
def is_test_state(): logger.get_logger("airtest").info('开始检测是否处于测试状态') if exists( Template(r"tpl1568969049545.png", record_pos=(0.435, -0.83), resolution=(1080, 1920))): touch( Template(r"tpl1568969049545.png", record_pos=(0.435, -0.83), resolution=(1080, 1920))) if not exists( Template(r"tpl1569486525811.png", record_pos=(0.106, -0.011), resolution=(1080, 1920))): return False else: touch( Template(r"tpl1569487068913.png", record_pos=(0.392, -0.472), resolution=(1080, 1920))) return True else: return False return True
class G(object): """Represent the globals variables""" BASEDIR = [] LOGGER = AirtestLogger(None) LOGGING = get_logger("airtest.core.api") SCREEN = None DEVICE = None DEVICE_LIST = [] RECENT_CAPTURE = None RECENT_CAPTURE_PATH = None CUSTOM_DEVICES = {} @classmethod def add_device(cls, dev): """ Add device instance in G and set as current device. Examples: G.add_device(Android()) Args: dev: device to init Returns: None """ for index, instance in enumerate(cls.DEVICE_LIST): if dev.uuid == instance.uuid: cls.LOGGING.warn("Device:%s updated %s -> %s" % (dev.uuid, instance, dev)) cls.DEVICE_LIST[index] = dev cls.DEVICE = dev break else: cls.DEVICE = dev cls.DEVICE_LIST.append(dev) @classmethod def register_custom_device(cls, device_cls): cls.CUSTOM_DEVICES[device_cls.__name__.lower()] = device_cls
def __init__(cls, name, bases, attrs): if name != "BasePage": cls.cls_name = name cls.page_ele_loc = config.page_ele_loc with open(package_name_path, "r") as f: cls.package_name = f.read().strip() if cls.package_name: # print("Base读取package_name.txt") pass else: # print("Base读取config.yaml") cls.package_name = config.Config.get_yaml().get("package_name", None) logger = get_logger("airtest") logger.setLevel(logging.INFO) print(f"**********\n" f"当前子类: {cls.cls_name}\n" f"包名: {cls.package_name}\n" f"**********\n") super().__init__(name, bases, attrs) else: print("[Base] BasePage __init__") cls.cls_name = name super().__init__(name, bases, attrs)
# coding=utf-8 import subprocess import os import re import struct import logging from airtest.utils.logger import get_logger from airtest.utils.nbsp import NonBlockingStreamReader from airtest.utils.safesocket import SafeSocket from airtest.utils.compat import SUBPROCESS_FLAG LOGGING = get_logger(__name__) class MinicapIOS(object): """https://github.com/openstf/ios-minicap""" CAPTIMEOUT = None def __init__(self, udid=None, port=12345): super(MinicapIOS, self).__init__() self.udid = udid or list_devices()[0] print(repr(self.udid)) self.port = port self.resolution = "320x568" self.executable = os.path.join(os.path.dirname(__file__), "ios_minicap") self.server_proc = None def setup(self): cmd = [ self.executable, "--udid", self.udid, "--port",
class G(object): """Represent the globals variables""" BASEDIR = [] LOGGER = AirtestLogger(None) LOGGING = get_logger("airtest.core.api") SCREEN = None DEVICE = None DEVICE_LIST = [] RECENT_CAPTURE = None RECENT_CAPTURE_PATH = None CUSTOM_DEVICES = {} @classmethod def snapshot(self, filename=None): self._gen_screen_log(filename=filename) @classmethod def _gen_screen_log(self, element=None, filename=None): if ST.LOG_DIR is None: return None if filename: self.screenshot(filename) jpg_file_name = str(int(time.time())) + '.jpg' jpg_path = os.path.join(ST.LOG_DIR, jpg_file_name) print("this is jpg path:", jpg_path) self.screenshot(jpg_path) saved = {"screen": jpg_file_name} if element: size = element.size location = element.location x = size['width'] / 2 + location['x'] y = size['height'] / 2 + location['y'] if "darwin" in sys.platform: x, y = x * 2, y * 2 saved.update({"pos": [[x, y]]}) return saved @classmethod def screenshot(filename, hwnd=None): """ Take the pyqt_screenshot of Windows app Args: filename: file name where to store the pyqt_screenshot hwnd: Returns: bitmap pyqt_screenshot file """ # import ctypes # user32 = ctypes.windll.user32 # user32.SetProcessDPIAware() if hwnd is None: """all screens""" hwnd = win32gui.GetDesktopWindow() # get complete virtual screen including all monitors w = win32api.GetSystemMetrics(SM_CXVIRTUALSCREEN) h = win32api.GetSystemMetrics(SM_CYVIRTUALSCREEN) x = win32api.GetSystemMetrics(SM_XVIRTUALSCREEN) y = win32api.GetSystemMetrics(SM_YVIRTUALSCREEN) else: """window""" rect = win32gui.GetWindowRect(hwnd) w = abs(rect[2] - rect[0]) h = abs(rect[3] - rect[1]) x, y = 0, 0 hwndDC = win32gui.GetWindowDC(hwnd) mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) saveDC.SelectObject(saveBitMap) saveDC.BitBlt((0, 0), (w, h), mfcDC, (x, y), win32con.SRCCOPY) # saveBitMap.SaveBitmapFile(saveDC, filename) bmpinfo = saveBitMap.GetInfo() bmpstr = saveBitMap.GetBitmapBits(True) pil_image = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) cv2_image = pil_2_cv2(pil_image) mfcDC.DeleteDC() saveDC.DeleteDC() win32gui.ReleaseDC(hwnd, hwndDC) win32gui.DeleteObject(saveBitMap.GetHandle()) # cv2.imshow('toolIcon',cv2_image) # cv2.waitKey(0) return cv2_image @classmethod def add_device(cls, dev): """ Add device instance in G and set as current device. Examples: G.add_device(Android()) Args: dev: device to init Returns: None """ cls.DEVICE = dev cls.DEVICE_LIST.append(dev) @classmethod def register_custom_device(cls, device_cls): cls.CUSTOM_DEVICES[device_cls.__name__.lower()] = device_cls
import time from typing import Union import openpyxl from airtest.core.android.adb import ADB from poco.drivers.ios import iosPoco from poot.core.api import Poot import common.setting as ST from poco.pocofw import Poco from airtest.utils.logger import get_logger from airtest.core.api import (init_device, connect_device, set_current, auto_setup) from poco.drivers.android.uiautomation import AndroidUiautomationPoco from common.tools import tools import threading LOGGING = get_logger("airtest.||%s||" % __name__) endFlag = False class TestData(object): def __init__(self): ''' 测试数据专用类 ''' self.__data = {} # type:dict #测试数据 self.__groupList = set() # type:set #数据分组列表 self.__now_group = None # type:str #当前使用分组 @property def group(self): '''
# -*- encoding=utf8 -*- __author__ = "ivan.zhao" from airtest.core.api import * from airtest.cli.parser import cli_setup import logging from airtest.core.settings import Settings from airtest.utils.logger import get_logger logger = get_logger("airtest") logger.setLevel(logging.INFO) # airtest日志级别 # logging.basicConfig(level=logging.INFO, # 控制台打印的日志级别 logging.basicConfig(level=logging.INFO, # 控制台打印的日志级别 filename='./log/hfs_http_server.log', filemode='a', ##模式,有w和a,w就是写模式,每次都会重新写日志,覆盖之前的日志 # a是追加模式,默认如果不写的话,就是追加模式 format= '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s' # 日志格式 ) Settings.THRESHOLD = 0.9 Settings.THRESHOLD_STRICT = 0.9 Settings.FIND_TIMEOUT = 5 def reset_to_hfs_menu(): if not cli_setup(): auto_setup(__file__, devices=[ "Windows:///?title_re=HFS ~ HTTP*"])
# -*- encoding=utf8 -*- __author__ = "zheng.cong" from airtest.core.api import * import time import pytest import os, sys from airtest.core.api import * import logging import airtest.utils.logger as logger logger.get_logger("airtest").setLevel(logging.ERROR) class Get_config(object): def __init__(self): self.path = 'Z:\\publish\\android\\China\\6.9.1\\pilot_run' def get_apks_name(self): return ([ os.path.join(root, filename) for root, dirs, files, in os.walk(self.path) for filename in files if filename.endswith('apk') ]) def get_devices(): os.system('adb kill-server') os.system('adb start-server') connect_device("Android://127.0.0.1:5037/172.16.2.144:7777") print('设备已连接:', device())
else: from urlparse import urljoin from airtest import aircv from airtest.core.device import Device from airtest.core.ios.constant import CAP_METHOD, TOUCH_METHOD, IME_METHOD from airtest.core.ios.rotation import XYTransformer, RotationWatcher from airtest.core.ios.fake_minitouch import fakeMiniTouch from airtest.utils.logger import get_logger # roatations of ios from wda import LANDSCAPE, PORTRAIT, LANDSCAPE_RIGHT, PORTRAIT_UPSIDEDOWN from wda import WDAError logger = get_logger(__name__) DEFAULT_ADDR = "http://localhost:8100/" # retry when saved session failed def retry_session(func): def wrapper(self, *args, **kwargs): try: return func(self, *args, **kwargs) except WDAError as err: # 6 : Session does not exist if err.status == 6: self._fetchNewSession() return func(self, *args, **kwargs) else: raise err return wrapper
import os import logging from airtest.utils.logger import get_logger # for making logging easier LOG_LEVEL = logging.ERROR if os.environ.get('LOG_LEVEL') == "DEBUG": LOG_LEVEL = logging.DEBUG elif os.environ.get('LOG_LEVEL') == "INFO": LOG_LEVEL = LOG_LEVEL ## This class logger TODO:make this simpler LOGGER = get_logger(__name__) formatter = logging.Formatter( fmt='[Amazon_app_logger][%(asctime)s]<%(name)s> %(message)s', datefmt='%I:%M:%S') handler = logging.StreamHandler() handler.setFormatter(formatter) LOGGER.addHandler(handler) LOGGER.setLevel(logging.INFO) # Dynamically using desiredcapabilities Test_mobile_type = "Android" TestApkPath = os.path.abspath( os.path.join(os.path.dirname(__file__), "apps", "Amazon_shopping.apk")) TestappPackage = 'in.amazon.mShop.android.shopping' TestAppActivity = "com.amazon.mShop.home.HomeActivity"