Exemplo n.º 1
0
 def setUp(self):
     self.methon = WebMethon()
     self.config = Config()
     self.excel = OperationExcel()
     self.pm = PublicMethod()
     self.operationJson = OperationJson()
     self.iscontent = IsContent()
Exemplo n.º 2
0
class OperationExcel:
    def __init__(self):
        self.pm = PublicMethod()
        self.ex = ExcelVaribles()

    def getExcel(self):
        '''打开要操作的文件'''
        db = xlrd.open_workbook(self.pm.data_dir('data', 'data.xls'))
        '''找到要操作的第几个sheet,索引从0开始'''
        sheet = db.sheet_by_index(0)
        return sheet

    def get_rows(self):
        '''获取excel的行数'''
        return self.getExcel().nrows

    def get_row_cel(self, row, col):
        '''获取单元格的内容'''
        return self.getExcel().cell_value(row, col)

    def get_CaseID(self, row):
        '''获取用例ID'''
        return self.get_row_cel(row, self.ex.getCaseID())

    def get_Url(self, row):
        '''获取请求地址'''
        return self.get_row_cel(row, self.ex.getUrl())

    def get_CasePre(self, row):
        #获取前置条件
        return self.get_row_cel(row, self.ex.getCasePre())

    def get_Method(self, row):
        #获取请求方法
        return self.get_row_cel(row, self.ex.getMethod())

    def get_ParamsType(self, row):
        #获取请求参数类型
        return self.get_row_cel(row, self.ex.getParamsType())

    def get_Referer(self, row):
        #获取请求引用链接
        return self.get_row_cel(row, self.ex.getReferer())

    def get_Params(self, row):
        '''获取请求参数'''
        return self.get_row_cel(row, self.ex.getParams())

    def get_Expect(self, row):
        '''获取期望结果'''
        return self.get_row_cel(row, self.ex.getExpect())

    def get_IsRun(self, row):
        '''获取是否运行'''
        return self.get_row_cel(row, self.ex.getIsRun())
Exemplo n.º 3
0
class Login(unittest.TestCase):
    def setUp(self):
        self.methon = WebMethon()
        self.config = Config()
        self.excel = OperationExcel()
        self.pm = PublicMethod()
        self.operationJson = OperationJson()
        self.iscontent = IsContent()

    def tearDown(self):
        pass

    def test_Login_001(self):
        '''
		登陆大桶大后台系统:/Account/Login
		:return:
		'''
        r = self.methon.post(0, 1)
        self.assertTrue(r.json()['IsSuccess'], True)
        self.assertTrue(self.iscontent.isContent(1, r.text))

        #将登陆成功后得token写入到文件中
        self.pm.writeFile('data', 'login', 'token', r.json()['Data']['token'])
Exemplo n.º 4
0
class OperationJson:
    def __init__(self):
        self.excel = OperationExcel()
        self.pm = PublicMethod()

    def getReadJson(self, ensure_ascii=False):
        '''读取到json文件中的内容'''
        with open(self.pm.data_dir('data', 'jsonData.json'),
                  encoding='utf-8') as f:
            data = json.load(f)
            return data

    def getRequestsData(self, row, ensure_ascii=False):
        '''获取请求参数'''
        return self.getReadJson()[self.excel.get_Params(row=row)]
Exemplo n.º 5
0
 def __init__(self):
     self.config = Config()
     self.excel = OperationExcel()
     self.public = PublicMethod()
     self.json = OperationJson()
Exemplo n.º 6
0
class WebMethon(PublicMethod):
    def __init__(self):
        self.config = Config()
        self.excel = OperationExcel()
        self.public = PublicMethod()
        self.json = OperationJson()

