自动化开发cmd封装:

android相关cmd封装:
import math
import os
import platform

from ...config.laputa_config import run_path, source_path

get_log = False
if os.getenv('get_log') is not None:
    get_log = True  # 执行文件为test_run.py时开启抓取手机日志功能
if os.getenv('no_install') is None:
    os.environ['no_install'] = 'true'


class Cmd:

    def get_cmd_return(self, cmd):
        return os.popen(cmd).readlines()

    # 获取设备id
    def get_devices(self):
        comd = 'adb devices'
        content = self.get_cmd_return(comd)
        device_list = list()
        ignore_list = [  # 设备udid黑名单,黑名单设备会用于冒烟测试和aquaman性能测试
            'RTJ0217727000776',  # 华为MT20
            'UYT5T18504003754',  # MT9
            'Y2J7N17926004140',  # P10
            'dbb9d5be',  # 小米mix2
        ]
        if 'test_run' in run_path:
            from ..init_project import module_list
        else:
            module_list = None
        for one in content:
            if '988bdc464f52475252' in one:  # 跳过三星
                continue
            if 'device' in one and 'List' not in one:
                udid = one.split('\t')[0]
                if module_list == ['Build_check']:
                    if udid in ignore_list and (os.getenv('no_install') == 'true' or os.getenv('%s_install' % udid) == 'success'):
                        device_list.append(udid)
                elif os.getenv('no_install') == 'true' or os.getenv('%s_install' % udid) == 'success':
                    device_list.append(udid)
        if os.getenv('print_cmd') is None:
            print('可用设备列表:', sorted(device_list))
            os.environ['print_cmd'] = '1'
            if len(device_list) is 0:
                raise Exception('无可用设备,请在控制台输入命令「%s」确认连接设备信息' % comd)
        return device_list

    def get_screen_size(self, udid, type=1):
        """
        获取屏幕分辩率,若adb只返回一种尺寸,则只返回该尺寸,与type无关
        :param udid:设备号
        :param type: 1获取屏幕大小,2获取物理尺寸
        :return:
        """
        size_dict = {}
        sizes = self.get_cmd_return('adb -s %s shell wm size' % udid)
        size = ''
        for s in sizes:
            if 'Physical' in s:
                size = s.split(':')[-1].strip()
                if type == 2:
                    break
            if 'Override' in s:
                size = s.split(':')[-1].strip()
                if type == 1:
                    break
        x, y = size.split('x')
        size_dict['x'] = int(x)
        size_dict['y'] = int(y)
        return size_dict

    # 获取屏幕密度
    def get_screen_density(self, udid):
        density = self.get_cmd_return('adb -s %s shell wm density' % udid)
        density = int(density[0].split(':')[-1].strip())
        return density

    # 获取物理尺寸
    def get_physical_dimension(self, udid):
        size = self.get_screen_size(udid, type=2)
        x, y = size['x'], size['y']
        density = self.get_screen_density(udid)
        dimension = math.sqrt(x * x + y * y) / density
        return round(dimension, 1)

    # 获取系统版本
    def get_system_version(self, udid):
        version = os.popen('adb -s %s shell getprop ro.build.version.release' % udid).readlines()
        version = version[0].split('\n')[0]
        return version

    # 获取手机型号
    def get_phone_name(self, udid):
        name = os.popen('adb -s %s shell getprop ro.product.model' % udid).readlines()
        name = name[0].split('\n')[0].replace(' ', '_')
        return name

    # 获取手机品牌
    def get_phone_product(self, udid):
        name = os.popen('adb -s %s shell getprop ro.product.brand' % udid).readlines()
        name = name[0].split('\n')[0]
        return name

    def kill_port(self, port):
        from time import sleep
        t = 0
        while True:
            if os.name == 'nt':
                pid_line = os.popen('netstat -ano|findstr 127.0.0.1:%s' % port).readlines()
                if len(pid_line) > 0 and t < 3:
                    t += 1
                    for i in pid_line:
                        if 'LISTEN' in i:
                            i = i.strip('\n').strip(' ')
                            line = i.split(' ')[-1]
                            os.system('tskill %s' % line)
                else:
                    return
                os.system('taskkill /f /im cmd.exe /fi "windowtitle eq appium"')  # win10 appium结束后遗留窗口
                os.system('taskkill /f /im cmd.exe /fi "windowtitle eq 管理员: appium"')  # win7 appium结束后遗留窗口
            else:
                while True:

                    pid_line = os.popen("lsof -i:%s|grep node | awk '{print $2}'" % port).readline().strip('\n')
                    if len(pid_line) > 0 and t < 3:
                        t += 1
                        os.system('kill -9 %s' % pid_line)
                        sleep(1)
                    else:
                        return

    def create_log_path(self, path):
        # def create_log_path(self, path, udid):
        """
        创建log存储目录,并将目录写入手机中以供调用
        """
        dir_path = os.path.abspath(path + '/log/')
        os.makedirs(dir_path, exist_ok=True)
        os.environ['log_path'] = dir_path

        # dir_path = os.path.abspath(path + '/log').replace('\\', '/')
        # os.makedirs(dir_path)
        # os.system('adb -s %s shell "echo %s > /sdcard/report_path"' % (udid, dir_path.replace('/', '*')))

    def start_logcat(self, udid):
        """
        logcat日志临时存放在手机中,测试完成后取出
        """
        if get_log:
            os.popen('adb -s %s shell "killall -9 logcat"' % udid)
            os.system('adb -s %s shell "logcat -c"' % udid)
            os.popen('adb -s %s shell "logcat > /sdcard/logcat.log"' % udid)

    def end_logcat(self, udid, case_id, case_result):
        """
        报告路径从提前写入到手机中,用例结束后将logcat压缩取出更名存入到报告目录下
        :param udid: 通过设备id指定设备执行
        :param case_id: 脚本名
        :return: 返回服务器log文件链接
        """
        if get_log:
            # log_path = os.popen('adb -s %s shell "cat /sdcard/report_path"' % udid) \
            #     .readline().strip('\n').replace('*', '/')
            log_path = os.getenv('log_path')
            os.popen('adb -s %s shell "killall -9 logcat"' % udid)
            if case_result != 'Pass':
                os.system('adb -s %s shell "rm -rf /sdcard/logcat.log.gz"' % udid)
                os.system('adb -s %s shell "gzip /sdcard/logcat.log"' % udid)
                if '\\' in case_id:
                    case_id.replace('\\', '-')
                try:
                    os.system('adb -s %s pull /sdcard/logcat.log.gz %s/%s.log.gz' % (udid, log_path, case_id))
                except:
                    pass

    # 获取手机适用chromedriver版本
    def get_driver_path(self, udid):
        webview_list = os.popen('adb -s %s shell "dumpsys package com.google.android.webview | grep versionName"' % udid).readlines()
        webview_versions = [x.split('=')[1].split('.')[0] for x in webview_list]
        webview_version = max(webview_versions)
        driver_version = '57' if int(webview_version) in range(0, 66) else '79'
        system_type = platform.system()
        version_plus = '.exe' if system_type == 'Windows' else ''
        driver_path = os.path.join(source_path, 'config/chromedriver/{0}/chromedriver_{1}{2}'.format(system_type, driver_version, version_plus))
        return driver_path
