通用技术 python-monkey 压测 app 生成曲线图的三层架构

测试小书童 · 2016年09月03日 · 最后由 测试小书童 回复于 2017年06月08日 · 1738 次阅读

基于 (python-monkey 压测监控 app)[https://testerhome.com/topics/5662]
最开始是看到了蛇的文章来学习的 https://testerhome.com/topics/2514 找了好久才找到。。。

  • 最近开始关注代码的分离质量了,就开始学习了三层架构,重构之前的 monkey 测试代码

  • MODEL 实体类
  • DAL 数据处理,用的最多的就是数据库方法
  • BLL 业务逻辑 这里个人一直不是很理解
  • COMMON 放一些公用的方法在里面

代码分析

model 层

用的 schematics,不用自己写 get,set 了


from schematics.models import Model
from schematics.types import StringType,IntType
class monkeyconfig(Model):
    cmd = StringType()
    package_name = StringType()
    logdir = StringType() #本机的log存放地址
    remote_path = StringType()  #远程服务器地址,可以给开发查看
    phone_msg_log = StringType() #临时存放手机日志信息路径
    now = StringType()
    exceptions = StringType() #异常列表监控
    sum = StringType() #事件数量
    activity = StringType()
    monkey_log = StringType()

  • 如果我的实体类想放 list 怎么弄?
    • ListType(IntType) 这样就可以了,是不是很酷
    • 设置值就这样设置 [[111],[3333]]

DAL 层

import configparser
import time
def monkeyConfig(mmonkeyconfig, init_file):
    config = configparser.ConfigParser()
    config.read(init_file)
    mmonkeyconfig.package_name = config['DEFAULT']['package_name']
    mmonkeyconfig.logdir = config['DEFAULT']['logdir']
    mmonkeyconfig.remote_path = config['DEFAULT']['remote_path']
    mmonkeyconfig.phone_msg_log = config['DEFAULT']['phone_msg_log']
    mmonkeyconfig.now = time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time()))
    mmonkeyconfig.activity = config['DEFAULT']['activity']
    mmonkeyconfig.sum = int(config['DEFAULT']['sum'])
    mmonkeyconfig.monkey_log = mmonkeyconfig.logdir + "\\" + mmonkeyconfig.now + r"monkey.log"
    mmonkeyconfig.cmd = config['DEFAULT']['cmd'] + " " + str(mmonkeyconfig.sum) + ">>" + mmonkeyconfig.monkey_log
    return mmonkeyconfig

BLL 层

from DAL import DMonkeyConfig
def monkeyConfig(mmonkeyconfig, init_file):
    return DMonkeyConfig.monkeyConfig(mmonkeyconfig, init_file)

UI 层


# 只调用BLL层的东西
from BLL import BMatPlo
from BLL import BAdbCommon
from Common import OperateFile
from BLL import BMonkeyConfig
from Model import MMonkeyConfig
from Model import MMatplo
from BLL import BMenCpu

 ba = BAdbCommon
mconfig = MMonkeyConfig.monkeyconfig()
mc = BMonkeyConfig.monkeyConfig(mconfig, ini_file)

# 下面就可以取实体类的值
mc.cmd, mc.logdir, mc.now, mc.monkey_log

入口代码

import os
import time
import datetime as dt
from BLL import BMatPlo
from BLL import BAdbCommon
from Common import OperateFile
from BLL import BMonkeyConfig
from Model import MMonkeyConfig
from Model import MMatplo
from BLL import BMenCpu

#开始脚本测试
def start_monkey(cmd, logdir, now1, monkey_log):
    print(cmd)
    os.popen(cmd)
    cmd2 = "adb logcat -d >%s" % monkey_log
    os.popen(cmd2)
    # logcatname=logdir+"\\"+now1+r"logcat.log"
    # cmd2="adb logcat -d >%s" %(logcatname)
    # os.popen(cmd2) 用于error的分析
    #print"导出traces文件"
    tracesname = logdir + "\\" + now1 + r"traces.log"
    cmd3 = "adb shell cat /data/anr/traces.txt>%s" % tracesname
    os.popen(cmd3)
