ReadExcel
# -*- coding:utf-8 -*-
from openpyxl import load_workbook
import os
class TestExcel():
def get_TestExcel(self, file_name, sheet_name):
print("======", os.getcwd())
# workbook = load_workbook('Datas.xlsx')#打开表
# sheet = workbook['jack']#定位表单
workbook = load_workbook(file_name) # 打开表
sheet = workbook[sheet_name] # 定位表单
test_data = [] # 把所有行的数据放到列表中
for i in range(2, sheet.max_row + 1):
sub_data = {} # 把每行的数据放到字典中
for j in range(1, sheet.max_column + 1):
sub_data[sheet.cell(1, j).value] = sheet.cell(i, j).value
test_data.append(sub_data) # 拼接每行单元格的数据
return test_data
class WriteExcel():
def write_result(file_name,sheet_name,row,column,result):
workbook = load_workbook(file_name)
sheet = workbook[sheet_name]
sheet.cell(row,column).value = result
workbook.save(file_name)
workbook.close()
return True
if __name__ == "__main__":
te = TestExcel()
txt = te.get_TestExcel("../data/supdatas.xlsx", "staging")
conftest
#encoding=utf-8
# conftest.py
import json
import time
import requests
from py.xml import html
import pytest
def pytest_html_report_title(report):
report.title = "Pro线上 接口测试结果"
# def pytest_configure(config):
# # config._metadata['测试地址'] = "生产环境"
# config._metadata.pop("Platform")
# config._metadata.pop("Plugins")
# config._metadata.pop("Python")
# config._metadata.pop("Packages")
def pytest_html_results_table_header(cells):
cells.insert(1, html.th("Description"))
cells.pop() # 默认删除最后一个列表值
def pytest_html_results_table_row(report, cells):
cells.insert(1, html.td(report.description))
cells.pop()
#它在测试用例执行完毕并生成测试报告时触发,可以在此处对测试结果进行处理,通过实现该钩子函数来对测试报告进行定制化的处理,例如记录测试用例的执行结果、截图等
def pytest_sessionstart(session):
session.results = dict()
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.description = str(item.function.__doc__)
if report.when == 'call':
item.session.results[item] = report
#在测试套件执行结束后调用(也就是pytest进程结束前,会调用此钩子函数,),可以在此钩子函数中执行清理操作或收集报告等
def pytest_sessionfinish(session):
# print('run status code:', exitstatus)
passed_amount = sum(1 for result in session.results.values() if result.passed)
failed_amount = sum(1 for result in session.results.values() if result.failed)
url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=237361a1-3808-4b23-95e4-631d5a06afb0"
nowt = time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime())
data = {"msgtype": "markdown",
"markdown": {
"content": nowt +
"\n> <font color=\"info\">Passed: " + str(passed_amount) + "</font>"
"\n> <font color=\"warning\">Failed: " + str(
failed_amount) + "</font>"
}
}
json_data = json.dumps(data)
headers = {'Content-Type': 'application/json;charset=UTF-8'}
r = requests.post(url, json_data, headers=headers)
# print(r.text)
pytest.ini
# -*- coding: utf-8 -*-
[pytest]
addopts = --html=../report/test_staging.html
console_output_style = classic
junit_suite_name = pytest
junit_logging = no
disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True
Test_api
# -*- coding: utf-8 -*-
import json
import pytest
import requests
import hashlib
import sys
import os
os.environ['PYTHONIOENCODING'] = 'utf-8'
sys.path.append("..")
from common.ReadExcel import TestExcel,WriteExcel
import logging
logger = logging.getLogger(__name__)
xtoken = ""
def setup_module():
domain = ''
url = '%s/api/v1/login' % domain
str = '888888'
md5 = hashlib.md5()
md5.update(str.encode('utf-8'))
str_md5 = md5.hexdigest()
data = {"email": "email", "password": str_md5}
r = requests.post(url, data)
res = json.loads(r.text)
global xtoken
xtoken = res['data']['token']
return xtoken
def http_req(method,url,data,token):
headers = {
'Content-Type':'application/json; charset=utf-8',
'Authorization': xtoken
}
if method == 'post':
resJson = requests.post(url,data,headers=headers)
elif method == 'get':
resJson = requests.get(url,json.loads(data),headers=headers)
elif method == 'delete':
resJson = requests.delete(url,headers=headers)
else:
resJson = requests.get(url,json.loads(data),headers=headers)
res = resJson.text
# logger.add("../logs/file_{time}.log", encoding ="utf - 8")
# logger.info(resp)
return resJson.text
def res_content(res):
if len(res) > 300:
resp = res[0:299]
else:
resp = res
return resp
from openpyxl import load_workbook
def write_result(file_name,sheet_name,row,column,result):
workbook = load_workbook(file_name)
sheet = workbook[sheet_name]
sheet.cell(row,column).value = result
workbook.save(file_name)
workbook.close()
return True
case_data=TestExcel().get_TestExcel("../data/supdatas.xlsx","staging") # pro test test2
idss = [" {} ,地址:{} ".format(data["infor"],data["url"]) for data in case_data]
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
# 确保获取的文本内容已经转为UTF-8编码
docstring = getattr(item.function, '__doc__', '')
report.description = docstring.encode('utf-8').decode('utf-8') # 此处假设docstring原本是正确编码的,此处操作可能多余,仅作示例
@pytest.mark.parametrize("test_data", case_data, ids=idss)
def test_pro_api(test_data):
filename = "../data/supdatas.xlsx"
# filename = data_file
run = test_data["run"]
if run == 1:
method = test_data["method"]
url = test_data["url"]
data = test_data["params"]
expected = test_data["exp"]
row = test_data["row"]
try:
response = http_req(method, url, json.dumps(data).encode('utf-8'), xtoken)
print(res_content(response))
write_result(filename, 'staging', row+1, 8, response)
assert expected in response, '是否存在期望结果:%s ' % expected
except Exception as e:
logger.error(f"Test failed: {e}")
pytest.fail(str(e))
else:
pytest.skip("跳过,不执行")
if __name__ == "__main__":
pytest.main(["Test_stagingApi.py", # 测试用例
"--html=../report/report.html", # 生成测试报告 生成assert存放的css文件和html文件
"--self-contained-html", # 把css样式合并到html里 仅生成html文件
"--capture=sys"
])
标签:sheet,测试报告,企微,用例,pytest,workbook,import,data,name
From: https://www.cnblogs.com/luckyletop/p/18502141