def loglevel(self, value): loglever = ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'] if value in loglever: self.__loglevel = value Logger('日志级别设置为: %s' % value) else: Logger('日志级别%s 不在%s中,日志级别设置为默认值:INFO' % (value, str(loglever))) self.__loglevel = 'INFO'
def Remove_file(file_path): try: if os.path.exists(file_path): os.remove(file_path) Logger('成功刪除文件 :%s' % file_path) else: Logger('不存在文件夾:%s' % file_path) except Exception as e: Logger('刪除文件拋出異常:%s' % e)
def seed(self): try: if isinstance(int(self.__seed), int): return self.__seed else: Logger('输入的send参数,类型必须是整数,否则send值默认为20') return 20 except Exception: Logger('输入的send参数,类型必须是整数,否则send值默认为20') return 20
def throttle(self): try: if isinstance(int(self.__throttle), int): return self.__throttle else: Logger('输入的throttle参数,类型必须是整数,否则throttle值默认为500') return 500 except Exception: Logger('输入的throttle参数,类型必须是整数,否则throttle值默认为500') return 500
def seed(self, value): try: if isinstance(int(value), int): Logger('seed值为: ' + value) self.__seed = value else: Logger('输入的send参数,类型必须是整数,否则send值默认为20') self.__seed = 20 except Exception: Logger('输入的send参数,类型必须是整数,否则send值默认为20') self.__seed = 20
def throttle(self, value): try: if isinstance(int(value), int): Logger('throttle的参数值为: ' + value) self.__throttle = value else: Logger('输入的throttle参数,类型必须是整数,否则throttle值默认为500') self.__throttle = 500 except Exception: Logger('输入的throttle参数,类型必须是整数,否则throttle值默认为500') self.__throttle = 500
def runtime(self): try: if isinstance(int(self.__runtime), int): if int(self.__runtime) > 600: Logger('最大运行时间是600分钟,大于600分钟会默认为600分钟') return 600 else: return self.__runtime except Exception: Logger('输入的运行时间必须是整数,否则默认运行时间为10分钟') return 10
def emptyLogcat(self): ''' monkey运行前执行 adb logcat -c 清空所有log缓存日志 :return: ''' try: Logger('使用adb logcat -c 清空手机中的log') os.popen('adb -s %s logcat -c' % self.devices) return 0 except Exception as e: Logger('执行adb logcat -c 出现异常: %s' % e) return 1
def runtime(self, value): try: if isinstance(int(value), int): if int(value) > 60: Logger('最大运行时间是60分钟,大于60分钟会默认设置为60分钟') self.__runtime = 60 else: Logger('执行时间设置为: %s 分钟' % value) self.__runtime = value except Exception: Logger('输入的运行时间必须是整数,否则默认运行时间为10分钟: ') self.__runtime = 10
def inspectapp(self, apkname): ''' 检测APP是否存在 :param apkname: :return: ''' try: cmd = 'adb -s %s shell pm list packages' % self.device result = os.popen(cmd) if apkname in result.read(): Logger('%s 存在' % apkname) return 0 else: Logger('%s 不存在' % apkname) return 1 except Exception: Logger('%s 检测失败' % apkname) return 1
def installAPP(self, apkname, apkpath): ''' 安装安装包 :param apkname: 安装包名称 :param apkpath: 安装包路径 :return: 0 安装成功 1安装失败 ''' try: if self.inspectapp(apkname) == 0: Logger('已有安装包') return 0 else: cmd = 'adb -s %s install %s' % (self.device, apkpath) os.system(cmd) if self.installAPP(apkname) == 0: Logger('安装安装包成功') return 0 else: Logger('安装安装包失败') return 1 except Exception as e: Logger('安装安装包失败/n' + e) return 1
def writterError(self, monkeyInfoPath, wirteErrorPath): ''' 解析log文件中是否有crash,ANR等错误,有的话写入writerErrorPath文件中 :param monkeyInfoPath: monkey日志文件地址 :param wirteErrorPath: 错误日志写入的文件地址 :return: 0 表示有错误日志 1表示没有错误日志 ''' # monkeyInfoPath = self.devices.monkeylog # wirteErrorPath = self.devices.writeerror try: f = open(monkeyInfoPath, 'r') lines = f.readlines() if len(lines) == 0: Logger('%s 路径的日志为空' % monkeyInfoPath) else: fr = open(wirteErrorPath, 'a', encoding='utf-8') for line in lines: if (re.findall('CRASH', line) or re.findall('ANR', line) or re.findall('No Response', line)): # 找到行数 number = lines.index(line) + 1 fr.write('第%s行' % number + ',' + '错误原因: %s' % line) fr.write('\n') f.close() fr.close() if os.path.getsize(wirteErrorPath) == 0: Logger('扫描%s路径下的日志未发现错误日志' % monkeyInfoPath) # os.system('rm -rf %s' % wirteErrorPath) return 1 else: Logger('扫描%s路径下的日志发现错误日志,过滤后的文件路径%s' % (monkeyInfoPath, wirteErrorPath)) return 0 except Exception as e: Logger('解析日志文件报错: %s' % e) return 1
class TestApi(unittest.TestCase): myLogger = Logger('ApiTest').GetLog() def setParameters(self, case_name, path, query, method, header): self.case_name = case_name self.path = path self.query = query self.method = method self.header = header @classmethod def setUpClass(cls): #做前提工作 print("-----------START----------------") @classmethod def tearDownClass(cls): #做结束工作 print("-------接口测试结束-------,请查看报告") # def test_print(self): # print(self.case_name) # print(self.path) # print(type(self.query)) # print(self.method) # print(type(self.header)) def test_api1(self): '''测试1''' #req = HttpRequest().send('post', url, data_json, header) data_json = json.loads(self.query) data_json = json.dumps(data_json) #header = json.loads(self.header) url = url1 + self.path print(url) print(self.method) print(data_json) print(type(data_json)) req = HttpRequest().send(self.method, url, data_json, eval(self.header)) print(req) #在使用try except 时, 捕获了assert函数产生的AssertionError异常, 导致异常没有上抛, 这时只需要在后面加上raise 就可以再次把它抛出。 try: self.assertEqual(req[1]['code'], '200', '测试失败,code码不符合预期') except AssertionError as e: #self.myLogger.error(format(e)) raise
def runMonkey(self): ''' 执行Monkey :return: ''' # 检查上一级目录是否存在某文件夹? # if not os.path.exists(self.devices.monkeyfolder): # os.mkdir(self.devices.monkeyfolder) # adb -s %s shell monkey 指定设备运行monkey # -s # -p 指定包名 # --hprof 指定该项后在事件序列发送前后会立即生成分析报告 # --throttle # --ignore-crashes 忽略奔溃 # --ignore-timeouts 忽略超时 # --ignore-security-exceptions 忽略安全异常 # --monitor-native-crashes 用于指定是否监视并报告应用程序发生崩溃的本地代码 # --pct-syskeys 系统事件的百分比 cmd = 'adb -s %s shell monkey ' \ '-s %d ' \ '-p %s ' \ '--hprof ' \ '--throttle %d ' \ '--ignore-crashes ' \ '--ignore-timeouts ' \ '--ignore-security-exceptions ' \ '--ignore-native-crashes ' \ '--monitor-native-crashes ' \ '--pct-syskeys 10 ' \ '-v -v -v %d 1>%s 2>%s' % \ (self.devices.device, int(self.devices.seed), self.devices.apkname, int(self.devices.throttle), self.event, self.devices.monkeylog, self.devices.monkeyerrorlog) Logger(cmd) pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout return cmd
def getProductInfo(self): ''' 获取当前设备的信息 :return: 设备信息 ''' try: m = 'unidefined' # 品牌 b = 'unidefined' # 系统版本号 v = 'unidefined' # 手机型号 m = os.popen('adb -s %s shell getprop ro.product.model' % self.device) b = os.popen('adb -s %s shell getprop ro.product.brand' % self.device) v = os.popen('adb -s %s shell getprop ro.build.version.release' % self.device) model = m.read().replace('\n', '').replace('\r', '') brand = b.read().replace('\n', '').replace('\r', '') version = v.read().replace('\n', '').replace('\r', '') return brand, model, version except Exception: Logger("获取手机型号报错") return 'unidefined' 'unidefined' 'unidefined'
def stopMonkey(self): ''' 停止monkey :return: ''' sleep(1) try: grep_cmd = 'adb -s %s shell ps | findstr monkey' % self.devices.device Logger(grep_cmd) pipe = os.popen(grep_cmd) result = pipe.read() Logger(result) if result == '': Logger('monkey进程不存在 : %s'%grep_cmd) else: Logger('monkey 进程存在 : %s'%grep_cmd) pid = result.split()[1] stop_cmd = 'adb -s %s shell kill %s' % (self.devices.device, pid) Logger(stop_cmd) os.system(stop_cmd) except Exception: Logger('停止 monkey 异常')
def run(): # 读取配置值 devices = Monkey_Config() # 加载设配信息类 adb = AdbCommon(devices.device) monkey = MonkeyCommon(devices) startTime = int(abs(round(time.time(), 0))) # 手机中是否有安装包 if adb.installAPP(devices.apkname, devices.apkpath) == 0: # 存在就执行下一步 # 清楚手机中的日志 monkey.emptyLogcat() Logger('开始执行脚本') cmd = monkey.runMonkey() flag = True while flag: currentTime = int(abs(round(time.time(), 0))) Logger('已经运行时间:%d' % (currentTime - startTime)) Logger('预期运行时间: %d' % (int(devices.runtime) * 60)) if (currentTime - startTime) >= (int(devices.runtime) * 60): monkey.stopMonkey() flag = False else: time.sleep(30) Logger('脚本停止执行') # 如果有错误日志,就发送邮件 if monkey.writterError(devices.monkeylog, devices.writeerror) == 0: send_mail(devices.runtime * 60, adb, cmd, devices.monkeylog, devices.monkeyerrorlog, devices.writeerror) else : Logger('刪除空文件 : %s,%s'%(devices.writeerror,devices.monkeyerrorlog)) Remove_file(devices.writeerror) else: Logger('安装失败')
import unittest from Common.configHttp import ConfigHttp from Common.logger import Logger from TestCase.login.getkey import login logger = Logger('TestUserInfo').get_logger() class TestUserInfo(unittest.TestCase): def setUp(self): self.base_url = '/api/user/getUserInfo' self.token = login() self.request = ConfigHttp() self.request.set_headers(self.token) self.data = {'device_type': 'web', 'token': self.token} self.AssertionError = [] def tearDown(self): self.assertEqual([], self.AssertionError) def test_userinfo(self): self.request.set_url(self.base_url) self.request.set_data(self.data) response = self.request.post() json = response.json() print(json)
import datetime import os import copy import locust.stats from locust import HttpLocust, TaskSet, task, between from Common.config import config_intel_api from Common.config_endpoints import indicator_endpoints from Common.logger import Logger LOG_FILE = "Logs/{0}_{1}.log".format( os.path.relpath(__file__), datetime.datetime.now().strftime("%Y-%m-%d-%S")) logger = Logger().get_logger(os.path.relpath(__file__), LOG_FILE) headers_indicator = copy.deepcopy(config_intel_api) headers_indicator['headers']['Accept'] = 'application/stix+json; version=2.1' locust.stats.CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW = 2 class IndicatorBehaviour(TaskSet): @task(1) def indicator_objectendpoint(self): res = self.client.get(indicator_endpoints['object'], auth=(config_intel_api['username'], config_intel_api['password']), headers=headers_indicator['headers']) assert res.status_code == 200 logger.debug('indicator_objectendpoint %s', res.status_code)
def apkname(self, value): Logger('要执行的包名是: ' + value) self.__apkname = value
def device(self, value): Logger('设备号为: ' + value) self.__device = value
from Common.config import get_params import time if __name__ == '__main__': #参数初始化 params = get_params() test_env = make_atari(params["env_name"]) params.update({"n_actions": test_env.action_space.n}) print(f"Environment: {params['env_name']}\n" f"Number of actions:{params['n_actions']}") # 创建训练环境 env = make_atari(params["env_name"]) env.seed(int(time.time())) agent = Agent(**params) logger = Logger(agent, **params) # 使用预训练模型 if not params["train_from_scratch"]: chekpoint = logger.load_weights() agent.online_model.load_state_dict(chekpoint["online_model_state_dict"]) agent.hard_update_of_target_network() params.update({"beta": chekpoint["beta"]}) min_episode = chekpoint["episode"] print("Keep training from previous run.") # 从头开始训练模型 else: min_episode = 0 print("Train from scratch.") #执行训练 if params["do_train"]:
import unittest <<<<<<< HEAD from Common import HTMLTestRunner ======= from HTMLTestRunner import HTMLTestRunner >>>>>>> 3844286a40da226ec37809448b36ca460b06ee04 from Util.basePath import os, base_path from Common.sendEmail import sendEmail from Common.logger import Logger log = Logger().get_logger("debug") class Run(object): def __init__(self): self.case_path = os.path.join(base_path, "TestCase") self.report_path = os.path.join(base_path, "Report", "report.html") log.info("case_path--->", self.case_path) log.info("report_path--->", self.report_path) def run(self): discover = unittest.defaultTestLoader.discover(self.case_path) log.info("case_list--->", discover) try: with open(self.report_path, "wb") as f: runner = HTMLTestRunner.HTMLTestRunner(stream=f, title="TEST", description="This is test!") runner.run(discover) except Exception as b: print("测试失败!!!", b)
from Common.configHttp import ConfigHttp from Common.logger import Logger url = '/api/account/login' target = readConfig.readConfig().get_user('target') password = readConfig.readConfig().get_user('password') device_type = 'web' target_type = '1' data = { 'device_type': device_type, 'target_type': target_type, 'target': target, 'password': password } request = ConfigHttp() log_token = Logger('lonin_token').get_logger() def login(): request.set_url(url) request.set_data(data) response = request.post() response = response.json() if response['code'] == 1: token = response['data']['token'] log_token.info("token值:{}".format(token)) return token else: log_token.info('登录失败:{}'.format(response))
def run(argv): ''' :return: ''' device = '' seed = '' apkname = '' throttle = '' runtime = '' loglevel = '' # 读取配置值 devices = Monkey_Config() # 加载设配信息类 adb = AdbCommon(devices.device) monkey = MonkeyCommon(devices) example = 'python run.py --device 69d8ac6f --seed 1001 --apkname com.nongfadai.android.beta3220 --throttle 500 --runtime 1 --loglevel INFO' try: options = [ 'device=', 'seed=', 'apkname=', 'throttle=', 'runtime=', 'loglevel=' ] opts, args = getopt.getopt(argv, 'd:s:a:t:r:l', options) for opt, arg in opts: if opt == '--device': devices.device = arg elif opt == '--seed': devices.seed = arg elif opt == '--apkname': devices.apkname = arg elif opt == '--throttle': devices.throttle = arg elif opt == '--runtime': devices.runtime = arg elif opt == '--loglevel': devices.loglevel = arg else: Logger('参考命令:%s' % example) except Exception as e: Logger(e) sys.exit() startTime = int(abs(round(time.time(), 0))) # 手机中是否有安装包 if adb.installAPP(devices.apkname, devices.apkpath) == 0: # 存在就执行下一步 # 清楚手机中的日志 monkey.emptyLogcat() Logger('开始执行脚本') cmd = monkey.runMonkey() flag = True while flag: currentTime = int(abs(round(time.time(), 0))) Logger('已经运行时间:%d' % (currentTime - startTime)) Logger('预期运行时间: %d' % (int(devices.runtime) * 60)) if (currentTime - startTime) >= (int(devices.runtime) * 60): monkey.stopMonkey() flag = False else: Logger('等一会~,还没到时间呢') time.sleep(30) Logger('脚本停止执行') # 如果有错误日志,就发送邮件 if monkey.writterError(devices.monkeylog, devices.writeerror) == 0: send_mail(devices.runtime * 60, adb, cmd, devices.monkeylog, devices.monkeyerrorlog, devices.writeerror) else: Logger('刪除空文件 : %s,%s' % (devices.writeerror, devices.monkeyerrorlog)) Remove_file(devices.writeerror) else: Logger('安装失败')
from Common.logger import Logger from Common.play import Play from Brain.agent import Agent from Common.utils import * from Common.config import get_params import time if __name__ == '__main__': params = get_params() test_env = make_atari(params["env_name"]) params.update({"n_actions": test_env.action_space.n}) #创建测试环境 env = make_atari(params["env_name"]) env.seed(int(time.time())) #初始化智能体 agent = Agent(**params) logger = Logger(agent, **params) #加载已经训练好的模型 chekpoint = logger.load_weights() player = Play(agent, env, chekpoint["online_model_state_dict"], **params) #开始测试模型 player.evaluate()
if __name__ == "__main__": params = get_params() test_env = make_atari(params["env_name"], episodic_life=False) params.update({"n_actions": test_env.action_space.n}) print(f"Number of actions: {params['n_actions']}") if params["do_intro_env"]: intro_env() env = make_atari(params["env_name"], episodic_life=False) agent = SAC(**params) logger = Logger(agent, **params) if params["do_train"]: if not params["train_from_scratch"]: episode = logger.load_weights() agent.hard_update_target_network() agent.alpha = agent.log_alpha.exp() min_episode = episode print("Keep training from previous run.") else: min_episode = 0 print("Train from scratch.") stacked_states = np.zeros(shape=params["state_shape"], dtype=np.uint8)
# -*- coding: utf-8 -*- # @Time : 2020/10/25 8:54 AM # @Author : Hui # @File : test_base.py import requests from json import dumps from Common.logger import Logger from requests.packages.urllib3.exceptions import InsecureRequestWarning logger = Logger().logger # 禁用安全请求警告 requests.packages.urllib3.disable_warnings(InsecureRequestWarning) class BaseTest(requests.Session): """ 接口基类,供后续脚本使用 """ def get_request(self, url, headers=None, params=None, cookies=None): ''' get请求方法 :param url: 地址 :param headers: 请求头 :param params: 请求参数 :param cookies: :return: ''' try:
import pytest from selenium import webdriver from PageObjects.login_page_xcfb import LoginPageXcfb from TestDatas import common_datas as CD from Common.logger import Logger import time logger = Logger(__name__).getlog() driver = None #声明它是一个fixture @pytest.fixture(scope="class") def access_web1(): global driver #前置操作 print("=====测试用例执行之前,setUpClass,整个测试类只执行一次") driver = webdriver.Chrome() driver.maximize_window() driver.get(CD.web_login_url) lg = LoginPageXcfb(driver) yield (driver, lg) #分割线; #后面接返回值 #后置操作 print("=====测试用例执行之后,tearDownClass,整个测试类只执行一次") driver.quit() @pytest.fixture() def refresh_page1(): global driver
@monkeylog.setter def monkeylog(self, value): self.__monkeylog = value @property def monkeyerrorlog(self): return self.__monkeyerrorlog @monkeyerrorlog.setter def monkeyerrorlog(self, value): self.__monkeyerrorlog = value @property def writeerror(self): return self.__writeerror @writeerror.setter def writeerror(self, value): self.writeerror = value if __name__ == '__main__': c = Monkey_Config() Logger(c.runtime) Logger(c.device) c.runtime = 70 Logger(c.runtime) c.runtime = 'oo' Logger(c.runtime)