#=================封装请求头,s=0,未登录的请求头。s=1,已登陆的请求头==============================

    def getHeadersInfo(
        self,
        row,
    ):
        '''已登录的请求头'''
        headers = {
            'Host': self.config.getHost(),
            #'Content-Type': self.excel.get_ParamsType(row=row),
            'Accept-Encoding': 'gzip, deflate',
            'Cookie':
            'Hm_lvt_950d894867df0a55fbb3239fba8837ea=1588758701,1588774347,1588833146,1588856383',
            'Accept': '*/*',
            'User-Agent': 'DDOU/1.0.3 (iPhone; iOS 13.3.1; Scale/3.00)',
            'Authorization': self.public.getFile('data', 'login', 'token'),
            #'Referer': self.config.getUrl()[0]+self.excel.get_Referer(row=row)
        }
        return headers

    def post(self, s, row, **kwargs):
        '''
		请求参数是json格式的post,这里读取的是excel+json文件中的数据
		s=1:json格式的参数
		s=2:data格式的参数
		'''
        if s == 1:
            try:
                r = requests.post(url=self.config.getUrl()[0] +
                                  self.excel.get_Url(row=row),
                                  json=self.json.getRequestsData(row=row),
                                  headers=self.getHeadersInfo(row=row),
                                  timeout=5)
                return r
            except Exception as e:
                raise RuntimeError('接口请求法生未知的错误')
        elif s == 2:
            '''请求方法是data格式的post,这里读取得是excel文件中的数据'''
            try:
                r = requests.post(url=self.excel.get_Url(row=row),
                                  data=self.excel.get_Params(row=row),
                                  headers=self.getHeadersInfo(row=row),
                                  timeout=5)
                return r
            except Exception as e:
                raise RuntimeError('接口请求法生未知的错误')
        else:
            print('Eorr:请检查请求参数!')

    def get(self, url, params=None):
        '''对get请求进行二次封装'''
        r = requests.get(url=url,
                         params=params,
                         headers=self.getHeadersInfo(),
                         timeout=5)
        return r
Exemplo n.º 7
0
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#Author: Peng Chao

import logging
from utils.public import PublicMethod

pm = PublicMethod()
# def log(log_content):
#     # 定义文件
#     logFile = logging.FileHandler(pm.data_dir('logs', 'logInfo.md'), 'a',encoding='utf-8')
#     # log格式
#     fmt = logging.Formatter(fmt='%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s')
#     logFile.setFormatter(fmt)
#     # 定义日志
#     logger1 = logging.Logger('logTest', level=logging.DEBUG)
#     logger1.addHandler(logFile)
#     logger1.info(log_content)


import os
import logging
from logging.handlers import TimedRotatingFileHandler


class Logger(object):
    def __init__(self, logger_name='logs…'):
        self.logger = logging.getLogger(logger_name)
        logging.root.setLevel(logging.NOTSET)
        #self.log_file_name = 'logs'  # 日志文件的名称
        self.backup_count = 5  # 最多存放日志的数量
Exemplo n.º 8
0
 def __init__(self):
     self.excel = OperationExcel()
     self.pm = PublicMethod()
Exemplo n.º 9
0
class Runner:
    def __init__(self):
       self.pm = PublicMethod()
       self.excel = OperationExcel()
#==============定义发送邮件==========
    def send_mail(self,file_new):
        #-----------1.跟发件相关的参数------
        smtpserver ='smtp.qq.com'  #发件服务器
        port = 25   #端口
        username = '******' #发件箱用户名
        password = '******'        #发件箱密码
        sender = '*****@*****.**'   #发件人邮箱
        receiver =['*****@*****.**'] #收件人邮箱
        #'*****@*****.**','*****@*****.**'
        # ----------2.编辑邮件的内容------
        #读文件
        f = open(file_new,'rb')
        mail_body = f.read()
        f.close()

        # content = '通过数:{0} 失败数:{1} 通过率:{2}'.format(
        #     self.excel.run_success_result(),
        #     self.excel.run_fail_result(),
        #     self.excel.run_pass_rate(),
        # )
        # 邮件正文是MIMEText
        #body = MIMEText(content,_subtype='plain',_charset='utf-8')
        body = MIMEText(_text=None,_subtype='plain', _charset='utf-8')
        # 邮件对象
        msg = MIMEMultipart()
        msg['Subject'] =Header("自动化测试报告",'utf-8').encode()#主题
        msg['From'] =Header('发件人:'.format(sender))
        msg['To'] = Header('收件人:'.format(receiver))       #收件人
        msg['To'] = ','.join(receiver)
        msg['date'] = self.pm.timer
        msg.attach(body)
        # 附件
        att = MIMEText(mail_body, "base64", "utf-8")
        att["Content-Type"] = "application/octet-stream"
        att["Content-Disposition"] = 'attachment; filename="test_report.html"'
        msg.attach(att)
        # ----------3.发送邮件------
        try:
            smtp = smtplib.SMTP()
            smtp.connect(smtpserver)  # 连服务器
            smtp.login(sender, password)
        except:
            smtp = smtplib.SMTP_SSL(smtpserver, port)
            smtp.login(sender, password)  # 登录
        smtp.sendmail(sender, receiver, msg.as_string())  # 发送
        smtp.quit()
        #发送邮件
        smtp = smtplib.SMTP()
        smtp.connect("smtp.qq.com")  # 邮箱服务器
        smtp.login(username, password)  # 登录邮箱
        smtp.sendmail(sender, receiver, msg.as_string())  # 发送者和接收者
        smtp.quit()
        print("邮件已发出!注意查收。")
    # ======查找测试目录,找到最新生成的测试报告文件======
    def new_report(self,test_report):
        lists = os.listdir(test_report)  # 列出目录的下所有文件和文件夹保存到lists
        lists.sort(key=lambda fn: os.path.getmtime(test_report + "\\" + fn))  # 按时间排序
        file_new = os.path.join(test_report, lists[-1])  # 获取最新的文件保存到file_new
        print(file_new)
        return file_new

    def getSuite(self):
        '''获取要执行的测试套件'''
        suite = unittest.TestLoader().discover(
            start_dir=self.pm.data_dirFile('tests'),
            pattern='test_dtd_*.py',
            top_level_dir=None)
        return suite

    def runAll(self):
        # 保存生成报告的路径
        report_path = self.pm.data_dir("report","test_Report.html")
        fp = open(report_path, 'wb')
        # 返回实例
        runner = unittest.TextTestRunner()
        # 执行所有的测试用例并发送邮件
        runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                               title=u"DTD项目接口自动化测试报告",
                                               description=u"用例执行情况",
                                               verbosity=2
                                               ).run(self.getSuite())
        # 关闭文件,记住用open()打开文件后一定要记得关闭它,否则会占用系统的可打开文件句柄数。
        fp.close()
        # 测试报告文件夹
        test_path= self.pm.data_dirFile('report')
        new_report = self.new_report(test_path)
        self.send_mail(new_report)
