python基础
如果你在写python程序时遇到异常后想进行如下处理的话,一般用try来处理异常,假设有下面的一段程序:

但是你并不知道"语句1至语句N"在执行会出什么样的异常,但你还要做异常处理,且想把出现的异常打印出来,并不停止程序的运行,所以在"except ......"这句应怎样来写呢?
总结了一下3个方法:
方法一:捕获所有异常
try:
a=b b=c except Exception,e: print Exception,":",e
try:
a=b b=c except Exception,e: print Exception,":",e方法二:采用traceback模块查看异常

#引入python中的traceback模块,跟踪错误
import traceback try: a=b b=c except: traceback.print_exc()方法三:采用sys模块回溯最后的异常

#引入sys模块
import sys try: a=b b=c except: info=sys.exc_info() print info[0],":",info[1]但是,如果你还想把这些异常保存到一个日志文件中,来分析这些异常,那么请看下面的方法:
把 traceback.print_exc() 打印在屏幕上的信息保存到一个文本文件中

二、python基础语法
import requests
import random
# python基本数据类型
def test01():
a = int(3)
b = str("hello,world_你好")
c = float(3.1455)
d = {"key1": "values", "key2": "values2"}
e = True
list = [1, 2, 3, 4]
g = ("hello", 100, 3.13)
f = {"A", "B", "C"}
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(list))
print(type(f))
print(type(g))
print(type(f))
# 截取字符串
def test02():
caseInfo = '12312-121312-【新企业】-上海市-特快-舒享型-L1'
case_start = caseInfo.find("【")
print(case_start)
case_end = caseInfo.find('L')
print(case_end)
casename = str(caseInfo[case_start:case_end])
print(casename)
def test03():
year = input("请输入年份:")
year = int(year)
if (year % 400 == 0) or (year % 4 == 0):
print(f"{year} 年是闰年")
else:
print(f"{year} 年不是闰年")
# IF判断
# 枚举值 1= 石头, 2=剪刀, 3= 布
def test04():
user_number = input("请输入1=石头、2=箭头、3=布:")
user_number = int(user_number)
print(f"用户输入的是:{user_number}")
robot_number = int(random.randint(1, 3))
print(f"机器输入的是:{robot_number}")
if (user_number == robot_number):
print("平局了")
elif (user_number == 1 and robot_number == 2) or (user_number == 2 and robot_number == 3) or (
user_number == 3 and robot_number == 1):
print("恭喜你,你胜利了!")
else:
print("对比起,你输了,再试一次")
# 字典
def test05():
d = {"cityName": "上海市", "cityCode": "310100", "hotCity": True, "warnLevel": "A0"}
print(type(d))
print(d)
print(d.get("cityName")) # 查找某个元素
print(d["cityName"]) # 查找某个元素
d["people"] = 33 # 字典新增某个元素
d.update({"aa", "25"}) # 新增字典元素
print(d.pop("warnLevel")); # 删除字典某个元素
print(d.keys()) # 获取字典所有key
print(d.values()) # 获取字典所有values
print(d.clear()) # 清空字典元素
# 字典取值-判断字典的vlues值是否为空,判断字典长度
def test06():
dic = {"cityName": "上海市", "cityCode": "310100", "hotCity": True, "warnLevel": "A0"}
dic2 = {"cityName": "上海市", "cityCode": "310100", "hotCity": True, "warnLevel": "A0"}
if dic['warnLevel'].__len__() > 0:
result = dic["warnLevel"]
else:
result = "无"
print(result)
# 字典取值-判断指定key是否包含再字典中
def test07():
dic2 = {"cityName": "上海市", "cityCode": "", "hotCity": True, "warnLevel": "A0"}
if dic2['cityCode'].__len__() > 0:
show = dic2['cityCode']
elif "cityName" in dic2:
show = "有"
else:
show = "无"
print(show)
#for 循环打印指定key是否再字典中
def test08():
dic = {"cityName": "上海市", "cityCode": "310100", "hotCity": True, "warnLevel": "A0"}
for i in dic:
print(i)
for key in dic.keys():
print(key)
for values in dic.values():
print(values)
for allJosn in dic.items():
print(allJosn)
switch = list(dic.items())
print(switch)
#字典转list
def test10():
dic = {"cityName": "上海市", "cityCode": "310100", "hotCity": True, "warnLevel": "A0"}
switch2 = str(dic)
print(switch2)
# 列表list[]
# list_a = ['北京', '上海', '武汉', '广州', '深圳', '北京', '杭州']
# print(list_a)
# #列表末尾添加元素
# list_a.append("锦州")
# print(list_a)
# #移除列表元素,元素下标
# list_a.pop(1)
# print(list_a)
# a = list_a.count('北京')
# print(a)
#清空列表
# list_a.clear()
# print(list_a)
# list_b = [1,2,3]
# list_b.remove(1)
# print(list_b)
list_c = ['北京', '武汉', '广州', '深圳', '北京', '杭州', '锦州']
list_c.index('武汉')
print(list_c)
# list_C.insert("福州")
# for i in list_c:
# print(i)
# if i =='北京':
# print(1)
# else:
# print(0)
if __name__ == '__main__': test10()
三、Python对JIRA- API 处理
# coding:utf-8 import requests import pandas as pd def auto_importJIRA(): url = "http://jira.xx.com:8080/rest/raven/2.0/api/dataset/import" headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } def create_issue(summary, assigneeName, reporterName): url = "http://jira.xx.com:8080/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": summary, "description": "test测试用例", "assignee": { "name": assigneeName, }, "reporter": { "name": reporterName }, "issuetype": { "name": "测试用例" } } } headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } result = requests.post(url=url, json=data, headers=headers) print(result.status_code) testcase_issue = result.json() testcase_issue_key = testcase_issue['key'] print(testcase_issue_key) update_testcase_issue_status(testcase_issue_key) def readExcel_testcaseNme(): df = pd.read_csv(r"D:\testCase\xx.csv") # 读取excel数据 data_list = df.to_dict(orient='records') print(data_list) testcase_name = [] for testcase in data_list: testcase_name.append(testcase['概要']) print(testcase_name) return testcase_name def while_create_issue(): for i in range(0, 2): create_issue(readExcel_testcaseNme()[i], "xx", "xx"); def update_testcase_issue_status(testcase_issue_key): testcase_issue_key = str(testcase_issue_key) url = "http://jira.xx.com:8080/rest/api/2/issue/" + testcase_issue_key + "/transitions"; headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } testcaseBody = { "transition": { "id": 11 } } result = requests.post(url=url, json=testcaseBody, headers=headers) print(result.status_code) print("评审通过") if __name__ == '__main__': # create_issue("test测试用例", "xx", "xx") while_create_issue() update_testcase_issue_status("ORIDE-xx")
关闭JIRA的API
# coding:utf-8 from jira import JIRA import requests import pandas as pd def auto_serchJIRA(): jira = JIRA('http://jira.xx.com:8080', basic_auth=('xx', 'xx')) print("jira") query_sql = 'project = NKHFK AND issuetype = 事件 AND status = Closed AND labels = xx AND created >= 2022-06-16 AND created <= 2022-12-31 ORDER BY created DESC' query_info = jira.search_issues(query_sql, maxResults=50) print(query_info) print(type(query_info)) for i in query_info: key_name = i.key issue = jira.issue(key_name) # 根据编号获得issue对象 print(f" 筛选查询到数结果{issue}") def readExcel_testcaseNme(): df = pd.read_csv(r"D:\testCase\newKFKF.csv") # 读取excel数据 data_list = df.to_dict(orient='records') print(data_list) print(type(data_list)) testcase_name = [] for testcase in data_list: print(testcase) testcase_name.append(testcase['问题关键字']) #print(testcase_name) return testcase_name def auto_closeJIRA_center(strJIRAkey): url = "http://jira.xx.com:8080/rest/api/2/issue/" + strJIRAkey + "/transitions" print(url) headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } # dicbody = {"transition": {"id": 311, "name": "修改责任问题根因分类", "customfield_21966": {"id": "28240", "value": "xx"}}} jsonbody = { "transition": { "id": 311, "name": "修改责任问题根因分类", "customfield_21966": { "id": "28240", "value": "成本中心" } }, "fields": { "customfield_21966": { "id": "28240", "value": "成本中心" } } } result = requests.post(url=url, json=jsonbody, headers=headers) print(result.status_code) print(result.text) print(result.content) def while_closeJIRA_center(): for i in range(0, 47): auto_closeJIRA_center(readExcel_testcaseNme()[i]); print(readExcel_testcaseNme()[i]) if __name__ == '__main__': #auto_serchJIRA() #auto_closeJIRA_center("xx-xx") while_closeJIRA_center()
# coding:utf-8 import requests import pandas as pd planBody = ["ORIDE-249775", "ORIDE-249717"] def create_testcseList(userName): url = "http://jira.xx.com:8080/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": "api测试套件", # "components": [{"name": "web相关"}], "description": "test测试套件", "assignee": { "name": userName, }, "reporter": { "name": userName }, "issuetype": { "name": "测试套件" } } } headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } result = requests.post(url=url, json=data, headers=headers) print(result.status_code) testcase_list = result.json() print(testcase_list) testcaselist_key = testcase_list['key'] return testcaselist_key def create_testcsePaln(summary, userName, caseType): url = "http://jira.xx.com:8080/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": summary, # "components": [{"name": "web相关"}], "description": "test测试计划", "assignee": { "name": userName, }, "issuetype": { "name": caseType } } } headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } result = requests.post(url=url, json=data, headers=headers) print(result.status_code) testcasePlan = result.json() print(testcasePlan) testcasePlan_key = testcasePlan['key'] return testcasePlan_key def create_testcse_execute(summary, userName): url = "http://jira.xx.com:8080/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": summary, # "components": [{"name": "web相关"}], "description": "test测试执行", "assignee": { "name": userName, }, "issuetype": { "name": "测试执行" } } } headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } result = requests.post(url=url, json=data, headers=headers) print(result.status_code) testcaseExecute = result.json() print(testcaseExecute) testcaseExecute_key = testcaseExecute['key'] return testcaseExecute_key def create_issue(summary, userName, moudleName): url = "http://jira.xx.com:8080/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": summary, "components": [{"name": moudleName}], "description": "test测试用例", "assignee": { "name": userName, }, "reporter": { "name": userName }, "issuetype": { "name": "测试用例" } } } headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } result = requests.post(url=url, json=data, headers=headers) print(result.status_code) testcase_issue = result.json() testcase_issue_key = testcase_issue['key'] print(testcase_issue_key) update_testcase_issue_status(testcase_issue_key) return testcase_issue_key def create_step(testcase_id, caseStep, caseData, caseExcepctResult): step_data = {"step": caseStep, "data": caseData, "result": caseExcepctResult} create_step_url = 'http://jira.xx.com:8080/rest/raven/2.0/api/test/' + testcase_id + '/step' print(create_step_url) headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } result = requests.put(url=create_step_url, json=step_data, headers=headers) print(result.status_code) print(result) def getLine_num(): filename = r"./智慧屏优化.csv" total = sum(1 for line in open(filename, encoding='gb18030', errors='ignore')) total = total - 1 return total def while_create_issue(userName): filename = r"./智慧屏优化.csv" # filename = inputfilename total = sum(1 for line in open(filename, encoding='gb18030', errors='ignore')) totalLine = total - 1 df = pd.read_csv(filename) # 读取excel数据 data_list = df.to_dict(orient='records') print(data_list) moudle_Name = [] testcase_name = [] step_name = [] data_name = [] expectResult_name = [] s = -1 for i in data_list: moudle_Name.append(i['模块']) testcase_name.append(i['概要']) step_name.append(i['操作步骤']) data_name.append(i['预置条件']) expectResult_name.append(i['预期结果']) print(moudle_Name, testcase_name) case_list = [] for i in range(totalLine): s = s + 1 case_list.append(create_issue(testcase_name[s], userName, moudle_Name[s])) print(case_list) add_testcasekey_to_testList(create_testcseList("xx"), case_list) # create_step(create_issue(testcase_name[s], userName, moudle_Name[s]), step_name[s], data_name[s],expectResult_name[s]) def update_testcase_issue_status(testcase_issue_key): testcase_issue_key = str(testcase_issue_key) url = "http://jira.xx.com:8080/rest/api/2/issue/" + testcase_issue_key + "/transitions"; headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } testcaseBody = { "transition": { "id": 11 } } result = requests.post(url=url, json=testcaseBody, headers=headers) print(result.status_code) print("评审通过") def add_testcasekey_to_testList(testcaselist_key, searchkeyList): url = "http://jira.xx.com:8080/rest/raven/1.0/testset/" + testcaselist_key + "/tests" headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } planBody = searchkeyList result = requests.post(url=url, json=planBody, headers=headers) print(result.status_code) if __name__ == '__main__': # create_issue("test测试用例", "xx", "xx") # create_testcseList("test测试套件", "xx") # create_testcsePaln("test测试计划", 'xx', "测试计划") # create_testcse_execute("test测试执行", 'xx') while_create_issue('xx') # create_step('721111', '11', '11', '11') # add_testcasekey_to_testList() #add_testcasekey_to_testList(create_testcseList("xx"), planBody)
# coding:utf-8 import requests import pandas as pd import time from jira import JIRA headers = { "Authorization": "Basic xx", "X-Atlassian-Token": "nocheck", "Content-Type": "application/json" } JaraURL = "http://jira.xx.com:8080" class JiraSprint: def __init__(self, userName, psd): self.jira = JIRA(auth=(userName, psd), options={'server': JaraURL}) self.cookies = self.jira._session.cookies # 获取登录的cookie print(self.cookies) self.headers2 = { "Accept": "application/json", } def create_testcseList(userName): url = "" + JaraURL + "/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": "api测试套件", # "components": [{"name": "web相关"}], "description": "test测试套件", "assignee": { "name": userName, }, "reporter": { "name": userName }, "issuetype": { "name": "测试套件" } } } result = requests.post(url=url, json=data, headers=headers) print(result.status_code) testcase_list = result.json() testcaselist_key = testcase_list['key'] return testcaselist_key def create_testcsePaln(userName): url = "" + JaraURL + "/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": "api测试计划", # "components": [{"name": "web相关"}], "description": "test测试计划", "assignee": { "name": userName, }, "issuetype": { "name": "测试计划" } } } result = requests.post(url=url, json=data, headers=headers) print(result.status_code) testcasePlan = result.json() testcasePlan_key = testcasePlan['key'] return testcasePlan_key def create_currentUser_testcsePaln(self, userName): url = "" + JaraURL + "/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": "api测试计划", # "components": [{"name": "web相关"}], "description": "test测试计划", "assignee": { "name": userName, }, "issuetype": { "name": "测试计划" } } } result = requests.post(url=url, json=data, headers=self.headers2, cookies=self.cookies) print(result.status_code) testcasePlan = result.json() testcasePlan_key = testcasePlan['key'] return testcasePlan_key def create_testcse_execute(userName): url = "" + JaraURL + "/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": "API测试执行", # "components": [{"name": "web相关"}], "description": "test测试执行", "assignee": { "name": userName, }, "issuetype": { "name": "测试执行" } } } result = requests.post(url=url, json=data, headers=headers) testcaseExecute = result.json() print(testcaseExecute) testcaseExecute_key = testcaseExecute['key'] return testcaseExecute_key def create_currentUser_testcse_execute(self, userName): url = "" + JaraURL + "/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": "API测试执行", # "components": [{"name": "web相关"}], "description": "test测试执行", "assignee": { "name": userName, }, "issuetype": { "name": "测试执行" } } } result = requests.post(url=url, json=data, headers=self.headers2, cookies=self.cookies) testcaseExecute = result.json() print(testcaseExecute) testcaseExecute_key = testcaseExecute['key'] return testcaseExecute_key def create_issue(summary, userName, moudleName): url = "" + JaraURL + "/rest/api/2/issue/" data = { "fields": { "project": { "key": "ORIDE" }, "summary": summary, "components": [{"name": moudleName}], "description": "test测试用例", "assignee": { "name": userName, }, "reporter": { "name": userName }, "issuetype": { "name": "测试用例" } } } result = requests.post(url=url, json=data, headers=headers) print(result.status_code) testcase_issue = result.json() testcase_issue_key = testcase_issue['key'] print(testcase_issue_key) update_testcase_issue_status(testcase_issue_key) return testcase_issue_key def while_create_issue(userName, inputfilename): filename = r"./" + inputfilename + ".csv" # filename = r"./智慧屏优化.csv" total = sum(1 for line in open(filename, encoding='gb18030', errors='ignore')) totalLine = total - 1 df = pd.read_csv(filename) # 读取excel数据 data_list = df.to_dict(orient='records') print(data_list) moudle_Name = [] testcase_name = [] step_name = [] data_name = [] expectResult_name = [] s = -1 for i in data_list: moudle_Name.append(i['模块']) testcase_name.append(i['概要']) step_name.append(i['操作步骤']) data_name.append(i['预置条件']) expectResult_name.append(i['预期结果']) print(moudle_Name, testcase_name) case_list = [] for i in range(totalLine): s = s + 1 case_list.append(create_issue(testcase_name[s], userName, moudle_Name[s])) time.sleep(1) create_step(self, case_list[s], step_name[s], data_name[s], expectResult_name[s]) time.sleep(1) testcaselist_key = create_testcseList(userName) testcaseExecute_key = create_currentUser_testcse_execute(self, userName) testcasePlan_key = create_currentUser_testcsePaln(self, userName) add_testcasekey_to_testList(testcaselist_key, case_list) time.sleep(3) add_testcaselist_to_testExecute(testcaseExecute_key, testcaselist_key) time.sleep(3) add_testExecute_to_testplan(testcasePlan_key, testcaseExecute_key) time.sleep(3) def update_testcase_issue_status(testcase_issue_key): testcase_issue_key = str(testcase_issue_key) url = "http://jira.xx.com:8080/rest/api/2/issue/" + testcase_issue_key + "/transitions"; testcaseBody = { "transition": { "id": 11 } } requests.post(url=url, json=testcaseBody, headers=headers) print("评审通过") def add_testcasekey_to_testList(testcaselist_key, searchkeyList): url = "http://jira.xx.com:8080/rest/raven/1.0/testset/" + testcaselist_key + "/tests" planBody = searchkeyList result = requests.post(url=url, json=planBody, headers=headers) print(result.status_code) def add_testcaselist_to_testExecute(testcaseExecute_key, testcaselist_key): url = "http://jira.xx.com:8080/rest/raven/1.0/testexec/" + testcaseExecute_key + "/test" exeBody = {"keys": [testcaselist_key]} result = requests.post(url=url, json=exeBody, headers=headers) print(result.status_code) print(result.json()) def add_testExecute_to_testplan(testcasePlan_key, testcaseExecute_key): url = "http://jira.xx.com:8080/rest/raven/1.0/testplan/" + testcasePlan_key + "/testexec" exeBody = {"keys": [testcaseExecute_key]} result = requests.post(url=url, json=exeBody, headers=headers) print(result.status_code) print(result.json()) def create_step(self, testcase_id, caseStep, caseData, caseExcepctResult): step_data = {"step": caseStep, "data": caseData, "result": caseExcepctResult} url = 'http:/xx/rest/raven/1.0/api/test/' + testcase_id + '/step' print(url) result = requests.put(url=url, json=step_data, headers=self.headers2, cookies=self.cookies) print(result.status_code) print(result.json()) if __name__ == '__main__': userName = input('请输入域账号:\n') psd = input('请输入域账号密码:\n') inputfilename = input('请输入csv文件名:\n') self = JiraSprint(userName, psd) while_create_issue(userName, inputfilename)

浙公网安备 33010602011771号