def Perform(self): # 使用cursor()方法获取操作游标 self.db = self.connect_db() self.cursor = self.db.cursor() sql = self.get_sql() version = self.db.server_version Log().info('成功登录数据库:%s,版本为:%s,执行SQL:%s' % (self.getdb, version, sql)) if "SELECT" in sql or "select" in sql: # 查询 try: self.cursor.execute(sql) results = self.cursor.fetchall() Log().info('查询结果:%s' % results[0][0]) return results[0][0] except: Log().info("Error: unable to fetch data") raise elif "UPDATE" in sql or "update" in sql: #修改 try: self.cursor.execute(sql) self.db.commit() Log().info("更新成功") except: self.db.rollback() Log().info("Error:Has been rolled back") raise self.db.close()
def get_param(self): if self.param_place != 'database': return self.connent else: #获取数据库名 self.database = Getyaml(yamlparam="interface_db", interface=self.url).port_db() Log().info('当前接口涉及数据库:%s' % self.database) #执行数据库操作 post_data = Operate_db(self.database, self.url).Perform() Log().info('数据格式为:%s' % post_data) return post_data
def datacel(filrpath): try: file = xlrd.open_workbook(filrpath) me = file.sheets()[0] nrows = me.nrows listid = [] listname = [] listkey = [] listconeent = [] listparam_place = [] listurl = [] listfangshi = [] listqiwang1 = [] listqiwang2 = [] for i in range(1, nrows): listid.append(me.cell(i, 0).value) listname.append(me.cell(i, 1).value) listkey.append(me.cell(i, 2).value) listconeent.append(me.cell(i, 3).value) listparam_place.append(me.cell(i, 4).value) listurl.append(me.cell(i, 5).value) listfangshi.append((me.cell(i, 6).value)) listqiwang1.append((me.cell(i, 7).value)) listqiwang2.append((me.cell(i, 8).value)) return listid, listname, listkey, listconeent, listparam_place, listurl, listfangshi, listqiwang1, listname, listqiwang2 except: Log().error('打开测试用例失败,原因是:%s' % Exception)
def assertre(asserqingwang): if len(asserqingwang.split('=')) > 1: data = asserqingwang.split('&') #['code=4001'] result = dict([(item.split('=')) for item in data]) #{'code': '4001'} return result else: Log().info('填写测试预期值') raise {"code": 1, 'result': '填写测试预期值'}
def data(): path = file_path + "\" + "case{0}.xlsx".format(aa) listid, listname, listkey, listconeent, listparam_place, listurl, listfangshi, listqiwang1, listname, listqiwang2=datacel(path) make_data1 = [] try: for i in range(len(listid)): make_data.append({'url': listurl[i], 'listname': listname[i], 'key': listkey[i], 'coneent':listconeent[i], 'param_place': listparam_place[i], 'fangshi': listfangshi[i], 'expect1': listqiwang1[i], 'expect2': listqiwang2[i]}) i += 1 return make_data1 except: Log().error('打开测试用例失败,原因是:%s' % Exception)
def testCase(self, data_test): expect_one = dict(assertre(asserqingwang=data_test['expect1'])) expect_two = dict(assertre(asserqingwang=data_test['expect2'])) data1 = list(expect_two.keys())[0] #传递给实际值所要的key值,如task Log().info('获取用例数据:%s' % data_test) apijson = TestApi(url=data_test['url'], key=data_test['key'], connent=data_test['coneent'], fangshi=data_test['fangshi'], assertdata=data1, param_place=data_test['param_place']).testapi() Log().info('请求传入数据:url:%s,key:%s,参数:%s,请求方式:%s' % (data_test['url'], data_test['key'], data_test['coneent'], data_test['fangshi'])) #apijson = dict(api.getJson()) # Log().info('返回实际结果:%s' % apijson) try: self.assertEqual(int(expect_one['code']), apijson[0], msg='预期和返回不一致') Log().info('对【code】断言,断言结果--预期值%s == 实际值%s' % (expect_one['code'], apijson[0])) except: Log().warning('对【code】断言,断言结果--预期值%s != 实际值%s' % (expect_one['code'], apijson[0])) raise if data1 != "param": try: self.assertEqual(expect_two[data1], apijson[1], msg='预期和返回不一致') Log().info('对【%s】字段断言,断言结果--预期值%s == 实际值%s' % (data1, expect_two[data1], apijson[1])) except: Log().warning('对【%s】字段断言,断言结果--预期值%s != 实际值%s' % (data1, expect_two[data1], apijson[1])) raise
def assert_in(asserqiwang, fanhuijson): if len(asserqiwang.split('=')) > 1: data = asserqiwang.split('&') result = dict([(item.split('=')) for item in data]) value1 = ([(str(fanhuijson[key])) for key in result.keys()]) value2 = ([(str(value)) for value in result.values()]) if value1 == value2: return {'code': 0, "result": 'pass'} else: return {'code': 1, 'result': 'fail'} else: Log().info('填写测试预期值') return {"code": 2, 'result': '填写测试预期值'}
def _run_maxim(run, cases, command, actions, widget_black): log = Log() log.set_logger(run.get_device()['model'], os.path.join(run.get_path(), 'client.log')) log.i('udid: %s', run.get_device()['udid']) # set cls.path, it must be call before operate on any page path = ReportPath() path.set_path(run.get_path()) # set cls.driver, it must be call before operate on any page base_page = BasePage() if 'ip' in run.get_device(): base_page.set_driver(run.get_device()['ip']) else: base_page.set_driver(run.get_device()['serial']) try: # run cases base_page.d.shell('logcat -c') # 清空logcat if cases: run.run_cases(cases) Maxim().run_monkey(monkey_shell=command, actions=actions, widget_black=widget_black) base_page.d.shell('logcat -d > /sdcard/logcat.log') time.sleep(1) base_page.d.pull('/sdcard/logcat.log', os.path.join(path.get_path(), 'logcat.log')) base_page.d.pull('/sdcard/monkeyerr.txt', os.path.join(path.get_path(), 'monkeyerr.txt')) base_page.d.pull('/sdcard/monkeyout.txt', os.path.join(path.get_path(), 'monkeyout.txt')) base_page.set_original_ime() base_page.identify() if 'ip' in run.get_device(): log.i('release device %s ' % run.get_device()['serial']) atxserver2().release_device(run.get_device()['serial']) except AssertionError as e: log.e('AssertionError, %s', e)
def _run_cases(run, cases, retry, save_last_try): log = Log() log.set_logger(run.get_device()['model'], run.get_path() + '/' + 'client.log') log.i('udid: %s' % run.get_device()['udid']) # set cls.path, it must be call before operate on any page path = ReportPath() path.set_path(run.get_path()) # set cls.driver, it must be call before operate on any page base_page = BasePage() if 'ip' in run.get_device(): base_page.set_driver(run.get_device()['ip']) else: base_page.set_driver(run.get_device()['serial']) try: # print(run.get_device()) # 运行前准备 base_page.unlock_device() base_page.set_fastinput_ime() # 设置fastime输入法 # base_page.d.shell('logcat -c') # 清空logcat # 开始执行测试 run.run(cases, retry, save_last_try) # 结束后操作 base_page.unwatch_device() base_page.set_original_ime() # 将logcat文件上传到报告 # base_page.d.shell('logcat -d > /sdcard/logcat.log') # time.sleep(2) # base_page.d.pull('/sdcard/logcat.log', os.path.join(path.get_path(), 'logcat.log')) if 'ip' in run.get_device(): log.i('release device %s ' % run.get_device()['serial']) atxserver2().release_device(run.get_device()['serial']) except AssertionError as e: log.e('AssertionError, %s' % e)
def makedata(): #import os #path = os.getcwd() + '\\test_case_data\\case.xlsx' #path = globalparam.data_path + "\\" + "case.xlsx" path = globalparam.data_path + "/" + "case.xlsx" listid, listname, listkey, listconeent, listparam_place, listurl, listfangshi, listqiwang1, listname, listqiwang2 = datacel( path) make_data = [] try: for i in range(len(listid)): make_data.append({ 'url': listurl[i], 'listname': listname[i], 'key': listkey[i], 'coneent': listconeent[i], 'param_place': listparam_place[i], 'fangshi': listfangshi[i], 'expect1': listqiwang1[i], 'expect2': listqiwang2[i] }) i += 1 return make_data except: Log().error('打开测试用例失败,原因是:%s' % Exception)
import unittest import ddt from Public.expect import assertre from Public.get_excel import makedata from Public.log import Log from Public.select_request import TestApi data_test = makedata() logger = Log() def my_print(msg): logger.info(msg) @ddt.ddt class MyTest(unittest.TestCase): def setUp(self): my_print('测试用例开始执行') def tearDown(self): my_print('测试用例执行完毕') @ddt.data(*data_test) def test_api(self, data_test): my_print('获取用例数据:%s' % data_test) api = TestApi(url=data_test['url'], key=data_test['key'], connent=data_test['coneent'],
def setUp(self): Log().info('测试用例开始执行')
def tearDown(self): Log().info('测试用例执行完毕') Log().info('----------------------------------')
#!/usr/bin/env python # -*- coding: utf-8 -*- # from Public.basepage import BasePage # from uiautomator2 import UiObjectNotFoundError from Public.decorator import * from Public.log import Log from Demo import dm_config import json from Public.filetools import read_file package = json.loads(read_file(dm_config.info_path))['package'] log = Log() class baidu_page(BasePage): @teststep def set_text(self, text="西湖"): log.i('搜索栏输入%s' % text) self.d(resourceId="index-kw", className="android.widget.EditText").set_text(text) @teststep def click_search_btn(self): log.i('点击百度一下搜索按钮') self.d(text=u"百度一下", className="android.widget.Button").click()
# -*- coding: utf-8 -*- import requests, json from Public.log import Log from xml.etree.ElementTree import Element from xml.etree.ElementTree import tostring import xml.etree.ElementTree as ET logger = Log() def my_print(msg): logger.info(msg) class requ(): def __init__(self): self.headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:51.0) Gecko/20100101 Firefox/51.0" } def dict_to_xml(self, tag, d): #tag为头尾标签,d传入字典 elem = Element(tag) for key, val in d.items(): child = Element(key) child.text = str(val) elem.append(child) return elem def xml_to_dict(self, xml_str): msg = {} root_elem = ET.fromstring(xml_str) for ch in root_elem: msg[ch.tag] = ch.text
#!/usr/bin/env python # -*- coding: utf-8 -*- import time from Public.basepage import BasePage from Public.decorator import * from Demo.Page.home import home_page from Demo.Page import login import unittest import json from Public.filetools import read_file from Demo import dm_config log = Log() pkg_name = json.loads(read_file(dm_config.info_path))['package'] apkpath = json.loads(read_file(dm_config.info_path))['apk_path'] # @unittest.skip class TestBootStrap(unittest.TestCase, BasePage): '''BootStrap demo测试''' @classmethod @setupclass def setUpClass(cls): cls.d.app_start("com.github.android_app_bootstrap") # restart app @classmethod @teardownclass def tearDownClass(cls): cls.d.app_stop("com.github.android_app_bootstrap") # restart app # cls.set_original_ime()
import os import time import uiautomator2 as u2 from uiautomator2 import UiObjectNotFoundError import re from Public.reportpath import ReportPath from Public.test_data import get_apk_info from Public.config import internalapp, unlock_apk # from Public.chromedriver import ChromeDriver # from Public.ports import Ports from Public.log import Log log = Log() class BasePage(object): @classmethod def set_driver(cls, dri): cls.d = u2.connect(dri) # cls.d.debug = True # cls.d.implicitly_wait(10.0) def get_driver(self): return self.d @classmethod def local_install(cls, apk_path, clear=False, uninstall=True): ''' 安装本地apk 覆盖安装,不需要usb链接 :param apk_path: apk文件本地路径