示例#1
0
文件: configDB.py 项目: bopopescu/RY
class MyDB:

    def __init__(self):
       global host, user, passwd, port, database, config
       host = localReadConfig.get_db("host")
       user = localReadConfig.get_db("username")
       passwd = localReadConfig.get_db("password")
       port = localReadConfig.get_db("port")
       database = localReadConfig.get_db("database")
       self.log = MyLog().get_log()
       self.logger = self.log.get_logger()

       self.db = None
       self.cursor=None

    #连接数据库,把连接后数据数据库的游标赋值给初始化定义的游标,以便后面操作的使用。不要使用return 游标。
    #因为return  的函数不更改原值,而赋值则是将None改为实际的游标。
    def connectDB(self):

        """
        connect to database
        :return:
        """
        try:
            # connect to DB
            self.db = MySQLdb.connect(host,user,passwd,database,use_unicode=True, charset="utf8")
            print "self.db is",self.db
            self.cursor=self.db.cursor()
            print("Connect DB successfully!")
        except MySQLdb.Error as ex:
            self.logger.error(str(ex))
            print "Connect DB faild"

    #通过初始化函数中的self.cursor = self.db.cursor()获得游标,执行sql语句。
    def executeSQL(self, sql):
        """
        execute sql
        :param sql:
        :return:
        """
        self.connectDB()
        # executing sql,游标执行之前一定要保证是连接了数据库
        self.cursor.execute(sql)
        # executing by committing to DB
        self.db.commit()
        return self.cursor
    #不用self.cursor原因是任何数据库操作的执行都需要先链接,获取curse。gett all是在执行数据库操作之后获取数据,所以是在
    # executeSQL执行之后执行的函数,因此可以将 executeSQL执行后返回的curse传入get_allh函数获取数据。因此此处定义了一个变量。
    #而使用全局的sel.curser是不需要定义变量的
    def get_all(self,cursor):
        """
        get all result after execute sql
        :param cursor:
        :return:
        """
        value = cursor.fetchall()
        return value

    def get_one(self,cursor):
        """
        get one result after execute sql
        :param cursor:
        :return:
        """
        value =cursor.fetchone()
        return value

    def closeDB(self):
        """
        close database
        :return:
        """
        self.db.close()
        print("Database closed!")
示例#2
0
class Email:
    def __init__(self):
        global host, user, psw, port, sender, title
        #有几个变量以下其实并未用到
        host = localReadConfig.get_email("mail_host")
        user = localReadConfig.get_email("mail_user")
        psw = localReadConfig.get_email("mail_pass")
        port = localReadConfig.get_email("mail_port")
        sender = localReadConfig.get_email("sender")
        title = localReadConfig.get_email("subject")
        # content = localReadConfig.get_email("content")
        #receiver=localReadConfig.get_email("receiver")
        self.receivers = []

        #get receiver list
        value = localReadConfig.get_email("receiver")
        for n in str(value).split("/"):
            self.receivers.append(n)
        #print self.receivers

        # defined email subject
        date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.subject = u"接口测试报告" + " " + date

        self.log = MyLog().get_log()
        self.logger = self.log.get_logger()
        self.msg = MIMEMultipart('related')

    def config_header(self, receivers=None):
        """
        defined email header include subject, sender and receiver
        :return:
        """
        self.msg['subject'] = title
        self.msg['from'] = sender
        #添加多个接收人
        self.msg['to'] = ",".join(self.receivers)
        print self.msg['to']

    def config_content(self):
        """
        write the content of email
        :return:
        """
        f = open(os.path.join(readConfig.proDir, 'testFile', 'emailStyle.txt'))
        content = f.read()
        f.close()
        content_plain = MIMEText(content, 'html', 'UTF-8')
        #上传文件
        self.msg.attach(content_plain)
        #上传图片
        self.config_image()

    def config_image(self):
        """
        config image that be used by content
        :return:
        """
        # defined image path
        image1_path = os.path.join(readConfig.proDir, 'testFile', 'img',
                                   '1.png')
        fp1 = open(image1_path, 'rb')
        msgImage1 = MIMEImage(fp1.read())
        # self.msg.attach(msgImage1)
        fp1.close()

        # defined image id
        msgImage1.add_header('Content-ID', '<image1>')
        self.msg.attach(msgImage1)

        image2_path = os.path.join(readConfig.proDir, 'testFile', 'img',
                                   'logo.jpg')
        fp2 = open(image2_path, 'rb')
        msgImage2 = MIMEImage(fp2.read())
        # self.msg.attach(msgImage2)
        fp2.close()

        # defined image id
        msgImage2.add_header('Content-ID', '<image2>')
        self.msg.attach(msgImage2)

    def config_file(self):
        """
        config email file
        :return:
        """

        # if the file content is not null, then config the email file
        if self.check_file():

            reportpath = self.log.get_result_path()
            zippath = os.path.join(readConfig.proDir, "result", "test.zip")

            # zip file
            files = glob.glob(reportpath + '\*')
            f = zipfile.ZipFile(zippath, 'w', zipfile.ZIP_DEFLATED)
            for file in files:
                # 修改压缩文件的目录结构
                f.write(file, '/report/' + os.path.basename(file))
            f.close()

            reportfile = open(zippath, 'rb').read()
            filehtml = MIMEText(reportfile, 'base64', 'utf-8')
            filehtml['Content-Type'] = 'application/octet-stream'
            filehtml['Content-Disposition'] = 'attachment; filename="test.zip"'
            self.msg.attach(filehtml)

    def check_file(self):
        """
        check test report
        :return:
        """
        reportfile = self.log.get_report_path()
        if os.path.isfile(reportfile) and not os.stat(reportfile) == 0:
            return True
        else:
            return False

    def send_email(self):
        try:
            self.config_header()
            self.config_content()
            self.config_file()
            try:
                smtp = smtplib.SMTP()
                smtp.connect(host)
                smtp.login(sender, psw)
            except:
                smtp = smtplib.SMTP_SSL(host)
                smtp.login(sender, psw)
            smtp.sendmail(sender, self.receivers, self.msg.as_string())
            smtp.quit()
            #print "The test report has send to developer by email!"
            self.logger.info("The test report has send to developer by email.")
        except Exception as ex:
            self.logger.error(str(ex))