def __generateTestCases(): from testdatas.models import NewAddAndCheck newaddandchecktestcase_all = NewAddAndCheck.objects.filter(is_run_case=True).\ filter(test_project="餐饮油烟监管治服一体化平台").filter(test_module="登录")\ .order_by('id') for newaddandchecktestcase in newaddandchecktestcase_all: forcount = newaddandchecktestcase.case_counts starttime = GetTimeStr().getTimeStr() if len(str(newaddandchecktestcase.id)) == 1: newaddandchecktestcaseid = '0000%s' % newaddandchecktestcase.id elif len(str(newaddandchecktestcase.id)) == 2: newaddandchecktestcaseid = '000%s' % newaddandchecktestcase.id elif len(str(newaddandchecktestcase.id)) == 3: newaddandchecktestcaseid = '00%s' % newaddandchecktestcase.id elif len(str(newaddandchecktestcase.id)) == 4: newaddandchecktestcaseid = '0%s' % newaddandchecktestcase.id elif len(str(newaddandchecktestcase.id)) == 5: newaddandchecktestcaseid = '%s' % newaddandchecktestcase.id else: newaddandchecktestcaseid = 'Id已经超过5位数,请重新定义' for i in range(1, forcount + 1): # 循环,从1开始 if len(str(i)) == 1: forcount_i = '0000%s' % i elif len(str(i)) == 2: forcount_i = '000%s' % i elif len(str(i)) == 3: forcount_i = '00%s' % i elif len(str(i)) == 4: forcount_i = '0%s' % i elif len(str(i)) == 5: forcount_i = '%s' % i else: forcount_i = 'Id已经超过5位数,请重新定义' args = [] args.append(newaddandchecktestcaseid) # args.append(i) args.append(newaddandchecktestcase.depend_click_case_id) args.append(newaddandchecktestcase.is_click_cancel) args.append(newaddandchecktestcase.id) args.append(newaddandchecktestcase.confirm_ele_find) args.append(newaddandchecktestcase.confirm_ele_find_value) args.append(newaddandchecktestcase.cancel_ele_find) args.append(newaddandchecktestcase.cancel_ele_find_value) args.append(newaddandchecktestcase.is_submit_success) args.append(newaddandchecktestcase.is_signel_page) args.append(newaddandchecktestcase.page_number_xpath) args.append(newaddandchecktestcase.result_table_ele_find) args.append(newaddandchecktestcase.result_table_ele_find_value) args.append(newaddandchecktestcase.table_colnum_counts) setattr( TestLoginClass, 'test_func_%s_%s_%s' % (newaddandchecktestcaseid, newaddandchecktestcase.test_case_title, forcount_i), TestLoginClass.getTestFunc( *args)) # 通过setattr自动为TestCase类添加成员方法,方法以“test_func_”开头
def __generateTestCases(): from testdatas.models import LoginAndCheck loginandchecktestcase_all = LoginAndCheck.objects.filter(is_run_case=True).\ filter(test_project="中石油_迭代一").filter(id=3).filter(test_module="登录")\ .order_by('id') for loginandchecktestcase in loginandchecktestcase_all: forcount = loginandchecktestcase.case_counts starttime = GetTimeStr().getTimeStr() if len(str(loginandchecktestcase.id)) == 1: loginandchecktestcaseid = '0000%s' % loginandchecktestcase.id elif len(str(loginandchecktestcase.id)) == 2: loginandchecktestcaseid = '000%s' % loginandchecktestcase.id elif len(str(loginandchecktestcase.id)) == 3: loginandchecktestcaseid = '00%s' % loginandchecktestcase.id elif len(str(loginandchecktestcase.id)) == 4: loginandchecktestcaseid = '0%s' % loginandchecktestcase.id elif len(str(loginandchecktestcase.id)) == 5: loginandchecktestcaseid = '%s' % loginandchecktestcase.id else: loginandchecktestcaseid = 'Id已经超过5位数,请重新定义' for i in range(1, forcount + 1): # 循环,从1开始 if len(str(i)) == 1: forcount_i = '0000%s' % i elif len(str(i)) == 2: forcount_i = '000%s' % i elif len(str(i)) == 3: forcount_i = '00%s' % i elif len(str(i)) == 4: forcount_i = '0%s' % i elif len(str(i)) == 5: forcount_i = '%s' % i else: forcount_i = 'Id已经超过5位数,请重新定义' args = [] args.append(loginandchecktestcaseid) # args.append(i) args.append(loginandchecktestcase.id) args.append(loginandchecktestcase.login_url) args.append(loginandchecktestcase.is_auto_input_code) args.append(loginandchecktestcase.code_image_xpath) args.append(loginandchecktestcase.code_type) args.append(loginandchecktestcase.code_input_ele_find) args.append(loginandchecktestcase.code_input_ele_find_value) args.append(loginandchecktestcase.login_button_ele_find) args.append(loginandchecktestcase.login_button_ele_find_value) args.append(loginandchecktestcase.click_login_button_delay_time) setattr( TestLoginClass, 'test_func_%s_%s_%s' % (loginandchecktestcaseid, loginandchecktestcase.test_case_title, forcount_i), TestLoginClass.getTestFunc( *args)) # 通过setattr自动为TestCase类添加成员方法,方法以“test_func_”开头
def __generateTestCases(): from testdatas.models import ClickAndBack clickandbacktestcase_all = ClickAndBack.objects.filter( id=123).order_by('id') for clickandbacktestcase in clickandbacktestcase_all: forcount = clickandbacktestcase.case_counts starttime = GetTimeStr().getTimeStr() if len(str(clickandbacktestcase.id)) == 1: clickandbacktestcaseid = '0000%s' % clickandbacktestcase.id elif len(str(clickandbacktestcase.id)) == 2: clickandbacktestcaseid = '000%s' % clickandbacktestcase.id elif len(str(clickandbacktestcase.id)) == 3: clickandbacktestcaseid = '00%s' % clickandbacktestcase.id elif len(str(clickandbacktestcase.id)) == 4: clickandbacktestcaseid = '0%s' % clickandbacktestcase.id elif len(str(clickandbacktestcase.id)) == 5: clickandbacktestcaseid = '%s' % clickandbacktestcase.id else: clickandbacktestcaseid = 'Id已经超过5位数,请重新定义' for i in range(1, forcount + 1): # 循环,从1开始 if len(str(i)) == 1: forcount_i = '0000%s' % i elif len(str(i)) == 2: forcount_i = '000%s' % i elif len(str(i)) == 3: forcount_i = '00%s' % i elif len(str(i)) == 4: forcount_i = '0%s' % i elif len(str(i)) == 5: forcount_i = '%s' % i else: forcount_i = 'Id已经超过5位数,请重新定义' args = [] args.append(clickandbacktestcaseid) args.append(i) args.append(clickandbacktestcase.depend_case_id) args.append(clickandbacktestcase.current_page_click_ele_find) args.append(clickandbacktestcase.current_page_click_ele_find_value) args.append(clickandbacktestcase.is_new) args.append(clickandbacktestcase.next_page_check_ele_find) args.append(clickandbacktestcase.next_page_check_ele_find_value) args.append(clickandbacktestcase.test_project) args.append(clickandbacktestcase.test_module) args.append(clickandbacktestcase.test_page) args.append(clickandbacktestcase.test_case_title) args.append(starttime) args.append(i) setattr( TestClickAndBackClass, 'test_func_%s_%s_%s' % (clickandbacktestcaseid, clickandbacktestcase.test_case_title, forcount_i), TestClickAndBackClass.getTestFunc( *args)) # 通过setattr自动为TestCase类添加成员方法,方法以“test_func_”开头
def __generateTestCases(): from testdatas.models import SearchAndCheck searchandchecktestcase_all = SearchAndCheck.objects.filter(is_run_case=False).\ filter(test_project="餐饮油烟监管治服一体化平台").\ filter(test_module="服务商管理").\ filter(test_page="排口信息").\ order_by('id') for searchandchecktestcase in searchandchecktestcase_all: forcount = searchandchecktestcase.case_counts starttime = GetTimeStr().getTimeStr() if len(str(searchandchecktestcase.id)) == 1: searchandchecktestcaseid = '0000%s' % searchandchecktestcase.id elif len(str(searchandchecktestcase.id)) == 2: searchandchecktestcaseid = '000%s' % searchandchecktestcase.id elif len(str(searchandchecktestcase.id)) == 3: searchandchecktestcaseid = '00%s' % searchandchecktestcase.id elif len(str(searchandchecktestcase.id)) == 4: searchandchecktestcaseid = '0%s' % searchandchecktestcase.id elif len(str(searchandchecktestcase.id)) == 5: searchandchecktestcaseid = '%s' % searchandchecktestcase.id else: searchandchecktestcaseid = 'Id已经超过5位数,请重新定义' for i in range(1, forcount + 1): # 循环,从1开始 if len(str(i)) == 1: forcount_i = '0000%s' % i elif len(str(i)) == 2: forcount_i = '000%s' % i elif len(str(i)) == 3: forcount_i = '00%s' % i elif len(str(i)) == 4: forcount_i = '0%s' % i elif len(str(i)) == 5: forcount_i = '%s' % i else: forcount_i = 'Id已经超过5位数,请重新定义' args = [] args.append(searchandchecktestcaseid) # args.append(i) args.append(searchandchecktestcase.depend_click_case_id) args.append(searchandchecktestcase.id) args.append(searchandchecktestcase.search_ele_find) args.append(searchandchecktestcase.search_ele_find_value) args.append(searchandchecktestcase.is_with_date) args.append(searchandchecktestcase.result_table_ele_find) args.append(searchandchecktestcase.result_table_ele_find_value) setattr( TestSearchClass, 'test_func_%s_%s_%s' % (searchandchecktestcaseid, searchandchecktestcase.test_case_title, forcount_i), TestSearchClass.getTestFunc( *args)) # 通过setattr自动为TestCase类添加成员方法,方法以“test_func_”开头
def inputtapinputtext(self,activebrowser,newaddid): timestr = GetTimeStr().getTimeStr() inputtext_list = [] from testdatas.models import InputTapInputText inputtapinputtexts = InputTapInputText.objects.filter(newaddandcheck_id=int(newaddid)) if str(inputtapinputtexts) != "<QuerySet []>": activebrowser.outPutMyLog(u"找到依赖数据") for inputtapinputtext in inputtapinputtexts: if inputtapinputtext.is_auto_input: if inputtapinputtext.auto_input_type == '1' : #自动生成0~9数字字符串 inputtextwithtimestr = automakestring.getDigits(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '2' : #小写字母 inputtextwithtimestr = automakestring.getAsciiLowercase(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '3' : #字母(大写) inputtextwithtimestr = automakestring.getAsciiUppercase(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '4' : #特殊符号 inputtextwithtimestr = automakestring.getSymbols(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '5' : #数字和字母(小写) inputtextwithtimestr = automakestring.getLowercaseAndDigits(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '6' : #数字和字母(大写) inputtextwithtimestr = automakestring.getUppercaseAndDigits(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '7' : #字母(大小写) inputtextwithtimestr = automakestring.getAsciiLetters(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '8' : #数字和字母(大小写) inputtextwithtimestr = automakestring.getLettersAndDigits(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '9' : #数字和字母和特殊符号 inputtextwithtimestr = automakestring.getLetterAndDigitsAndSymbols(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '10' : #数字和字母和特殊符号和空白字符 inputtextwithtimestr = automakestring.getLetterAndDigitsAndSymbolsAndWhitespace(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '11' : #汉字 inputtextwithtimestr = automakestring.getUnicodeZh(inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '12': #手机号 inputtextwithtimestr = automakephonenumber.creat_phone() elif inputtapinputtext.auto_input_type == '13': #身份证号 inputtextwithtimestr = automakeidnumber.create_IDcard() else: inputtextwithtimestr = u"自动输入字符的类型不正确,请输入正确的自动输入字符的类型" activebrowser.outPutErrorMyLog(u"自动输入字符的类型不正确,请输入正确的自动输入字符的类型") else: if inputtapinputtext.is_with_time: inputtextwithtimestr = "%s%s"%(inputtapinputtext.input_text,timestr) else: inputtextwithtimestr = inputtapinputtext.input_text if inputtapinputtext.input_ele_find!=None and inputtapinputtext.input_ele_find_value != None: activebrowser.findEleAndInputNum(0,inputtapinputtext.input_ele_find, inputtapinputtext.input_ele_find_value,inputtextwithtimestr) if inputtapinputtext.is_check: inputtext_list.append(inputtextwithtimestr) else: activebrowser.outPutErrorMyLog(u"没有找到依赖id[%s]对应的数据!" % newaddid) return inputtext_list
def handlerequestsheaders(self, activebrowser, apirequestdataid): timestr = GetTimeStr().getTimeStr() requestcookies_dict = {} from testapidatas.models import RequestCookies requestcookieses = RequestCookies.objects.filter( apirequestdata_id=int(apirequestdataid)) if str(requestcookieses) != "<QuerySet []>": activebrowser.outPutMyLog("找到依赖数据") for requestcookies in requestcookieses: #处理键值对的键 requestheader_dict_key = requestcookies.request_key #处理键值对的值 if requestcookies.is_auto_input: if requestcookies.auto_input_type == '1': requestheader_dict_value = automakestring.getDigits( requestcookies.auto_input_long) elif requestcookies.auto_input_type == '2': requestheader_dict_value = automakestring.getAsciiLowercase( requestcookies.auto_input_long) elif requestcookies.auto_input_type == '3': requestheader_dict_value = automakestring.getLettersAndDigits( requestcookies.auto_input_long) elif requestcookies.auto_input_type == '4': requestheader_dict_value = automakestring.getLetterAndDigitsAndSymbols( requestcookies.auto_input_long) elif requestcookies.auto_input_type == '5': requestheader_dict_value = automakestring.getLetterAndDigitsAndSymbolsAndWhitespace( requestcookies.auto_input_long) elif requestcookies.auto_input_type == '6': requestheader_dict_value = automakestring.getUnicodeZh( requestcookies.auto_input_long) else: requestheader_dict_value = u"自动输入字符的类型不正确,请输入正确的自动输入字符的类型" activebrowser.outPutErrorMyLog( u"自动输入字符的类型不正确,请输入正确的自动输入字符的类型") else: if requestcookies.is_with_time: requestheader_dict_value = "%s%s" % ( requestcookies.input_text, timestr) else: requestheader_dict_value = requestcookies.input_text requestcookies_dict[ requestheader_dict_key] = requestheader_dict_value else: activebrowser.outPutErrorMyLog("没有找到依赖id[%s]对应的数据!" % apirequestdataid) activebrowser.outPutMyLog("requestcookies_dict:%s" % requestcookies_dict) return requestcookies_dict
def __generateTestCases(): from testdatas.models import NewAddAndCheck newaddandchecktestcase_all = NewAddAndCheck.objects.filter(is_run_case=True).\ filter(test_project="中石油_迭代一").filter(id=215).filter(test_module="登录")\ .order_by('id') for newaddandchecktestcase in newaddandchecktestcase_all: forcount = newaddandchecktestcase.case_counts starttime = GetTimeStr().getTimeStr() if len(str(newaddandchecktestcase.id)) == 1: newaddandchecktestcaseid = '0000%s' % newaddandchecktestcase.id elif len(str(newaddandchecktestcase.id)) == 2: newaddandchecktestcaseid = '000%s' % newaddandchecktestcase.id elif len(str(newaddandchecktestcase.id)) == 3: newaddandchecktestcaseid = '00%s' % newaddandchecktestcase.id elif len(str(newaddandchecktestcase.id)) == 4: newaddandchecktestcaseid = '0%s' % newaddandchecktestcase.id elif len(str(newaddandchecktestcase.id)) == 5: newaddandchecktestcaseid = '%s' % newaddandchecktestcase.id else: newaddandchecktestcaseid = 'Id已经超过5位数,请重新定义' for i in range(1, forcount + 1): # 循环,从1开始 if len(str(i)) == 1: forcount_i = '0000%s' % i elif len(str(i)) == 2: forcount_i = '000%s' % i elif len(str(i)) == 3: forcount_i = '00%s' % i elif len(str(i)) == 4: forcount_i = '0%s' % i elif len(str(i)) == 5: forcount_i = '%s' % i else: forcount_i = 'Id已经超过5位数,请重新定义' args = [] args.append(newaddandchecktestcaseid) # args.append(i) args.append(newaddandchecktestcase.id) args.append(newaddandchecktestcase.confirm_ele_find) args.append(newaddandchecktestcase.confirm_ele_find_value) args.append(newaddandchecktestcase.click_confirm_delay_time) setattr( TestLoginClass, 'test_func_%s_%s_%s' % (newaddandchecktestcaseid, newaddandchecktestcase.test_case_title, forcount_i), TestLoginClass.getTestFunc( *args)) # 通过setattr自动为TestCase类添加成员方法,方法以“test_func_”开头
def inputtapinputtext(self, activebrowser, newaddid): timestr = GetTimeStr().getTimeStr() inputtext_list = [] from testdatas.models import InputTapInputText inputtapinputtexts = InputTapInputText.objects.filter( newaddandcheck_id=int(newaddid)) if str(inputtapinputtexts) != "<QuerySet []>": activebrowser.outPutMyLog(u"找到依赖数据") for inputtapinputtext in inputtapinputtexts: if inputtapinputtext.is_auto_input: if inputtapinputtext.auto_input_type == '1': inputtextwithtimestr = automakestring.getDigits( inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '2': inputtextwithtimestr = automakestring.getAsciiLowercase( inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '3': inputtextwithtimestr = automakestring.getLettersAndDigits( inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '4': inputtextwithtimestr = automakestring.getLetterAndDigitsAndSymbols( inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '5': inputtextwithtimestr = automakestring.getLetterAndDigitsAndSymbolsAndWhitespace( inputtapinputtext.auto_input_long) elif inputtapinputtext.auto_input_type == '6': inputtextwithtimestr = automakestring.getUnicodeZh( inputtapinputtext.auto_input_long) else: inputtextwithtimestr = u"自动输入字符的类型不正确,请输入正确的自动输入字符的类型" activebrowser.outPutErrorMyLog( u"自动输入字符的类型不正确,请输入正确的自动输入字符的类型") else: if inputtapinputtext.is_with_time: inputtextwithtimestr = "%s%s" % ( inputtapinputtext.input_text, timestr) else: inputtextwithtimestr = inputtapinputtext.input_text if inputtapinputtext.input_ele_find != None and inputtapinputtext.input_ele_find_value != None: activebrowser.findEleAndInputNum( 0, inputtapinputtext.input_ele_find, inputtapinputtext.input_ele_find_value, inputtextwithtimestr) if inputtapinputtext.is_check: inputtext_list.append(inputtextwithtimestr) else: activebrowser.outPutErrorMyLog(u"没有找到依赖id[%s]对应的数据!" % newaddid) return inputtext_list
def inputtapinputtext(self,activebrowser,newaddid): timestr = GetTimeStr().getTimeStr() inputtext_list = [] from testdatas.models import InputTapInputText inputtapinputtexts = InputTapInputText.objects.filter(newaddandcheck_id=int(newaddid)) if str(inputtapinputtexts) != "<QuerySet []>": activebrowser.outPutMyLog("找到依赖数据") for inputtapinputtext in inputtapinputtexts: if inputtapinputtext.is_with_time: inputtextwithtimestr = "%s%s"%(inputtapinputtext.input_text,timestr) else: inputtextwithtimestr = inputtapinputtext.input_text activebrowser.findEleAndInputNum(0,inputtapinputtext.input_ele_find, inputtapinputtext.input_ele_find_value,inputtextwithtimestr) if inputtapinputtext.is_check: inputtext_list.append(inputtextwithtimestr) else: activebrowser.outPutErrorMyLog("没有找到依赖id[%s]对应的数据!" % newaddid) return inputtext_list
def DrawPie(self, result): """ 绘制饼图用pie :return: """ labels = 'OK', 'F', 'E' fracs = [ result.success_count, result.failure_count, result.error_count ] colors = ['green', 'orange', 'red'] explode = [0, 0, 0] # 0.1 凸出这部分, plt.axes( aspect=1) # set this , Figure is round, otherwise it is an ellipse # autopct ,show percet plt.pie(x=fracs, colors=colors, labels=labels, explode=explode, autopct='%3.1f %%', shadow=True, labeldistance=1.1, startangle=90, pctdistance=0.6) # plt.show() # 显示图例 plt.legend() #设置饼图截图路径 gts = GetTimeStr() tStr = gts.getTimeStr() #获取当前时间串 currentny = gts.getTimeStrNY() #获取当前时间的年月 firedir = r'%s/media/report/%s/pies/' % (os.path.dirname( os.path.dirname(os.path.dirname( os.path.abspath(__file__)))), currentny) gts.createdir(firedir) logPath = firedir imgPath = os.path.join(logPath, "%s_pie.png" % tStr) #保存饼图 plt.savefig(imgPath) #显示饼图路径: showimgPath = r'%s/media/report/%s/pies/%s_pie.png' % ( DJANGO_SERVER_YUMING, currentny, tStr) #返回饼图路径 return showimgPath
class ActiveBrowser(object): def __init__(self): # self.driver = self.getChromeDriver() # self.driver = self.getIeDriver() self.driver = self.getFirefoxDriver() self.timeStr = GetTimeStr() #实例化 #使用火狐浏览器 def getFirefoxDriver(self): # binary = FirefoxBinary(r'D:\Program Files (x86)\Mozilla Firefox\firefox.exe') # firefoxdriver = webdriver.Firefox(firefox_binary=binary) fire_options = webdriver.FirefoxOptions() #为驱动加入无界面配置 fire_options.add_argument('--headless') #为驱动加入无界面配置 firefoxdriver = webdriver.Firefox() # firefoxdriver = webdriver.Firefox(firefox_options=fire_options) # 需要把驱动所在路径配置到系统环境变量里 firefoxdriver.maximize_window() #窗口最大化 return firefoxdriver #使用谷歌浏览器 def getChromeDriver(self): chrome_options = webdriver.ChromeOptions() #为驱动加入无界面配置 chrome_options.add_argument('--headless') #为驱动加入无界面配置 # chromedriver = webdriver.Chrome(chrome_options=chrome_options) # chromedriver = webdriver.Chrome() # 需要把驱动所在路径配置到系统环境变量里 path = r"%s/driver/chromedriver.exe" % str( os.path.dirname(os.path.dirname( os.path.abspath(__file__)))) #配置驱动路径 print("path:%s" % path) # path = r"D:\Users\Administrator\PycharmProjects\webtestdata\TestCaseFunction\driver\chromedriver.exe" #配置驱动路径 option = webdriver.ChromeOptions() option.add_argument( '--user-data-dir=C:\\Users\\Administrator\\Local\\Google\\Chrome\\User Data\\Default' ) # 设置成用户自己的数据目录 #浏览器输入chrome://version 下个人资料路径就是自己的数据目录 chromedriver = webdriver.Chrome(executable_path=path, chrome_options=option) chromedriver.maximize_window() #窗口最大化 self.delayTime(5) return chromedriver #使用IE浏览器 def getIeDriver(self): iedriver = webdriver.Ie() # 需要把驱动所在路径配置到系统环境变量里 return iedriver #使用Edge浏览器 def getEdgeDriver(self): edgedriver = webdriver.Edge() # 需要把驱动所在路径配置到系统环境变量里 return edgedriver #使用Opera浏览器 def getOperaDriver(self): operadriver = webdriver.Opera # 需要把驱动所在路径配置到系统环境变量里 return operadriver def outPutMyLog(self, context): mylog = MyLogs(context) mylog.runMyLog() def outPutErrorMyLog(self, context): mylog = MyLogs(context) mylog.runErrorLog() #打开网址 def getUrl(self, url): try: self.driver.get(url) self.outPutMyLog("进入网址:%s" % url) # print("进入网址:%s"% url) except Exception as e: self.getScreenshotAboutMySQL() # 截图关联django服务 self.outPutErrorMyLog("打开网页失败,关闭驱动.问题描述:[%s]" % e) self.closeBrowse() #获取当前页面的url def getNowPageUrl(self): NowPageUrl = self.driver.current_url self.outPutMyLog("当前页面的URL为:%s" % NowPageUrl) return NowPageUrl #获取元素 def findELe(self, findstyle, findstylevalue): issecond = False try: if str(findstyle) == "class_name": ele = self.driver.find_element_by_class_name(findstylevalue) self.outPutMyLog("找到class_name为【%s】的元素" % findstylevalue) elif str(findstyle) == "css_selector": ele = self.driver.find_element_by_css_selector(findstylevalue) self.outPutMyLog("找到css_selector为【%s】的元素" % findstylevalue) elif str(findstyle) == "id": ele = self.driver.find_element_by_id(findstylevalue) self.outPutMyLog("找到id为【%s】的元素" % findstylevalue) elif str(findstyle) == "link_text": ele = self.driver.find_element_by_link_text(findstylevalue) self.outPutMyLog("找到link_text为【%s】的元素" % findstylevalue) elif str(findstyle) == "name": ele = self.driver.find_element_by_name(findstylevalue) self.outPutMyLog("找到name为【%s】的元素" % findstylevalue) elif str(findstyle) == "partial_link_text": ele = self.driver.find_element_by_partial_link_text( findstylevalue) self.outPutMyLog("找到link_text为【%s】的元素" % findstylevalue) elif str(findstyle) == "tag_name": ele = self.driver.find_element_by_tag_name(findstylevalue) self.outPutMyLog("找到tag_name为【%s】的元素" % findstylevalue) elif str(findstyle) == "xpath": ele = self.driver.find_element_by_xpath(findstylevalue) self.outPutMyLog("找到xpath为【%s】的元素" % findstylevalue) else: self.outPutErrorMyLog( "元素的查找方式不再八类(id、name、class_name、tag_name、" "link_text、partial_link_text、css_selector、xpath)之中," "请输入正确的查找方式.") self.driver.execute_script("arguments[0].scrollIntoView();", ele) # 拖动到可见的元素去,影响截取特定区域的截图,不影响整个页面截图 self.driver.execute_script( "arguments[0].setAttribute('style',arguments[1]);", ele, "background:green;border:2px solid red") #高亮显示操作的元素 except Exception as e: self.outPutMyLog("问题描述:%s" % e) self.getScreenshotNormal() self.delayTime(5) issecond = True if issecond: try: if str(findstyle) == "class_name": ele = self.driver.find_element_by_class_name( findstylevalue) self.outPutMyLog("再次查找,找到class_name为【%s】的元素" % findstylevalue) elif str(findstyle) == "css_selector": ele = self.driver.find_element_by_css_selector( findstylevalue) self.outPutMyLog("再次查找,找到css_selector为【%s】的元素" % findstylevalue) elif str(findstyle) == "id": ele = self.driver.find_element_by_id(findstylevalue) self.outPutMyLog("再次查找,找到id为【%s】的元素" % findstylevalue) elif str(findstyle) == "link_text": ele = self.driver.find_element_by_link_text(findstylevalue) self.outPutMyLog("再次查找,找到link_text为【%s】的元素" % findstylevalue) elif str(findstyle) == "name": ele = self.driver.find_element_by_name(findstylevalue) self.outPutMyLog("再次查找,找到name为【%s】的元素" % findstylevalue) elif str(findstyle) == "partial_link_text": ele = self.driver.find_element_by_partial_link_text( findstylevalue) self.outPutMyLog("再次查找,找到link_text为【%s】的元素" % findstylevalue) elif str(findstyle) == "tag_name": ele = self.driver.find_element_by_tag_name(findstylevalue) self.outPutMyLog("再次查找,找到tag_name为【%s】的元素" % findstylevalue) elif str(findstyle) == "xpath": ele = self.driver.find_element_by_xpath(findstylevalue) self.outPutMyLog("再次查找,找到xpath为【%s】的元素" % findstylevalue) else: self.outPutErrorMyLog( "元素的查找方式不再八类(id、name、class_name、tag_name、" "link_text、partial_link_text、css_selector、xpath)之中," "请输入正确的查找方式.") self.driver.execute_script( "arguments[0].scrollIntoView();", ele) # 拖动到可见的元素去,影响截取特定区域的截图,不影响整个页面截图 self.driver.execute_script( "arguments[0].setAttribute('style',arguments[1]);", ele, "background:green;border:2px solid red") # 高亮显示操作的元素 except Exception as e: self.getScreenshotAboutMySQL() #截图关联django服务 # self.getScreenshot() #截图不关联django服务 self.outPutErrorMyLog("停顿5秒后再次查找依然未找到元素.问题描述:%s" % e) self.closeBrowse() return ele #获取控件截图 def findEleImageNum(self, num, findstyle, findstylevalue): ele = self.findELe(findstyle, findstylevalue) #获取元素控件 pageScreenshotpath = self.getScreenshotNormal() # 获取整个页面截图 # location = ele.location #获取验证码x,y轴坐标 #截取了BUSINESS location = ele.location_once_scrolled_into_view # 获取元素x,y轴坐标 #消除self.driver.execute_script("arguments[0].scrollIntoView();", ele) 对截图的影响 截取了login imgae size = ele.size #获取元素的长宽 coderange = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height'])) #写成我们需要截取的位置坐标 pageScreenshot = Image.open(pageScreenshotpath) #打开截图 imageScreen = pageScreenshot.crop( coderange) #使用Image的crop函数,从截图中再次截取我们需要的区域,即验证码区域 tStr = self.getTimeStr() eleimage = "%s/imagefile/ele/%s_%s_ele.png" % (str( os.path.dirname(os.path.dirname( os.path.abspath(__file__)))), num, tStr) imageScreen.save(eleimage) #保存控件截图 self.outPutMyLog('获取到的元素的截图路径为:%s' % eleimage) return ele #查找元素,然后输入内容 def findEleAndInputNum(self, num, findstyle, findstylevalue, inputcontent): ele = self.findEleImageNum(num, findstyle, findstylevalue) ele.clear() #清除输入框内容 ele.send_keys(inputcontent) #输入内容 # self.delayTime(3) displaytext = self.findEleAndReturnValueNum(num, findstyle, findstylevalue, 'value') if str(inputcontent) == str(displaytext): self.outPutMyLog("输入内容:%s;显示内容:%s" % (inputcontent, displaytext)) else: self.outPutErrorMyLog("输入内容:%s;显示内容:%s" % (inputcontent, displaytext)) # self.delayTime #查找元素,然后返回元素的默认显示文字 def findEleAndReturnValueNum(self, num, findstyle, findstylevalue, valuename): ele = self.findEleImageNum(num, findstyle, findstylevalue) eletext = ele.get_attribute(valuename) self.outPutMyLog("得到的元素属性【%s】的值为:%s" % (valuename, eletext)) return eletext #查找元素,然后点击 def findEleAndClick(self, num, findstyle, findstylevalue): ele = self.findEleImageNum(num, findstyle, findstylevalue) ele.click() #点击 self.outPutMyLog("点击元素") self.delayTime(3) return ele #通过xpath查找元素 def findElementByXpath(self, path): issecond = False try: ele = self.driver.find_element_by_xpath(path) self.outPutMyLog("找到Xpath为【%s】的元素" % path) self.driver.execute_script("arguments[0].scrollIntoView();", ele) # 拖动到可见的元素去,影响截取特定区域的截图,不影响整个页面截图 self.driver.execute_script( "arguments[0].setAttribute('style',arguments[1]);", ele, "background:green;border:2px solid red") #高亮显示操作的元素 #使用JavaScript代码将传入的页面元素对象的背景颜色和边框颜分别设置为绿色和红色 except Exception as e: self.outPutErrorMyLog("问题描述:%s" % e) # print(e) self.getScreenshotNormal() self.delayTime(5) issecond = True if issecond: try: ele = self.driver.find_element_by_xpath(path) self.outPutMyLog("再次找到Xpath为【%s】的元素" % path) self.driver.execute_script( "arguments[0].scrollIntoView();", ele) # 拖动到可见的元素去,影响截取特定区域的截图,不影响整个页面截图 self.driver.execute_script( "arguments[0].setAttribute('style',arguments[1]);", ele, "background:green;border:2px solid red") # 高亮显示操作的元素 # 使用JavaScript代码将传入的页面元素对象的背景颜色和边框颜分别设置为绿色和红色 # print("最终找到元素") except Exception as e: self.getScreenshotAboutMySQL() #截图关联django服务 # self.getScreenshot() #截图不关联django服务 self.outPutErrorMyLog("停顿5秒后再次查找依然未找到元素.问题描述:%s" % e) self.closeBrowse() self.isActiveBrowser = True return ele #获取控件截图 def getEleImage(self, num, path): ele = self.findElementByXpath(path) #获取元素控件 pageScreenshotpath = self.getScreenshotNormal() # 获取整个页面截图 # location = ele.location #获取验证码x,y轴坐标 #截取了BUSINESS location = ele.location_once_scrolled_into_view # 获取元素x,y轴坐标 #消除self.driver.execute_script("arguments[0].scrollIntoView();", ele) 对截图的影响 截取了login imgae size = ele.size #获取元素的长宽 coderange = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height'])) #写成我们需要截取的位置坐标 pageScreenshot = Image.open(pageScreenshotpath) #打开截图 imageScreen = pageScreenshot.crop( coderange) #使用Image的crop函数,从截图中再次截取我们需要的区域,即验证码区域 tStr = self.getTimeStr() eleimage = "%s/imagefile/ele/%s_%s_ele.png" % (str( os.path.dirname(os.path.dirname( os.path.abspath(__file__)))), num, tStr) imageScreen.save(eleimage) #保存控件截图 self.outPutMyLog('获取到的元素的截图路径为:%s' % eleimage) return ele #通过xpath查找元素,然后返回元素的text内容 def findElementByXpathAndReturnText(self, num, path): ele = self.getEleImage(num, path) eletext = ele.text self.outPutMyLog("元素的Xpath路径为:%s;对应的文本信息为:%s" % (path, eletext)) self.delayTime(3) return eletext def findElementByXpathAndReturnTextNotNum(self, path): ele = self.findElementByXpath(path) eletext = ele.text self.outPutMyLog("元素的Xpath路径为:%s;对应的文本信息为:%s" % (path, eletext)) self.delayTime(3) return eletext #通过xpath查找元素,然后返回元素的标签名(例如input) def findElementByXpathAndReturnTagName(self, path): ele = self.findElementByXpath(path) eletext = ele.tag_name return eletext #通过xpath查找元素,然后返回元素的默认显示文字 def findElementByXpathAndReturnValue(self, path, valuename): ele = self.findElementByXpath(path) eletext = ele.get_attribute(valuename) return eletext #通过xpath查找元素,然后返回元素的默认显示文字 def findElementByXpathAndReturnValueNum(self, num, path, valuename): ele = self.getEleImage(num, path) eletext = ele.get_attribute(valuename) self.outPutMyLog("得到的元素属性【%s】的值为:%s" % (valuename, eletext)) return eletext #通过xpath查找元素,然后输入内容 def findElementByXpathAndInput(self, path, inputcontent): ele = self.findElementByXpath(path) ele.clear() #清除输入框内容 ele.send_keys(inputcontent) #输入内容 #通过xpath查找元素,然后输入内容 def findElementByXpathAndInputNum(self, num, path, inputcontent): ele = self.getEleImage(num, path) ele.clear() #清除输入框内容 ele.send_keys(inputcontent) #输入内容 # self.delayTime(3) displaytext = self.findElementByXpathAndReturnValueNum( num, path, 'value') self.outPutMyLog("输入内容:%s;显示内容:%s" % (inputcontent, displaytext)) # self.delayTime #通过xpath查找元素,然后情况输入框中的内容 def findElementByXpathAndDeleteInputContentNum(self, num, path): ele = self.getEleImage(num, path) displaytext = self.findElementByXpathAndReturnValueNum( num, path, 'value') ele.clear() #清除输入框内容 self.outPutMyLog("已经删除内容:%s." % displaytext) # self.delayTime(3000) #通过xpath查找元素,移除其Readonly属性然后输入内容 def findElementByXpathAndInputNumRemoveReadonly(self, num, path, inputcontent): ele = self.getEleImage(num, path) #移除Readonly属型 self.removeReadonly(ele) ele.clear() #清除输入框内容 ele.send_keys(inputcontent) #输入内容 # 设置Readonly属型为空 self.setReadonly(ele) # 点击使日期谈框消失 self.mockClickBlank(0, 0) displaytext = self.findElementByXpathAndReturnValueNum( num, path, 'value') self.outPutMyLog("输入内容:%s;显示内容:%s" % (inputcontent, displaytext)) # self.delayTime(3000) #通过xpath查找元素,使用JS直接设置Input框属性值(value=) def findElementByXpathAndInputNumJsSetValue(self, num, path, inputcontent): ele = self.getEleImage(num, path) self.jsSetValue(ele, inputcontent) displaytext = self.findElementByXpathAndReturnValueNum( num, path, 'value') self.outPutMyLog("输入内容:%s;显示内容:%s" % (inputcontent, displaytext)) # self.delayTime(3000) # 通过xpath查找元素,然后点击日期input框,点击选择日期路径 #日期控件路径path1,日期路径path2,日期左移月路径path3,日期右移月路径path4 def findElementByXpathAndClickAbountData(self, num, path1, path2, pathleft=None, pathright=None, pathconfirm=None): #点击日期input框 self.findElementByXpathAndClickNum(num, path1) if pathleft != None: #点击日期左移月按钮 self.findElementByXpathAndClickNum(num, pathleft) if pathright != None: #点击日期右移月按钮 self.findElementByXpathAndClickNum(num, pathright) #点击日期日路径 self.findElementByXpathAndClickNum(num, path2) if pathconfirm != None: self.findElementByXpathAndClickNum(num, pathconfirm) displaytext = self.findElementByXpathAndReturnValueNum( num, path1, 'value') self.outPutMyLog("日期显示内容:%s" % displaytext) self.mockClickBlank(0, 0) # 通过xpath查找元素,然后点击日期input框,点击选择日期路径,选择时分秒(预留) #日期控件路径path1,日期路径path2,分路径path3,日期左移月路径pathleft,日期右移月路径pathright def findElementByXpathAndClickAbountDataToSecound(self, num, path1, path2, path3, pathleft=None, pathright=None): #点击日期input框 self.findElementByXpathAndClickNum(num, path1) if pathleft != None: #点击日期左移月按钮 self.findElementByXpathAndClickNum(num, pathleft) if pathright != None: #点击日期右移月按钮 self.findElementByXpathAndClickNum(num, pathright) #点击日期日路径 self.findElementByXpathAndClickNum(num, path2) #点击日期时分秒路径 self.findElementByXpathAndClickNum(num, path3) displaytext = self.findElementByXpathAndReturnValueNum( num, path1, 'value') self.outPutMyLog("日期显示内容:%s" % displaytext) self.mockClickBlank(0, 0) #通过xpath查找元素,设置其Readonly属性值为空 def findElementByXpathAndInputNumSetReadonly(self, num, path): ele = self.getEleImage(num, path) self.setReadonly(ele) # self.delayTime(3000) #通过xpath查找元素,然后点击 def findElementByXpathAndClick(self, path): ele = self.findElementByXpath(path) ele.click() #点击 self.outPutMyLog("点击元素的Xpath路径为:%s" % path) # print("点击元素的Xpath路径为:%s" % path) self.delayTime(3) return ele #通过xpath查找元素,然后点击 def findElementByXpathAndClickNum(self, num, path): self.delayTime(1) ele = self.getEleImage(num, path) ele.click() #点击 self.outPutMyLog("点击Xpath路径为[%s]的元素" % path) # print("点击元素的Xpath路径为:%s" % path) self.delayTime(2) return ele #通过xpath查找元素,然后点击 def findElementByXpathAndScriptClick(self, path): ele = self.findElementByXpath(path) self.driver.execute_script("arguments[0].click();", ele) self.delayTime(3) return ele #通过xpath查找元素,然后点击 def findElementByXpathAndScriptClickNum(self, num, path): self.delayTime(1) ele = self.getEleImage(num, path) self.driver.execute_script("arguments[0].click();", ele) self.outPutMyLog("点击xpath为[%s]的元素" % path) self.delayTime(2) return ele #通过xpath查找到要输入文件的input元素,然后上传文件 def findElementByXpathAndAndFile(self, path, filepath): ele = self.findElementByXpath(path) try: ele.send_keys(filepath) self.delayTime(1) except Exception as e: self.outPutErrorMyLog("上传文件失败,关闭驱动.问题描述:%s" % e) self.closeBrowse() #通过xpath查找到要输入文件的input元素,然后上传文件 def findElementByXpathAndAndFileNum(self, num, path, filepath): ele = self.getEleImage(num, path) try: ele.send_keys(filepath) self.delayTime(1000) except Exception as e: self.outPutErrorMyLog("上传文件失败,关闭驱动.问题描述:%s" % e) self.closeBrowse() #通过xpath查找到要输入文件的input元素,然后上传文件 #pip install SendKeys #import win32gui #import win32con #import time def findElementByXpathAndAndFileNumVue(self, num, path, filepath): ele = self.findElementByXpathAndScriptClickNum(num, path) # ele = self.getEleImage(num,path) try: #pip install pywin32 #import win32gui # import win32con #文件名:D:\pic\1.jpg dialog = win32gui.FindWindow('#32770', '文件上传') # 对话框 ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None) ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None) Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None) # 上面三句依次寻找对象,直到找到输入框Edit对象的句柄 button = win32gui.FindWindowEx(dialog, 0, 'Button', None) # 确定按钮Button win32gui.SendMessage(Edit, win32con.WM_SETTEXT, None, filepath) # 往输入框输入绝对地址 win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button) # 按button self.delayTime(5) except Exception as e: self.outPutErrorMyLog("上传文件失败,关闭驱动.问题描述:%s" % e) # self.delayTime(1000) self.closeBrowse() #通过xpath查找到select元素,然后点击,然后点击要选择的项 def findElementByXpathAndClickOptionXpath(self, xpath, optiontextxpath): try: self.findElementByXpathAndScriptClick(xpath) self.findElementByXpathAndScriptClick(optiontextxpath) self.delayTime(2) except Exception as e: self.outPutErrorMyLog("出现问题,关闭驱动.问题描述:%s" % e) self.closeBrowse() #通过xpath查找到select元素,然后点击,然后点击要选择的项 def findElementByXpathAndClickOptionXpathNum(self, num, xpath, optiontextxpath): try: self.findElementByXpathAndScriptClickNum(num, xpath) self.findElementByXpathAndScriptClickNum(num, optiontextxpath) self.delayTime(2) except Exception as e: self.outPutErrorMyLog("出现问题,关闭驱动.问题描述:%s" % e) self.closeBrowse() #通过xpath查找到select元素,选择要选择的项 def findElementByXpathAndReturnOptions(self, path, optiontext): ele = Select(self.findElementByXpath(path)) try: selectoption = ele.select_by_visible_text(optiontext) self.delayTime(2) except Exception as e: self.outPutMyLog("填写内容与选项内容对不上,关闭驱动.问题描述:%s" % e) self.closeBrowse() #通过xpath查找到select元素,选择要选择的项 def findElementByXpathAndReturnOptionsNum(self, num, path, optiontext): ele = Select(self.getEleImage(num, path)) try: selectoption = ele.select_by_visible_text(optiontext) self.delayTime(2) except Exception as e: self.outPutErrorMyLog("填写内容与选项内容对不上,关闭驱动.问题描述:%s" % e) self.closeBrowse() #通过xpath查找到select并打印其所有的options def findElementByXpathAndReturnAllOptions(self, path): ele = Select(self.findElementByXpath(path)) optionlist = [] try: all_options = ele.options # print('所有选项内容如下:',all_options) for option in all_options: optionlist.append(option.text) # print('选项内容为:',option.text) self.outPutMyLog('获取的选项所有内容:%s' % optionlist) return optionlist except Exception as e: self.outPutErrorMyLog("获取选项内容出错,关闭驱动.问题描述%e" % e) self.closeBrowse() #通过xpath查找到tbody并打印表格里所有内容 def findElementByXpathAndReturnTable(self, path): ele = self.findElementByXpath(path) # print('tagname:',ele.tag_name) tabledic = {} try: trlist = ele.find_elements_by_tag_name('tr') # print(len(trlist)) for i in range(0, len(trlist)): # print('第%s行内容如下:\n'% str(i+1)) #遍历行对象,并获取每一行中所有列对象 tdlist = trlist[i].find_elements_by_tag_name('td') collist = [] for j in range(0, len(tdlist)): #遍历表格中的列,并打印单元格内容 collist.append(tdlist[j].text) # print('第%s列内容如下:'% str(j+1),tdlist[j].text) tabledic[i + 1] = collist self.outPutMyLog('获取的表格内容:%s' % tabledic) # print('获取的表格内容:',tabledic) return tabledic # print('列表内容为:',option.text) except Exception as e: self.outPutErrorMyLog("获取表格内容出错,关闭驱动.问题描述:%s" % e) self.closeBrowse() #通过xpath查找到tbody并打印表格里所有内容 def findElementByXpathAndReturnTableNum(self, num, path): ele = self.getEleImage(num, path) # ele = self.findElementByXpath(path) # print('tagname:',ele.tag_name) tabledic = {} try: trlist = ele.find_elements_by_tag_name('tr') # print(len(trlist)) for i in range(0, len(trlist)): # print('第%s行内容如下:\n'% str(i+1)) #遍历行对象,并获取每一行中所有列对象 tdlist = trlist[i].find_elements_by_tag_name('td') collist = [] for j in range(0, len(tdlist)): #遍历表格中的列,并打印单元格内容 collist.append(tdlist[j].text) # print('第%s列内容如下:'% str(j+1),tdlist[j].text) tabledic[i + 1] = collist self.outPutMyLog('获取的表格内容:%s' % tabledic) # print('获取的表格内容:',tabledic) return tabledic # print('列表内容为:',option.text) except Exception as e: self.outPutErrorMyLog("获取表格内容出错,关闭驱动.问题描述:%s" % e) self.closeBrowse() def checktable(self, path, inputtext, colnum): tabledic = self.findElementByXpathAndReturnTable(path) for value in tabledic.values(): if inputtext.lower() in value[colnum].lower(): self.outPutMyLog('input输入内容变小写:%s' % inputtext.lower()) self.outPutMyLog('搜索到的表格内容变小写:%s' % value[colnum].lower()) else: self.outPutMyLog("搜索到的内容不匹配!!!") #获取页面截图 def getScreenshot(self): driver = self.driver self.outPutMyLog("调用截取图片函数") tStr = self.getTimeStr() #获取当前时间串 currentny = self.getTimeStrNY() #获取当前时间的年月 # path = "../imagefile/%s.png"% tStr # path = '%s/screenshots/screenpicture_%s.png' % ( # str(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), tStr) firedir = r'%s/media/report/%s/screenshots/' % (os.path.dirname( os.path.dirname(os.path.dirname( os.path.abspath(__file__)))), currentny) self.createdir(firedir) path = '%s/screenpicture_%s.png' % (firedir, tStr) print(path) driver.get_screenshot_as_file(path) self.outPutMyLog("*****") self.outPutMyLog(path) self.outPutMyLog("*****") return path #获取页面截图 def getScreenshotAboutMySQL(self): driver = self.driver self.outPutErrorMyLog("调用截取图片函数") tStr = self.getTimeStr() #获取当前时间串 currentny = self.getTimeStrNY() #获取当前时间的年月 firedir = r'%s/media/report/%s/screenshots/' % (os.path.dirname( os.path.dirname(os.path.dirname( os.path.abspath(__file__)))), currentny) self.createdir(firedir) path = '%s/screenpicture_%s.png' % (firedir, tStr) pathaboutmysql = r'media\report\%s\screenshots\screenpicture_%s.png' % ( currentny, tStr) driver.get_screenshot_as_file(path) self.outPutErrorMyLog("*****") self.outPutErrorMyLog(pathaboutmysql) #打印截图路径,供报告截图使用 self.outPutErrorMyLog("*****") return path #获取页面截图 def getScreenshotNormal(self): driver = self.driver self.outPutMyLog("调用截取图片函数") tStr = self.getTimeStr() path = "%s/imagefile/%s.png" % (str( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), tStr) driver.get_screenshot_as_file(path) return path #获取code码截图 def getCodeImage(self, path): pageScreenshotpath = self.getScreenshotNormal() # 获取整个页面截图 image = self.findElementByXpath(path) #获取图片验证码控件 # location = image.location #获取验证码x,y轴坐标 location = image.location_once_scrolled_into_view # 获取验证码x,y轴坐标 #消除self.driver.execute_script("arguments[0].scrollIntoView();", ele) 对截图的影响 size = image.size #获取验证码的长宽 coderange = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height'])) #写成我们需要截取的位置坐标 pageScreenshot = Image.open(pageScreenshotpath) #打开截图 imageScreen = pageScreenshot.crop( coderange) #使用Image的crop函数,从截图中再次截取我们需要的区域,即验证码区域 tStr = self.getTimeStr() path = "%s/imagefile/%s_code.png" % (str( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), tStr) imageScreen.save(path) #保存验证码图片 return tStr #获取验证码文字信息 def getcodetext(self, path): imagecodestr = self.getCodeImage(path) imagecode = Image.open( "%s/imagefile/%s_code.png" % (str(os.path.dirname(os.path.dirname( os.path.abspath(__file__)))), imagecodestr)) # 打开验证码图片 pixtongji = [] for x in range(imagecode.size[1]): for y in range(imagecode.size[0]): # 遍历图片的xy坐标像素点颜色 pix = imagecode.getpixel((y, x)) pixtongji.append(pix) nonepixtongjidic = {} for item in pixtongji: if item in nonepixtongjidic.keys(): nonepixtongjidic[item] += 1 else: nonepixtongjidic[item] = 1 self.outPutMyLog("nonepixtongjidic:%s" % nonepixtongjidic) nonepixtongjilist = sorted(nonepixtongjidic.values(), reverse=True) #按照键值对的值对字典进行倒序排序 numvalue = [] numvalue.append(nonepixtongjilist[1]) #获取第二个值 getkey = self.getDictKey(nonepixtongjidic, numvalue) img_new = Image.new('P', imagecode.size, 255) for x in range(imagecode.size[1]): for y in range(imagecode.size[0]): # 遍历图片的xy坐标像素点颜色 pix = imagecode.getpixel((y, x)) # print(pix) # 自己调色,r(pix[0])=0,g(pix[1])=0,b(pix[2])>0为蓝色 for i in range(len(getkey)): if (pix[0] == getkey[i][0] and pix[1] == getkey[i][1] and pix[2] == getkey[i][2]): # 把遍历的结果放到新图片上,0为透明度,不透明 img_new.putpixel((y, x), 0) newpath = "%s/imagefile/%s_codegary.png" % (str( os.path.dirname(os.path.dirname( os.path.abspath(__file__)))), imagecodestr) img_new.save(newpath, format='png') imagecode = Image.open(newpath) #打开验证码图片 imgry = imagecode.convert( 'L' ) # 图像加强,二值化,PIL中有九种不同模式。分别为1,L,P,RGB,RGBA,CMYK,YCbCr,I,F。L为灰度图像 sharpness = ImageEnhance.Contrast(imgry) #对比度增强 imagecodegary = sharpness.enhance(2.0) #2.0为图像的饱和度 imagecodegary.save(newpath) #保存灰度值验证码 endcode = Image.open(newpath) #打开灰度值验证码 codetext = pytesseract.image_to_string(endcode).strip() #获取验证码文本文件 return codetext #获取字典对应值的键 def getDictKey(self, dict, prevalue): getkey = [] for key, value in dict.items(): for i in range(len(prevalue)): if value == prevalue[i]: getkey.append(key) return getkey #获取时间串 def getTimeStr(self): tStr = self.timeStr.getTimeStr() return tStr def getTimeStrNY(self): tStrNY = self.timeStr.getTimeStrNY() return tStrNY #获取cookies def getCookies(self): cookies = self.driver.get_cookies() for cookie in cookies: self.outPutMyLog("获取的cookie的值为:%s" % cookie) return cookies #写入cookies def writerCookies(self, cookies, url, url2): self.outPutMyLog("\n开始写入cookie-----------------\n") self.getUrl(url) long = len(cookies) for i in range(long): cookie = {'name': cookies[i]['name'], 'value': cookies[i]['value']} self.driver.add_cookie( cookie) #selenium添加cookies时,得先登录网址才能添加cookies的 self.outPutMyLog("写入cookie的值为:%s" % cookie) self.driver.refresh() # self.outPutMyLog("刷新当前页面---------") self.getUrl(url2) self.outPutMyLog("url2为:%s." % url2) self.driver.refresh() #刷新当前页面 self.outPutMyLog("刷新当前页面---------") self.delayTime(5000) #等待10秒 self.getCookies() #延迟3秒 def delayTime(self, dalaytime): time.sleep(int(dalaytime)) #延迟, self.outPutMyLog("等待%s秒---" % dalaytime) #使用js去掉input框中的readonly(只读)属性,设置为可输入状态,主要处理日期输入 def removeReadonly(self, ele): self.driver.execute_script("arguments[0].removeAttribute('readonly')", ele) # 使用js去掉元素中的readonly属性 self.outPutMyLog("移除input元素中readonly属性,使其可编辑") def setReadonly(self, ele): self.driver.execute_script("arguments[0].setAttribute('readOnly','')", ele) # 使用js去掉元素中的readonly属性 self.outPutMyLog("设置input元素中readonly属性值为true,使其不可编辑") #用js方法输入日期 def jsSetValue(self, ele, value): self.driver.execute_script("arguments[0].value='%s'" % value, ele) # 使用js去掉元素中的readonly属性 self.outPutMyLog("设置input元素中value属性值为%s" % value) self.delayTime(1) #模拟鼠标点击空白处 def mockClickBlank(self, xoffset, yoffset): action = ActionChains(self.driver) action.move_by_offset(xoffset, yoffset).click().perform() #点击空白区域:坐标(0,0) self.outPutMyLog("模拟点击空白区域(点击坐标(%s,%s))" % (xoffset, yoffset)) self.delayTime(1) def createdir(self, filedir): filelist = filedir.split("/") # print(filelist) long = len(filelist) # print(long) zuhefiledir = filelist[0] for i in range(1, long): zuhefiledir = zuhefiledir + "/" + filelist[i] if os.path.exists(zuhefiledir): self.outPutMyLog("已经存在目录:%s" % zuhefiledir) else: os.mkdir(zuhefiledir) self.outPutMyLog("已经创建目录:%s" % zuhefiledir) def clickBack(self): self.driver.back() url = self.getNowPageUrl() self.outPutMyLog("返回到页面URL为:%s的页面" % url) def switchNewWindows(self): window_handles = self.driver.window_handles long = len(window_handles) self.outPutMyLog("目前打开的窗口有%s个。" % long) window_before = self.driver.window_handles[long - 2] print("之前窗口的窗口句柄作为:%s" % window_before) window_after = self.driver.window_handles[long - 1] print("新打开的窗口的窗口句柄作为:%s" % window_after) self.driver.switch_to.window(window_after) # print("当前窗口:%s" % self.driver.current_window_handle) # # handles = self.driver.window_handles # 输出当前所有句柄 # print("所有窗口:%s" % handles) # for handle in handles: # if handle != self.driver.current_window_handle: # print("目前条件:%s" % handle) # self.driver.switch_to.window(handle) self.delayTime(3) print("切换到新窗口") #关闭浏览器 def closeBrowse(self): self.driver.quit()
def __generateTestCases(): from testdatas.models import DeleteAndCheck deleteandchecktestcase_all = DeleteAndCheck.objects.filter(test_project="中石油_迭代一").\ filter(test_module="企业管理").filter(is_run_case=True).order_by('id') for deleteandchecktestcase in deleteandchecktestcase_all: forcount = deleteandchecktestcase.case_counts starttime = GetTimeStr().getTimeStr() if len(str(deleteandchecktestcase.id)) == 1: deleteandchecktestcaseid = '0000%s' % deleteandchecktestcase.id elif len(str(deleteandchecktestcase.id)) == 2: deleteandchecktestcaseid = '000%s' % deleteandchecktestcase.id elif len(str(deleteandchecktestcase.id)) == 3: deleteandchecktestcaseid = '00%s' % deleteandchecktestcase.id elif len(str(deleteandchecktestcase.id)) == 4: deleteandchecktestcaseid = '0%s' % deleteandchecktestcase.id elif len(str(deleteandchecktestcase.id)) == 5: deleteandchecktestcaseid = '%s' % deleteandchecktestcase.id else: deleteandchecktestcaseid = 'Id已经超过5位数,请重新定义' for i in range(1, forcount + 1): # 循环,从1开始 if len(str(i)) == 1: forcount_i = '0000%s' % i elif len(str(i)) == 2: forcount_i = '000%s' % i elif len(str(i)) == 3: forcount_i = '00%s' % i elif len(str(i)) == 4: forcount_i = '0%s' % i elif len(str(i)) == 5: forcount_i = '%s' % i else: forcount_i = 'Id已经超过5位数,请重新定义' args = [] args.append(deleteandchecktestcaseid) # args.append(i) args.append(deleteandchecktestcase.depend_click_case_id) args.append(deleteandchecktestcase.delete_ele_find) args.append(deleteandchecktestcase.delete_ele_find_value) args.append(deleteandchecktestcase.delete_button_find) args.append(deleteandchecktestcase.delete_button_find_value) args.append(deleteandchecktestcase.is_click_cancel) args.append(deleteandchecktestcase.confirm_ele_find) args.append(deleteandchecktestcase.confirm_ele_find_value) args.append(deleteandchecktestcase.click_confirm_delay_time) args.append(deleteandchecktestcase.cancel_ele_find) args.append(deleteandchecktestcase.cancel_ele_find_value) args.append(deleteandchecktestcase.popup_ele_find) args.append(deleteandchecktestcase.popup_ele_find_value) args.append(deleteandchecktestcase.popup_text) args.append(deleteandchecktestcase.is_signel_page) args.append(deleteandchecktestcase.page_number_xpath) args.append(deleteandchecktestcase.result_table_ele_find) args.append(deleteandchecktestcase.result_table_ele_find_value) args.append(deleteandchecktestcase.table_colnum_counts) setattr(TestDeleteClass, 'test_func_%s_%s_%s' % ( deleteandchecktestcaseid, deleteandchecktestcase.test_case_title, forcount_i), TestDeleteClass.getTestFunc(*args)) # 通过setattr自动为TestCase类添加成员方法,方法以“test_func_”开头
def defineAdd_JiGou(self, ): timestr = GetTimeStr().getTimeStr() jigougunaliaddpagefunction.add_JiGOu(self.activebrowser, False, timestr, timestr, timestr)
def runAllTest(self, testproject=None, testmodule=None): if testproject == None: testproject = u"测试项目" else: testproject = testproject if testmodule == None: testmodule = u"测试模块" else: testmodule = testmodule #将用例组件成数组 alltestnames = caselist() suite = unittest.TestSuite() for testpy in alltestnames: try: suite.addTest( unittest.defaultTestLoader.loadTestsFromName( testpy)) #默认加载所有用例 except Exception: print('ERROR: Skipping tests from "%s".' % testpy) try: __import__(test) except ImportError: print('Could not import the "%s" test module.' % testpy) else: print('Could not load the "%s" test suite.' % testpy) from traceback import print_exc print_exc() self.outPutMyLog('Running the tests...') # print('Running the tests...') gettime = GetTimeStr() reporttimestr = gettime.getTimeStr() #获取当前时间 currentny = gettime.getTimeStrNY() #获取当前时间的年月 reportdir = "%s/media/report/%s" % (str( os.path.dirname( os.path.dirname(os.path.dirname( os.path.abspath(__file__))))), currentny) gettime.createdir(reportdir) #创建报告目录 reportname = "report/%s/%s_report.html" % (currentny, reporttimestr) filename = '%s/media/%s' % (str( os.path.dirname( os.path.dirname(os.path.dirname( os.path.abspath(__file__))))), reportname) fp = open(filename, 'wb') self.outPutMyLog('The report path:%s' % filename) # 定义测试报告 runner = HTMLTestRunner.HTMLTestRunner( stream=fp, title=u'%s_%s 自动化测试_测试报告' % (testproject, testmodule), description=u'用例执行情况:', verbosity=2) #verbosity=2,输出测试用例中打印的信息 runresult = runner.run(suite) fp.close() #保存报告到数据库 from reportdatas.models import Report reportrd = Report() # 数据库的对象等于Report,实例化 reportrd.testproject = testproject reportrd.testmodule = testmodule reportrd.reportname = reporttimestr print(reportname) reportrd.reportfile = reportname reportrd.save() from wanwenyc.settings import DJANGO_SERVER_YUMING reportnew = Report.objects.all().order_by('-id')[:1][0] #获取最新报告 reporturl = "%s/media/%s" % (DJANGO_SERVER_YUMING, reportnew.reportfile ) #最新报告访问网址 # 发送report至邮箱 emailtitle = u'%s_%s 自动化测试_测试报告' % (testproject, testmodule) send_e = SendEmail() send_e.run_send(runresult.success_count, runresult.failure_count, runresult.error_count, filename, emailtitle=emailtitle, reporturl=reporturl)
def handlerequestsdatas(self, activeapi, apirequestdataid): timestr = GetTimeStr().getTimeStr() requesturldatas_str = "" requesturldatas_dict = {} from testapidatas.models import RequestUrlDatas requesturldatases = RequestUrlDatas.objects.filter( apirequestdata_id=int(apirequestdataid)) requesturldatases_count = requesturldatases.count() if str(requesturldatases) != "<QuerySet []>": activeapi.outPutMyLog("找到依赖数据") for requesturldatas in requesturldatases: #处理键值对的键 requestheader_dict_key = requesturldatas.request_key #处理键值对的值 if requesturldatas.is_auto_input: if requesturldatas.auto_input_type == '1': requestheader_dict_value = automakestring.getDigits( requesturldatas.auto_input_long) elif requesturldatas.auto_input_type == '2': requestheader_dict_value = automakestring.getAsciiLowercase( requesturldatas.auto_input_long) elif requesturldatas.auto_input_type == '3': requestheader_dict_value = automakestring.getLettersAndDigits( requesturldatas.auto_input_long) elif requesturldatas.auto_input_type == '4': requestheader_dict_value = automakestring.getLetterAndDigitsAndSymbols( requesturldatas.auto_input_long) elif requesturldatas.auto_input_type == '5': requestheader_dict_value = automakestring.getLetterAndDigitsAndSymbolsAndWhitespace( requesturldatas.auto_input_long) elif requesturldatas.auto_input_type == '6': requestheader_dict_value = automakestring.getUnicodeZh( requesturldatas.auto_input_long) else: requestheader_dict_value = u"自动输入字符的类型不正确,请输入正确的自动输入字符的类型" activeapi.outPutErrorMyLog( u"自动输入字符的类型不正确,请输入正确的自动输入字符的类型") else: if requesturldatas.is_with_time: if requesturldatas.request_value == None: requesturldatas_request_value = "" else: requesturldatas_request_value = requesturldatas.request_value requestheader_dict_value = "%s%s" % ( requesturldatas_request_value, timestr) else: if requesturldatas.request_value == None: requesturldatas_request_value = "" else: requesturldatas_request_value = requesturldatas.request_value requestheader_dict_value = requesturldatas_request_value requesturldatas_dict[ requestheader_dict_key] = requestheader_dict_value for key, value in requesturldatas_dict.items(): requesturldatas_str = requesturldatas_str + "%s=%s" % ( key, value) + "&" requesturldatas_str = requesturldatas_str[:-1] #去掉最后一位&内容 print("requesturldatas_str:%s" % requesturldatas_str) else: activeapi.outPutErrorMyLog("没有找到依赖id[%s]对应的数据!" % apirequestdataid) activeapi.outPutMyLog("requesturldatas_dict:%s" % requesturldatas_dict) return requesturldatas_str
def __init__(self): # self.driver = self.getChromeDriver() # self.driver = self.getIeDriver() self.driver = self.getFirefoxDriver() self.timeStr = GetTimeStr() #实例化
if is_cancel: activebrowser.findEleAndClick( 0, "xpath", jigougunaliaddpage.cancel_button_xpath) activebrowser.delayTime(3) else: activebrowser.findEleAndClick( 0, "xpath", jigougunaliaddpage.confirm_button_xpath) activebrowser.delayTime(3) jigouguanlipagefunction.getLastPage(activebrowser) activebrowser.checktable(jigouguanlipage.result_table_xpath, jigoubianma_input_text, 1) activebrowser.checktable(jigouguanlipage.result_table_xpath, jigoumingcheng_input_text, 2) activebrowser.checktable(jigouguanlipage.result_table_xpath, beizhu_input_text, 4) jigougunaliaddpagefunction = JiGouGunaLiAddPageFunction() if __name__ == "__main__": activebrowser = ActiveBrowser() # lpf.loginwithcookies(activebrowser) # activebrowser.getUrl(jigouguanlipage.pageurl) lpf.login(activebrowser) activebrowser.delayTime(10) clickandbackdepend.clickandbackdepend(activebrowser, 10) timestr = GetTimeStr().getTimeStr() jigougunaliaddpagefunction.add_JiGOu(activebrowser, False, timestr, timestr, timestr)
def __generateTestCases(): from testdatas.models import EditAndCheck editandchecktestcase_all = EditAndCheck.objects.filter( test_project__contains="中石油").filter(is_run_case=True).order_by('id') for editandchecktestcase in editandchecktestcase_all: forcount = editandchecktestcase.case_counts starttime = GetTimeStr().getTimeStr() if len(str(editandchecktestcase.id)) == 1: editandchecktestcaseid = '0000%s' % editandchecktestcase.id elif len(str(editandchecktestcase.id)) == 2: editandchecktestcaseid = '000%s' % editandchecktestcase.id elif len(str(editandchecktestcase.id)) == 3: editandchecktestcaseid = '00%s' % editandchecktestcase.id elif len(str(editandchecktestcase.id)) == 4: editandchecktestcaseid = '0%s' % editandchecktestcase.id elif len(str(editandchecktestcase.id)) == 5: editandchecktestcaseid = '%s' % editandchecktestcase.id else: editandchecktestcaseid = 'Id已经超过5位数,请重新定义' for i in range(1, forcount + 1): # 循环,从1开始 if len(str(i)) == 1: forcount_i = '0000%s' % i elif len(str(i)) == 2: forcount_i = '000%s' % i elif len(str(i)) == 3: forcount_i = '00%s' % i elif len(str(i)) == 4: forcount_i = '0%s' % i elif len(str(i)) == 5: forcount_i = '%s' % i else: forcount_i = 'Id已经超过5位数,请重新定义' args = [] args.append(editandchecktestcaseid) # args.append(i) args.append(editandchecktestcase.depend_click_case_id) args.append(editandchecktestcase.edit_ele_find) args.append(editandchecktestcase.edit_ele_find_value) args.append(editandchecktestcase.edit_button_find) args.append(editandchecktestcase.edit_button_find_value) args.append(editandchecktestcase.is_click_cancel) args.append(editandchecktestcase.id) args.append(editandchecktestcase.confirm_ele_find) args.append(editandchecktestcase.confirm_ele_find_value) args.append(editandchecktestcase.click_confirm_delay_time) args.append(editandchecktestcase.cancel_ele_find) args.append(editandchecktestcase.cancel_ele_find_value) args.append(editandchecktestcase.is_submit_success) args.append(editandchecktestcase.is_signel_page) args.append(editandchecktestcase.page_number_xpath) args.append(editandchecktestcase.result_table_ele_find) args.append(editandchecktestcase.result_table_ele_find_value) args.append(editandchecktestcase.table_colnum_counts) setattr( TestEditClass, 'test_func_%s_%s_%s_%s_%s_%s' % (editandchecktestcaseid, editandchecktestcase.test_project, editandchecktestcase.test_module, editandchecktestcase.test_page, editandchecktestcase.test_case_title, forcount_i), TestEditClass.getTestFunc( *args)) # 通过setattr自动为TestCase类添加成员方法,方法以“test_func_”开头