def __init__(self, dbhost=conf.get('mysql', 'DB_HOST'), dbport=conf.getint('mysql', 'DB_PORT'), dbname=conf.get('mysql', 'DB_NAME'), dbuser=conf.get('mysql', 'DB_USER'), dbpasswd=conf.get('mysql', 'DB_PASSWORD'), charset='utf8', maxconnections=20): """ 数据库构造函数,从连接池中取出连接,并生成操作游标 :param dbhost: 数据库地址 :param dbport: 数据库端口 :param dbname: 数据库名称 :param dbuser: 数据库账号 :param dbpasswd: 数据库密码 :param charset: 数据库字符集 :param maxconnections:连接池通常允许的最大连接数,0或None表示任意数量的连接 """ # mincached 最少的空闲连接数,如果空闲连接数小于这个数,pool会创建一个新的连接,0表示启动时没有连接 # maxcached 最大的空闲连接数,如果空闲连接数大于这个数,pool会关闭空闲连接,0或None表示无限制的池大小 # use_unicode=False, cursorclass=DictCursor(返回字典格式) # ping:确定何时使用ping()检查连接(0=None=never,1=default=每当从池中获取时,2=创建游标时,4 =执行查询时,7=always) self.conn = PooledDB(creator=pymysql, mincached=0, maxcached=5, maxconnections=maxconnections, host=dbhost, port=dbport, user=dbuser, passwd=dbpasswd, db=dbname, charset=charset, ping=4).connection() self.cursor = self.conn.cursor()
def get_conn(dbhost=conf.get('mysql', 'DB_HOST'), dbport=conf.getint('mysql', 'DB_PORT'), dbname=conf.get('mysql', 'DB_NAME'), dbuser=conf.get('mysql', 'DB_USER'), dbpasswd=conf.get('mysql', 'DB_PASSWORD'), charset='utf8'): """ 获取sql连接 :param dbhost: 数据库地址 :param dbport: 数据库端口 :param dbname: 数据库名称 :param dbuser: 数据库账号 :param dbpasswd: 数据库密码 :param charset: 数据库字符集 :return:返回数据库连接对象 """ LOG.debug("The mysql host is :" + dbhost) LOG.debug("The mysql port is :" + str(dbport)) LOG.debug("The mysql user is :" + dbuser) LOG.debug("The mysql passwd is :" + dbpasswd) LOG.debug("The mysql db is :" + dbname) return pymysql.connect(host=dbhost, port=dbport, user=dbuser, passwd=dbpasswd, db=dbname, charset=charset)
def _runcase(self, _project_name): t1 = time.time() result_dict = dict() if self.is_valid_path(): # 1、获取当前时间,这样便于下面的使用。 now = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime(time.time())) # 2、html报告文件路径 report_abspath = os.path.join( self.report_path, "result_" + _project_name + "_" + now + ".html") LOGGER.info('生成报告路径:{0}'.format(report_abspath)) # 3、打开一个文件,将result写入此file中 fp = open(report_abspath, "wb") projectname = ms.select_one(ms.get_conn(), 't_dict', 'name', 'code="{}"'.format(_project_name)) title = projectname + '-' + ConfigUtils.get( 'report', 'REPORT_NAME') runner = HTMLTestRunner(stream=fp, title=title + u',运行情况如下:', description=u'用例执行情况:') # 4、调用add_case函数返回值 r = runner.run(self.case()) passed = r.success_count faild = r.failure_count + r.error_count result_dict['passed'] = passed result_dict['faild'] = faild fp.close() LOGGER.info('接口测试总耗时: {}秒'.format(time.time() - t1)) return result_dict
def __init__(self, logger): """ 指定保存日志的文件路径,日志级别,以及调用文件 将日志存入到指定的文件中 :param logger: """ # 创建日志名称。 log_level = conf.get('report', 'LogLevel').lower() level = LEVELS[log_level] rq = time.strftime('%Y%m%d', time.localtime(time.time())) # os.getcwd()获取当前文件的路径,os.path.dirname()获取指定文件路径的上级路径 log_path = os.path.dirname(os.path.dirname( os.path.dirname(__file__))) + '/testReport/log/' if 'Windows' in platform.system(): log_path = log_path.replace('/', '\\') FileUtils.mkdir(log_path) # 创建一个logger self.logger = logging.getLogger(logger) self.logger.setLevel(level) log_name = log_path + rq + '.log' # 创建一个handler,用于写入日志文件 fh = logging.FileHandler(filename=log_name, mode='a', encoding='utf-8') fh.setLevel(level) # 创建一个handler,用于写入error及以上级别的日志文件 e_name = log_path + 'ERROR' + rq + '.log' eh = logging.FileHandler(filename=e_name, mode='a', encoding='utf-8') eh.setLevel(logging.ERROR) # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() ch.setLevel(level) # 定义handler的输出格式 formatter = logging.Formatter( '%(asctime)s %(filename)s %(name)s [line:%(lineno)d] %(levelname)s ' '%(message)s', '%Y-%m-%d %H:%M:%S') fh.setFormatter(formatter) ch.setFormatter(formatter) eh.setFormatter(formatter) # 给logger添加handler self.logger.addHandler(fh) self.logger.addHandler(ch) self.logger.addHandler(eh)
from common.myCommon import Assertion from common.myCommon.Logger import getlog from common.myConfig import ConfigUtils as conf from common.myConfig import MysqlConfig from common.myFile import FileUtils from common.mydb import MysqlClent dp_web_URL = MysqlConfig.get('dp_web_apiURL', 'dp') dp_app_URL = MysqlConfig.get('dp_app_apiURL', 'dp') db_info = {"dbhost": "192.168.15.236", "dbport": 3308, "dbname": "car_screen", "dbuser": "******", "dbpasswd": "78dk.com"} DB = MysqlClent.get_conn(**db_info) LOGGER = getlog(__name__) API_TEST_HEADERS = {"Content-Type": "application/json", "Cache-Control": "no-cache"} rq = requests.Session() sign = conf.get('report', 'sign') username = '******' userpassword = '******' app_username = '******' app_userpassword = '******' def test_dp_web_login(): """ web端登录 :return: """ requesturl = dp_web_URL + "/login" LOGGER.info("登陆请求地址:【{}】".format(requesturl)) params = {"userName": username, "userPassword": userpassword}
class SendMail(object): LOG = getlog(__name__) reportPath = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + "/testReport/report/" logPath = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + "/testReport/log/" if "Windows" in platform.system(): reportPath = reportPath.replace("/", "\\") logPath = logPath.replace("/", "\\") # 邮箱服务器地址 MAIL_HOST = conf.get('mail', 'MAIL_HOST') # 登录邮箱服务器账号 MAIL_USER = conf.get('mail', 'MAIL_USER') # 登录邮箱服务器账号密码 MAIL_PASSWORD = conf.get('mail', 'MAIL_PASSWORD') # 邮箱服务器端口 MAIL_PORT = conf.getint('mail', 'MAIL_PORT') # 收件人邮箱,使用 , 隔开 MAIL_RECEIVER = conf.get('mail', 'MAIL_RECEIVER').split(',') # 抄送人 MAIL_CC_RECEIVER = conf.get('mail', 'MAIL_CC_RECEIVER').split(',') # 邮件标题 MAIL_SUBJECT = conf.get('mail', 'MAIL_SUBJECT') # 邮件类型,普通邮件为 plain ,包含HTML时用html MAIL_TYPE = conf.get('mail', 'MAIL_TYPE') # 邮件附件地址 MAIL_ATTACHMENT = conf.get('mail', 'MAIL_ATTACHMENT').split(',') LOG.info('服务器地址:【{0}】,登录邮箱服务器账号:【{1}】,' '登录邮箱服务器账号密码:【{2}】,' '邮箱服务器端口:【{3}】,收件人邮箱:【{4}】,邮件标题:【{5}】' .format(MAIL_HOST, MAIL_USER, MAIL_PASSWORD, MAIL_PORT, MAIL_RECEIVER, MAIL_SUBJECT)) def sendSMTP(self, sendcontent): """ 发送包普通邮件 :param sendcontent: 正文 """ message = MIMEText(sendcontent, self.MAIL_TYPE, "utf-8") message["From"] = Header(self.MAIL_USER, "utf-8") for toName in self.MAIL_RECEIVER: message["To"] = Header(toName, "utf-8") message["Subject"] = Header(self.MAIL_SUBJECT, "utf-8") self.LOG.info("开始发送邮件".center(40, "*")) try: smtpObj = smtplib.SMTP() smtpObj.connect(self.MAIL_HOST, self.MAIL_PORT) # 25 为 SMTP 端口号 smtpObj.login(self.MAIL_USER, self.MAIL_PASSWORD) smtpObj.sendmail( self.MAIL_USER, self.MAIL_RECEIVER, message.as_string() ) smtpObj.quit() self.LOG.info("邮件发送成功".center(40, "*")) except smtplib.SMTPException: self.LOG.error("Error: 无法发送邮件".center(40, "*")) def sendAttachment(self, sendcontent): """ 发送包含附件的邮件 :param sendcontent: 正文 :return: """ self.LOG.info(u"开始发送邮件".center(40, "*")) # 创建一个带附件的实例 message = MIMEMultipart() message["From"] = Header(self.MAIL_USER, "utf-8") for toName in self.MAIL_RECEIVER: message["To"] = Header(toName, "utf-8") message["Subject"] = Header(self.MAIL_SUBJECT, "utf-8") # 邮件正文内容 message.attach(MIMEText(sendcontent, self.MAIL_TYPE, "utf-8")) for attfile in self.MAIL_ATTACHMENT: # 构造附件1,传送当前目录下的 test.txt 文件 att = MIMEText(open(attfile, "rb").read(), "base64", "utf-8") fileName = open(attfile, "w+").name att["Content-Type"] = "application/octet-stream" # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att["Content-Disposition"] = "attachment; filename=" + fileName message.attach(att) try: smtpObj = smtplib.SMTP() smtpObj.connect(self.MAIL_HOST, self.MAIL_PORT) # 25 为 SMTP 端口号 smtpObj.login(self.MAIL_USER, self.MAIL_PASSWORD) smtpObj.sendmail( self.MAIL_USER, self.MAIL_RECEIVER, message.as_string() ) smtpObj.quit() self.LOG.info(u"邮件发送成功".center(40, "*")) except smtplib.SMTPException: self.LOG.error(u"Error: 无法发送邮件".center(40, "*")) def __get_report(self): """获取最新测试报告""" self.LOG.info("The report path is : {}".format(self.reportPath)) dirs = os.listdir(self.reportPath) dirs.sort() newreportname = dirs[-1] self.LOG.info("The new report name: {0}".format(newreportname)) return newreportname def __get_logpath(self): """获取最新日志""" self.LOG.info("The log path is : {}".format(self.logPath)) logdirs = os.listdir(self.logPath) logdirs.sort() logname = logdirs[-1] self.LOG.info("The new log path name: {0}".format(logname)) return logname @staticmethod def __read_file(fpath): # 读取文件 BLOCK_SIZE = 1024 with open(fpath, 'rb') as f: while True: block = f.read(BLOCK_SIZE) if block: yield block else: return def send(self): """发送测试结果报告邮件""" self.LOG.info(u"开始发送邮件".center(40, "*")) logname = self.__get_logpath() newreportname = self.__get_report() # 创建一个带附件的实例 message = MIMEMultipart() message["From"] = Header(self.MAIL_USER, "utf-8") for toName in self.MAIL_RECEIVER: message["To"] = Header(toName, "utf-8") """生成邮件的内容,和html报告附件""" message["Subject"] = Header(self.MAIL_SUBJECT, "utf-8") message["date"] = time.strftime("%a, %d %b %Y %H:%M:%S %z") # 读取报告内容,并添加到正文 newreportPath = os.path.join(self.reportPath, newreportname) self.LOG.info(u"添加附件{}".format(newreportPath)) # with open(newreportPath, "rb") as f: # mailbody = f.read() mailbody = '' for item in self.__read_file(newreportPath): mailbody += bytes.decode(item) html = MIMEText(mailbody, _subtype="html", _charset="utf-8") message.attach(html) # html附件 att1 = MIMEText(mailbody, "base64", "gb2312") att1["Content-Type"] = "application/octet-stream" att1["Content-Disposition"] = "attachment; filename={0}".format( newreportname ) # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 message.attach(att1) # log日志附件 newlogPath = os.path.join(self.logPath, logname) self.LOG.info(u"添加附件{}".format(newlogPath)) att2 = MIMEText(open(newlogPath, "rb").read(), "base64", "gb2312") att2["Content-Type"] = "application/octet-stream" att2["Content-Disposition"] = "attachment; filename={0}".format( logname ) # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 message.attach(att2) smtpObj = smtplib.SMTP() try: smtpObj.connect(self.MAIL_HOST, self.MAIL_PORT) # 25 为 SMTP 端口号 smtpObj.login(self.MAIL_USER, self.MAIL_PASSWORD) smtpObj.sendmail( self.MAIL_USER, self.MAIL_RECEIVER, message.as_string() ) self.LOG.info(u"邮件发送成功".center(40, "*")) except smtplib.SMTPException as e: self.LOG.error("Error: 无法发送邮件".center(40, "*")) self.LOG.error("错误原因:{}".format(e)) finally: smtpObj.quit() def send_report(self, project, report_path): """发送测试结果报告邮件""" self.LOG.info(u"开始发送邮件".center(40, "*")) logname = self.__get_logpath() # 创建一个带附件的实例 message = MIMEMultipart() message["From"] = Header(self.MAIL_USER, "utf-8") for toName in self.MAIL_RECEIVER: message["To"] = Header(toName, "utf-8") message["Cc"] = ';'.join(self.MAIL_CC_RECEIVER) """生成邮件的内容,和html报告附件""" subject = project + self.MAIL_SUBJECT + time.strftime("%Y%m%d", time.localtime(time.time())) message["Subject"] = Header(subject, "utf-8") message["date"] = time.strftime("%a, %d %b %Y %H:%M:%S %z") # 读取报告内容,并添加到正文 self.LOG.info(u"添加附件{}".format(report_path)) with open(report_path, "rb") as f: mailbody = f.read() # mailbody = ''.join(FileUtils.readfile(report_path)) # for item in self.__read_file(report_path): # mailbody += bytes.decode(item) html = MIMEText(mailbody, _subtype="html", _charset="utf-8") message.attach(html) # html附件 att1 = MIMEText(mailbody, "base64", "gb2312") att1["Content-Type"] = "application/octet-stream" # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1["Content-Disposition"] = "attachment; filename={0}".format(report_path) message.attach(att1) # log日志附件 newlogPath = os.path.join(self.logPath, logname) self.LOG.info(u"添加附件{}".format(newlogPath)) att2 = MIMEText(open(newlogPath, "rb").read(), "base64", "gb2312") att2["Content-Type"] = "application/octet-stream" att2["Content-Disposition"] = "attachment; filename={0}".format( logname ) # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 message.attach(att2) smtpObj = smtplib.SMTP() try: smtpObj.connect(self.MAIL_HOST, self.MAIL_PORT) # 25 为 SMTP 端口号 smtpObj.login(self.MAIL_USER, self.MAIL_PASSWORD) smtpObj.sendmail( self.MAIL_USER, self.MAIL_RECEIVER, message.as_string() ) self.LOG.info(u"邮件发送成功".center(40, "*")) except smtplib.SMTPException as e: self.LOG.error("Error: 无法发送邮件".center(40, "*")) self.LOG.error("错误原因:{}".format(e)) finally: smtpObj.quit()