ios相关cmd封装: 
# -*- coding: utf-8 -*-
import os

from ...config.laputa_config import source_path, run_path

temp_path = source_path + 'test_report/ios'
get_log = True if os.getenv('get_log') else False  # 执行文件为test_run.py时开启抓取手机日志功能
if os.getenv('no_install') is None:
    os.environ['no_install'] = 'true'


class Cmd:

    def get_cmd_return(self, cmd):
        return os.popen(cmd).readlines()

    # 获取设备id
    def get_devices(self, cmd='idevice_id -l'):
        content = self.get_cmd_return(cmd=cmd)
        device_list = list()
        ignore_list = [
            '8056ca675ee0f32cf0bdae6bcbaeda80eb41e688',  # 7
            '00008020-001045490238002E',  # xs
            '08feda8b7b9e76e22a244d8f90de2f9d01e178de'  # 7
        ]
        if 'test_run' in run_path:
            from ..init_project import module_list
        else:
            module_list = None
        for d in content:
            udid = d.split('\n')[0]
            if module_list == ['Build_check']:
                if udid in ignore_list and (os.getenv('no_install') == 'true' or os.getenv('%s_install' % udid) == 'success'):
                    device_list.append(udid)
            elif os.getenv('no_install') == 'true' or os.getenv('%s_install' % udid) == 'success':
                device_list.append(udid)
        if os.getenv('print_cmd') is None:
            print('可用设备列表:', sorted(device_list))
            os.environ['print_cmd'] = '1'
            if len(device_list) is 0:
                raise Exception('无可用设备,请在控制台输入命令「%s」确认连接设备信息' % cmd)
        return sorted(device_list)

    # 获取系统版本
    def get_system_version(self, udid):
        os_system_version = os.popen('ideviceinfo -u %s -k ProductVersion' % udid).readlines()  # 适配ios
        os_system_version = os_system_version[0].split('\n')[0]  # 适配ios
        return os_system_version

    # 获取手机型号
    def get_phone_hw_info(self, udid):
        product_type = os.popen('ideviceinfo -u %s -k ProductType' % udid).readlines()  # 适配ios
        product_type = product_type[0].split('\n')[0]
        return product_type
        # for key in iphone_info:
        #     phone_info_value = iphone_info[key]
        #     phone_type_list = phone_info_value['type']
        #     if product_type in phone_type_list:
        #         return phone_info_value

    # 获取手机名字
    def get_device_name(self, udid):
        device_name = os.popen('ideviceinfo -u %s -k DeviceName' % udid).readlines()  # 适配ios
        device_name = device_name[0].split('\n')[0]
        if os.getenv('print_%s_name' % udid) is None:
            print(udid, 'name', device_name)
            os.environ['print_%s_name' % udid] = '1'
        return device_name

    # 获取手机品牌
    def get_phone_brand(self, udid):
        phone_brand = os.popen('ideviceinfo -u %s -k ProductName' % udid).readlines()
        phone_brand = phone_brand[0].split(' ')[0]
        return phone_brand

    def kill_port(self, port):
        from time import sleep
        t = 0
        while True:
            if os.name == 'nt':
                pid_line = os.popen('netstat -ano|findstr 127.0.0.1:%s' % port).readlines()
                if len(pid_line) > 0 and t < 3:
                    t += 1
                    for i in pid_line:
                        if 'LISTEN' in i:
                            i = i.strip('\n').strip(' ')
                            line = i.split(' ')[-1]
                            os.system('tskill %s' % line)
                else:
                    return
                os.system('taskkill /f /im cmd.exe /fi "windowtitle eq appium"')  # win10 appium结束后遗留窗口
                os.system('taskkill /f /im cmd.exe /fi "windowtitle eq 管理员: appium"')  # win7 appium结束后遗留窗口
            else:
                while True:

                    pid_line = os.popen("lsof -i:%s|grep node | awk '{print $2}'" % port).readline().strip('\n')
                    if len(pid_line) > 0 and t < 3:
                        t += 1
                        os.system('kill -9 %s' % pid_line)
                        sleep(1)
                    else:
                        return


    def create_log_path(self, path):
        """
        创建log存储目录,并将目录保存到环境变量中
        """
        dir_path = os.path.abspath(path + '/log/')
        os.makedirs(dir_path, exist_ok=True)
        os.environ['log_path'] = dir_path

    def start_syslog(self, udid):
        """
        logcat日志临时存放在手机中,测试完成后取出
        """
        if get_log:
            dir_path = os.getenv('log_path')
            print(dir_path)
            syslog_path = dir_path + '/%s.log' % udid
            start_syslog_cmd = 'nohup idevicesyslog -u %s  > %s &' % (udid, syslog_path)
            os.system(start_syslog_cmd)
            return syslog_path

    def end_syslog(self, udid, case_id=None, result=None):
        """
        报告路径从提前写入到手机中,用例结束后将logcat压缩取出更名存入到报告目录下
        :param udid: 通过设备id指定设备执行
        :param case_id: 脚本名
        :return: 返回服务器log文件链接
        """
        if get_log:
            check_pid_command = "ps -le| grep 'idevicesyslog -u %s'|sed -n '1p'|awk '{print $2}'" % udid
            pid_list = os.popen(check_pid_command).readline()
            os.system('kill -9 %s' % pid_list)
            if case_id is None:
                return
            dir_path = os.getenv('log_path') + '/%s.log' % udid
            gzip_command = 'gzip %s' % dir_path
            os.system(gzip_command)
            if os.path.exists(dir_path):
                os.remove(dir_path)
            dir_path_new = os.getenv('log_path')
            os.system('mv {0}/{1}.log.gz {0}/{2}.log.gz'.format(dir_path_new, udid, case_id))
            if result == 'Pass':
                os.remove('%s.log.gz' % (dir_path_new + '/' + case_id))

    def end_all_log(self):
        pid_lines = os.popen('ps -le| grep \'idevicesyslog -u\'').readlines()
        for i in pid_lines:
            if 'grep idevicesyslog' not in i:
                i = i.replace('  ', ' ')
                pid = i.split(' ')[1]
                os.system('kill -9 %s' % pid)

    def clear_cache(self):
        import getpass
        from laputa_auto.util.init_project import module_list
        if module_list == ['Build_check']:
            return
        wda_cache_path = '/Users/%s/Library/Developer/Xcode/DerivedData/WebDriverAgent*' % getpass.getuser()
        os.system('rm -rf %s' % wda_cache_path)
        content = self.get_cmd_return(cmd='idevice_id -l')
        for d in content:
            udid = d.split('\n')[0]
            wda = os.popen('ios-deploy --id %s --list_bundle_id | grep WebDriverAgent' % udid).readline().strip()
            if 'WebDriverAgent' in wda:
                os.system('ios-deploy -i %s -9 -1 %s' % (udid, wda))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值