if __name__ == '__main__':
    ini_file = 'monkey.ini'
    ba = BAdbCommon
    if OperateFile.base_file(ini_file, "r").check_file():
        if ba.attached_devices():
            mconfig = MMonkeyConfig.monkeyconfig()
            mc = BMonkeyConfig.monkeyConfig(mconfig, ini_file)
            # 打开想要的activity
            ba.open_app(mc.package_name, mc.activity)
            temp = ""
             # monkey开始测试
            start_monkey(mc.cmd, mc.logdir, mc.now, mc.monkey_log)

            # cpu,men统计
            ml = MMatplo.matplo()
            bm = BMenCpu.get_men_cpu(mc.package_name)
            ml.cpu = [[], []]
            ml.men = [[], []]
            ml.title = ["cpu测试", "内存测试"]
            ml.locator = 2
            for i in range(mc.sum):
                time.sleep(1)
                dn = dt.datetime.now()
                ml.cpu[0].append(dn)
                cpu = bm.top_cpu()
                ml.men[0].append(dn)
                men = bm.get_men()
                with open(mc.monkey_log, encoding='utf-8') as monkeylog:
                    temp = monkeylog.read()
                if temp.count('Monkey finished') > 0:
                    print("测试完成咯")
                    ml.cpu[1].append(cpu)
                    ml.men[1].append(men)
                    BMatPlo.cpu_men_plots(ml)
                    break
        else:
            print("设备不存在")
    else:
        print(u"配置文件不存在"+ini_file)
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 4 条回复 时间 点赞

good!很不错!学习了!

😅 大学的三层架构的

测试小书童 [该话题已被删除] 中提及了此贴 09月12日 18:57
测试小书童 关闭了讨论 09月12日 19:14
测试小书童 monkey 稳定性测试 中提及了此贴 11月28日 16:05
匿名 #3 · 2017年06月08日

楼主,BAdbCommon 这个类的代码能发下吗

class AndroidDebugBridge(object):
    def call_adb(self, command):
        command_result = ''
        command_text = 'adb %s' % command
        results = os.popen(command_text, "r")
        while 1:
            line = results.readline()
            if not line: break
            command_result += line
        results.close()
        return command_result

    # check for any fastboot device
    def fastboot(self, device_id):
        pass

    # 检查设备
    def attached_devices(self):
        result = self.call_adb("devices")
        devices = result.partition('\n')[2].replace('\n', '').split('\tdevice')
        flag = [device for device in devices if len(device) > 2]
        if flag:
            return True
        else:
            return False
            # return [device for device in devices if len(device) > 2]
    # 状态
    def get_state(self):
        result = self.call_adb("get-state")
        result = result.strip(' \t\n\r')
        return result or None
    #重启
    def reboot(self, option):
        command = "reboot"
        if len(option) > 7 and option in ("bootloader", "recovery",):
            command = "%s %s" % (command, option.strip())
        self.call_adb(command)

    # 将电脑文件拷贝到手机里面
    def push(self, local, remote):
        result = self.call_adb("push %s %s" % (local, remote))
        return result

    # 拉数据到本地
    def pull(self, remote, local):
        result = self.call_adb("pull %s %s" % (remote, local))
        return result
    # 同步更新 很少用此命名
    def sync(self, directory, **kwargs):
        command = "sync %s" % directory
        if 'list' in kwargs:
            command += " -l"
            result = self.call_adb(command)
            return result

    # 打开指定app
    def open_app(self,packagename,activity):
        result = self.call_adb("shell am start -n %s/%s" % (packagename, activity))
        check = result.partition('\n')[2].replace('\n', '').split('\t ')
        if check[0].find("Error") >= 1:
            return False
        else:
            return True

    # 根据包名得到进程id
    def get_app_pid(self, pkg_name):
        string = self.call_adb("shell ps | grep "+pkg_name)
        # print(string)
        if string == '':
            return "the process doesn't exist."
        result = string.split(" ")
        # print(result[4])
        return result[4]
测试小书童 关闭了讨论 07月10日 11:03
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册