自动化测试目录结构

编写自动化测试脚本时,根据项目的需要,设计不同的目录结构,以下仅供参考和记录:
image.png

1、common目录,存放一些基本的方法供调用:
Get_New_Report.py获取Report目录下最新的测试报告

import os

def new_report():
    reportmenu='D:\PycharmProjects\Ambulance_Api\Report'
    lists=os.listdir(reportmenu)
    lists.sort(key=lambda fn: os.path.getmtime(reportmenu+'\\'+fn))
    file_new=os.path.join(reportmenu,lists[-1])
    return file_new

LogGen.py日志方法的封装

import logging
import os
import time

class LogGen():
    def __init__(self,logger):
        self.logger=logging.getLogger(logger)
        self.logger.setLevel(logging.INFO)

        #存放路径
        lt=time.strftime('%Y%m%d%H%M',time.localtime(time.time()))
        logname=os.path.dirname(os.path.abspath('.'))+'\\logs\\'+lt+'.log'
        file=logging.FileHandler(logname)
        file.setLevel(logging.INFO)

        #终端打印
        consoleh=logging.StreamHandler()
        consoleh.setLevel(logging.INFO)

        #写入数据,设置格式
        formatter=logging.Formatter('%(asctime)s-%(levelname)s-%(lineno)s-%(message)s')
        file.setFormatter(formatter)
        consoleh.setFormatter(formatter)
        self.logger.addHandler(file)
        self.logger.addHandler(consoleh)
    def getlog(self):
        return self.logger

read_data.py读取测试用例里面的数据

import xlrd

list=[]
def read_excle():
    work=xlrd.open_workbook(r'D:\PycharmProjects\Ambulance_Api\TestCase\test.xls')
    sheet=work.sheet_by_index(0)
    rows=sheet.nrows     #获取一共有多少行,第一行为所以列,不能参与用例执行
    for r in range(1,rows):    #从第二行开始读取
        url='https://mbd.baidu.com/'+sheet.cell(r,1).value     #拼接完整的url
        list.append(url)
    return list

run.py执行测试用例,读取excel里的数据发送请求,并将结果写入excel对应字段

import xlrd
from xlutils.copy import copy
import time,requests
from common.read_data import read_excle
from common.LogGen import LogGen


logger=LogGen(logger='开始读取测试用例...').getlog()
filename=r'D:\PycharmProjects\Ambulance_Api\TestCase\test.xls'
logger.info('打开测试用例')
book=xlrd.open_workbook(filename,'rb')
sheet=book.sheet_by_index(0)
logger.info('复制并写入')
wb=copy(book)
url=read_excle()
count=1
for i in url:
    response=requests.get(i)
    if response.status_code==200:
        logger.info('写入200成功用例')
        wb.get_sheet(0).write(count,0,response.status_code)
        count+=1
    else:
        logger.info('写入失败用例标识')
        wb.get_sheet(0).write(count,0,'未通过')
        count+=1
wb.save(filename)

2、config配置文件,主要存放一些数据库等登录信息

[browser]
BrowserName=chrome
url=https://www.baidu.com/

3、logs目录,存放日志信息
4、mail目录,封装发送邮件的方法
Mail_module.py封装发送邮件的方法

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from smtplib import SMTP_SSL
from common.LogGen import LogGen

logger=LogGen(logger='开始发送邮件...').getlog()
def send_mail(fromuser,pwd,touser,filepath):
    #创建一个带附件的实例
    msg=MIMEMultipart()

    msg['Subject']=('第一轮测试结果')
    msg['From']=fromuser

    receivers=touser    #被调用时,receivers为列表
    # 判断收件人列表【】是否长度大于一,如果大于,就是群发
    if len(receivers)>1:
        msg['To']=','.join(receivers)    #群发
    else:
        msg['To']=receivers[0]

    smtp_server = 'smtp.sina.cn'
    msg.attach(MIMEText('小二自动化测试报告', 'plain', 'utf-8'))

    #添加附件部分
    for path in filepath:
        logger.info('--开始添加所有附件--')
        jpg_name=path.split('\\')[-1]
        jpgpart=MIMEApplication(open(path,'rb').read())
        jpgpart.add_header('Content-Disposition', 'attachment', filename=jpg_name)
        msg.attach(jpgpart)
        logger.info('附件添加完毕')

    try:
        server=smtplib.SMTP_SSL(smtp_server,timeout=30)
        print('开始登录,开启debug调试')
        server.set_debuglevel(0)
        server.ehlo(smtp_server)
        server.login(fromuser,pwd)
        print('登录成功!开始发送邮件......')
        server.sendmail(fromuser,touser,msg.as_string())
        server.quit()
        print('邮件发送成功~!')
    except Exception as e:
        print(str(e))

sendmail.py封装检测报告中是否有失败的用例,如果有,就调用Mail_module.py发送邮件

from bs4 import BeautifulSoup
from mail.Mail_module import send_mail
from common.Get_New_Report import new_report

def is_result_pass(newreport):
    try:
        with open(newreport,'rb') as fp:
            f=fp.read()
        soup=BeautifulSoup(f,'html.parser')
        status=soup.find_all(class_="attribute")
        result=status[2].contents[-1]
        if 'Error' in result or 'Failure' in result:
            print('测试用例有不通过的:%s' %result)
            return False
        else:
            return True

    except Exception as msg:
        print('判断过程出现异常:%s' %str(msg))
        return False


if __name__ == '__main__':
    newreport = new_report()
    res = is_result_pass(newreport)
    if not res:     #if not 只用于确定not后面的为false,none或者空,才执行冒号后面的
        fromuser = input('请输入登录邮箱:')
        pwd = input('请输入邮箱密码:')
        touser = ['[email protected]','[email protected]']
        filepath = ['D:\\xxxxxxxx.html','E:\\照片\\1.jpg']
        send_mail(fromuser,pwd,touser,filepath)
    else:
        print('恭喜你!--测试用例全部通过,不发送邮件~!')

5、Report存放每次执行后的测试报告文件,供sendmail.py解析和发送
6、TestCase目录存放测试用例目录

你可能感兴趣的:(自动化测试目录结构)