Python+unittest+requests+excel 인터페이스 자동화 테스트 프레임 워 크 실현
Excel 관리 테스트 용례,HTML TestRunner 생 성 테스트 보고서테스트 완료 후 메 일 로 테스트 보고 서 를 발송 합 니 다
프로젝트 전체 구조:
common 모듈 코드
class IsInstance:
def get_instance(self, value, check):
flag = None
if isinstance(value, str):
if check == value:
flag = True
else:
flag = False
elif isinstance(value, float):
if value - float(check) == 0:
flag = True
else:
flag = False
elif isinstance(value, int):
if value - int(check) == 0:
flag = True
else:
flag = False
return flag
# logger.py
import logging
import time
import os
class MyLogging:
def __init__(self):
timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../logs'))
filename = lib_path + '/' + timestr + '.log' #
self.logger = logging.getLogger() # name, root
self.logger.setLevel(logging.INFO) # , , warning
sh = logging.StreamHandler() #
sh.setLevel(logging.INFO) #
fh = logging.FileHandler(filename=filename) # filename
fh.setLevel(logging.INFO) #
#
formatter = logging.Formatter(
"%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s - %(message)s") #
# handler
sh.setFormatter(formatter)
fh.setFormatter(formatter)
# handler logger
self.logger.addHandler(sh)
self.logger.addHandler(fh)
if __name__ == "__main__":
log = MyLogging().logger
log.debug("debug")
log.info("info")
log.warning("warning")
log.error("error")
log.critical("critical")
# operate_excel.py
import xlrd
from xlrd import xldate_as_tuple
import openpyxl
import datetime
class ExcelData():
def __init__(self, file_path, sheet_name):
self.file_path = file_path
self.sheet_name = sheet_name
self.workbook = xlrd.open_workbook(self.file_path)
#
self.table = self.workbook.sheet_by_name(self.sheet_name)
#
self.keys = self.table.row_values(0)
#
self.rowNum = self.table.nrows
#
self.colNum = self.table.ncols
def readExcel(self):
datas = []
for i in range(1, self.rowNum):
sheet_data = []
for j in range(self.colNum):
#
c_type = self.table.cell(i, j).ctype
#
c_cell = self.table.cell_value(i, j)
if c_type == 2 and c_cell % 1 == 0:
c_cell = int(c_cell)
elif c_type == 3:
date = datetime.datetime(*xldate_as_tuple(c_cell, 0))
c_cell = date.strftime('%Y/%d/%m %H:%M:%S')
elif c_type == 4:
c_cell = True if c_cell == 1 else False
# sheet_data[self.keys[j]] = c_cell #
sheet_data.append(c_cell)
datas.append(sheet_data)
return datas
def write(self, rowNum, colNum, result):
workbook = openpyxl.load_workbook(self.file_path)
table = workbook.get_sheet_by_name(self.sheet_name)
table = workbook.active
# rows = table.max_row
# cols = table.max_column
# values = ['E','X','C','E','L']
# for value in values:
# table.cell(rows + 1, 1).value = value
# rows = rows + 1
#
table.cell(rowNum, colNum, result)
workbook.save(self.file_path)
if __name__ == '__main__':
file_path = "D:\python_data\ .xlsx"
sheet_name = " "
data = ExcelData(file_path, sheet_name)
datas = data.readExcel()
print(datas)
print(type(datas))
for i in datas:
print(i)
# data.write(2,12," ")
# send_email.py
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.text import MIMEText
from config import read_email_config
import smtplib
def send_email(subject, mail_body, file_names=list()):
#
smtp_server = read_email_config.smtp_server
port = read_email_config.port
user_name = read_email_config.user_name
password = read_email_config.password
sender = read_email_config.sender
receiver = read_email_config.receiver
#
msg = MIMEMultipart()
body = MIMEText(mail_body, _subtype="html", _charset="utf-8")
msg["Subject"] = Header(subject, "utf-8")
msg["From"] = user_name
msg["To"] = receiver
msg.attach(body)
# :
for file_name in file_names:
att = MIMEText(open(file_name, "rb").read(), "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] = "attachment;filename='%s'" % (file_name)
msg.attach(att)
#
try:
smtp = smtplib.SMTP()
smtp.connect(smtp_server)
smtp.login(user_name, password)
smtp.sendmail(sender, receiver.split(','), msg.as_string())
except Exception as e:
print(e)
print(" !")
else:
print(" !")
finally:
smtp.quit()
if __name__ == '__main__':
subject = " "
mail_body = " "
receiver = "[email protected],[email protected]" #
file_names = [r'D:\PycharmProjects\AutoTest\result\2020-02-23 13_38_41report.html']
send_email(subject, mail_body, receiver, file_names)
# send_request.py
import requests
import json
class RunMethod:
# post
def do_post(self, url, data, headers=None):
res = None
if headers != None:
res = requests.post(url=url, json=data, headers=headers)
else:
res = requests.post(url=url, json=data)
return res.json()
# get
def do_get(self, url, data=None, headers=None):
res = None
if headers != None:
res = requests.get(url=url, data=data, headers=headers)
else:
res = requests.get(url=url, data=data)
return res.json()
def run_method(self, method, url, data=None, headers=None):
res = None
if method == "POST" or method == "post":
res = self.do_post(url, data, headers)
else:
res = self.do_get(url, data, headers)
return res
config 모듈
# coding:utf-8
#
[mysqlconf]
host = 127.0.0.1
port = 3306
user = root
password = root
db = test
# coding:utf-8
#
# email_config.ini
[email]
smtp_server = smtp.qq.com
port = 465
sender = 780***[email protected]
password = hrpk******baf
user_name = 780***[email protected]
receiver = 780***[email protected],h***[email protected]
# coding:utf-8
from pymysql import connect, cursors
from pymysql.err import OperationalError
import os
import configparser
# read_db_config.py
# DB
# os.path.realpath(__file__):
# os.path.dirname(): ()
cur_path = os.path.dirname(os.path.realpath(__file__))
configPath = os.path.join(cur_path, "db_config.ini") # :/config/db_config.ini
conf = configparser.ConfigParser()
conf.read(configPath, encoding="UTF-8")
host = conf.get("mysqlconf", "host")
port = conf.get("mysqlconf", "port ")
user = conf.get("mysqlconf", "user")
password = conf.get("mysqlconf", "password")
port = conf.get("mysqlconf", "port")
# coding:utf-8
import os
import configparser
#
# os.path.realpath(__file__):
# os.path.dirname(): ()
# read_email_config.py
cur_path = os.path.dirname(os.path.realpath(__file__)) #
configPath = os.path.join(cur_path, "email_config.ini") # :/config/email_config.ini
conf = configparser.ConfigParser()
conf.read(configPath, encoding='UTF-8') # /config/email_config.ini
# get(section,option) section option , string
smtp_server = conf.get("email", "smtp_server")
sender = conf.get("email", "sender")
user_name = conf.get("email","user_name")
password = conf.get("email", "password")
receiver = conf.get("email", "receiver")
port = conf.get("email", "port")
testcase 모듈
# test_case.py
from common.operate_excel import *
import unittest
from parameterized import parameterized
from common.send_request import RunMethod
import json
from common.logger import MyLogging
import jsonpath
from common.is_instance import IsInstance
from HTMLTestRunner import HTMLTestRunner
import os
import time
lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../data"))
file_path = lib_path + "/" + " .xlsx" # excel
sheet_name = " "
log = MyLogging().logger
def getExcelData():
list = ExcelData(file_path, sheet_name).readExcel()
return list
class TestCase(unittest.TestCase):
@parameterized.expand(getExcelData())
def test_api(self, rowNumber, caseRowNumber, testCaseName, priority, apiName, url, method, parmsType, data,
checkPoint, isRun, result):
if isRun == "Y" or isRun == "y":
log.info("【 :{}】".format(testCaseName))
headers = {"Content-Type": "application/json"}
data = json.loads(data) # json
c = checkPoint.split(",")
log.info(" :%s" % c)
print(" :%s" % c)
log.info(" url:%s" % url)
log.info(" :%s" % data)
r = RunMethod()
res = r.run_method(method, url, data, headers)
log.info(" :%s" % res)
flag = None
for i in range(0, len(c)):
checkPoint_dict = {}
checkPoint_dict[c[i].split('=')[0]] = c[i].split('=')[1]
# jsonpath
list = jsonpath.jsonpath(res, c[i].split('=')[0])
value = list[0]
check = checkPoint_dict[c[i].split('=')[0]]
log.info(" {}:{}, :{}".format(i + 1, check, value))
print(" {}:{}, :{}".format(i + 1, check, value))
#
flag = IsInstance().get_instance(value, check)
if flag:
log.info("【 : 】")
ExcelData(file_path, sheet_name).write(rowNumber + 1, 12, "Pass")
else:
log.info("【 : 】")
ExcelData(file_path, sheet_name).write(rowNumber + 1, 12, "Fail")
#
self.assertTrue(flag, msg=" ")
else:
unittest.skip(" ")
if __name__ == '__main__':
# unittest.main()
# Alt+Shift+f10
# 1
suite = unittest.TestSuite()
suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestCase))
now = time.strftime('%Y-%m-%d %H_%M_%S')
report_path = r"D:\PycharmProjects\AutoTest\result\report.html"
with open(report_path, "wb") as f:
runner = HTMLTestRunner(stream=f, title="Esearch ", description=" ", verbosity=2)
runner.run(suite)
실행 파일
import os
import time
import unittest
from HTMLTestRunner import HTMLTestRunner
from common.send_email import send_email
# run_case.py
# py
cur_path = os.path.dirname(os.path.realpath(__file__))
# 1:
def all_test():
case_path = os.path.join(cur_path, "testcase")
suite = unittest.TestLoader().discover(start_dir=case_path, pattern="test_*.py", top_level_dir=None)
return suite
# 2:
def run():
now = time.strftime("%Y_%m_%d_%H_%M_%S")
#
file_name = os.path.join(cur_path, "report") + "/" + now + "-report.html"
f = open(file_name, "wb")
runner = HTMLTestRunner(stream=f, title=" ",
description=" :windows 10 :chrome",
tester="wangzhijun")
runner.run(all_test())
f.close()
# 3:
def get_report(report_path):
list = os.listdir(report_path)
list.sort(key=lambda x: os.path.getmtime(os.path.join(report_path, x)))
print(" :", list[-1])
report_file = os.path.join(report_path, list[-1])
return report_file
# 4:
def send_mail(subject, report_file, file_names):
# ,
with open(report_file, "rb") as f:
mail_body = f.read()
send_email(subject, mail_body, file_names)
if __name__ == "__main__":
run()
report_path = os.path.join(cur_path, "report") #
report_file = get_report(report_path) #
subject = "Esearch " #
file_names = [report_file] #
#
send_mail(subject, report_file, file_names)
data:report:
logs:
파 이 썬+unittest+requests+excel 인터페이스 자동화 테스트 프레임 워 크 실현 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 파 이 썬 인터페이스 자동화 테스트 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 부탁드립니다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Python의 None과 NULL의 차이점 상세 정보그래서 대상 = 속성 + 방법 (사실 방법도 하나의 속성, 데이터 속성과 구별되는 호출 가능한 속성 같은 속성과 방법을 가진 대상을 클래스, 즉 Classl로 분류할 수 있다.클래스는 하나의 청사진과 같아서 하나의 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.