Exemplo n.º 10
0
 def __init__(self):
     self.pm = PublicMethod()
     self.ex = ExcelVaribles()
Exemplo n.º 11
0
	def __init__(self):
		self.pm = PublicMethod()
Exemplo n.º 12
0
class Config:
	def __init__(self):
		self.pm = PublicMethod()

	def getHost(self,fileName = 'host'):
		#获取host
		list1 = []
		config = configparser.ConfigParser()
		config.read(self.pm.data_dir(file='config',fileName = 'config.ini'),encoding='UTF-8')
		host = config.get(fileName,'host')
		list1.append([host])
		return list1[0]
	def getLogin(self,fileName = 'login'):
		'''读取配置文件中登陆的数据'''
		list1 = []
		config = configparser.ConfigParser()
		config.read(self.pm.data_dir(file='config',fileName='config.ini'),encoding='UTF-8')
		phone = config.get(fileName,'phone')
		passWord = config.get(fileName, 'Password')
		list1.append([phone,passWord])
		return list1[0]

	def getEmail(self,fileName = 'email'):
		'''读取配置文件中邮箱的数据'''
		list1 = []
		config = configparser.ConfigParser()
		config.read(self.pm.data_dir(file='config',fileName='config.ini'),encoding='UTF-8')
		user = config.get(fileName,'user')
		passWord = config.get(fileName, 'password')
		list1.append([user,passWord])
		return list1[0]

	def getMysql(self,fileName = 'SQL Service'):
		'''读取配置文件中链接数据库的数据'''
		list1 = []
		config = configparser.ConfigParser()
		config.read(self.pm.data_dir(file='config',fileName='config.ini'),encoding='UTF-8')
		host = config.get(fileName,'host')
		user = config.get(fileName,'user')
		passwd = config.get(fileName, 'passwd')
		db = config.get(fileName,'db')
		list1.append([host,user,passwd,db])
		return list1[0]

	def getUrl(self,fileName = 'url'):
		'''读取配置文件中URL'''
		url = None
		config = configparser.ConfigParser()
		config.read(self.pm.data_dir(file='config',fileName='config.ini'),encoding='UTF-8')
		url = config.get(fileName,'url')
		url = url
		return url

	def getAuth(self,fileName = 'AppAuth'):
		'''读取配置文件中地址的信息'''
		list1 = []
		config = configparser.ConfigParser()
		config.read(self.pm.data_dir(file='config',fileName='config.ini'),encoding='UTF-8')
		Auth = config.get(fileName,'Auth')
		list1.append([Auth])
		return list1[0]