Ejemplo n.º 1
0
    def setupBox(self):
        self.cf = ReadConfig()

        self.sender = self.cf.get_mail('sender')
        self.receiver = self.cf.get_mail('receiver')
        self.smtpserver = self.cf.get_mail('smtpserver')
        self.username = self.cf.get_mail('username')
        self.passwd = self.cf.get_mail('passwd')
Ejemplo n.º 2
0
def get_data(sql):
    config = ReadConfig()
    data = config.get_section('db')
    con = Db(
        host=data['host'],
        port=data['port'],
        user=data['user'],
        password=data['password'],
        db=data['db']
    )
    return con.get_df(sql)
Ejemplo n.º 3
0
class ConfigEmail(object):
    def setupBox(self):
        self.cf = ReadConfig()

        self.sender = self.cf.get_mail('sender')
        self.receiver = self.cf.get_mail('receiver')
        self.smtpserver = self.cf.get_mail('smtpserver')
        self.username = self.cf.get_mail('username')
        self.passwd = self.cf.get_mail('passwd')

    def setupContent(self):
        t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        subject = '自动化测试结果_' + t
        content = '测试报告见附件'

        #文本内容
        msg = MIMEText(content, 'plain', 'utf-8')

        #添加附件
        htmlPath = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            r'report\testReport.html')
        print(htmlPath)
        htmlFilename = os.path.basename(htmlPath)
        print(htmlFilename)
        reportApart = MIMEApplication(open(htmlPath, 'rb').read())
        reportApart.add_header('Content-Disposition',
                               'attachment',
                               filename=htmlFilename)

        #打包文本内容和附件内容,加标题,form,to
        self.m = MIMEMultipart()
        self.m.attach(msg)
        self.m.attach(reportApart)
        self.m['Subject'] = Header(subject, 'utf-8')
        self.m['From'] = self.sender
        self.m['To'] = self.receiver

    def sendMail(self):
        self.setupBox()
        self.setupContent()

        try:
            s = smtplib.SMTP()
            s.connect(self.smtpserver)
            s.login(self.username, self.passwd)
            s.sendmail(self.sender, self.receiver, self.m.as_string())
        except BaseException as m:
            print("邮件发送失败", m)
        else:
            print("邮件发送成功")
        finally:
            s.quit()
Ejemplo n.º 4
0
 def read_config(cls, section, path=None):
     parser = ReadConfig(path)
     instance = cls.__new__(cls)
     parser.update_attr(instance, section)
     setattr(instance, 'login_status', False)
     setattr(instance, 'session', requests.Session())
     if hasattr(instance, 'host') and hasattr(instance, 'login_endpoint'):
         setattr(
             instance, 'login_url',
             urljoin(getattr(instance, 'host'),
                     getattr(instance, 'login_endpoint')))
     return instance
Ejemplo n.º 5
0
def choice_env(envs):
    """
    选择测试环境
    :param envs:
    :return:
    """

    if 'TEST' == envs:
        baseurl = ReadConfig().get_config_value('TESTHTTP', 'BASEURL')
    elif 'PRO' == envs:
        baseurl = ReadConfig().get_config_value('HTTP', 'BASEURL')
    else:
        print('请选择执行环境')
    return baseurl
Ejemplo n.º 6
0
def conOracle():
    host = ReadConfig.get_sql("host")
    port = ReadConfig.get_sql("host")
    user = ReadConfig.get_sql("host")
    password = ReadConfig.get_sql("host")
    service = ReadConfig.get_sql("host")

    db = oracle.connect('TFT_TSM/[email protected]:1521/tft_csm')
    cursor = db.cursor()
    sql = "select USERID from TFT_TSM.T_CLIENT_USER_INFO where MSISDN = '18328019517'"
    cursor.execute(sql)
    data = cursor.fetchone()
    print(data)
    cursor.close()
    db.close()
Ejemplo n.º 7
0
class Optool(object):

    config = ReadConfig()
    log = Log()

    # def __init__(self):
    #     pass

    def join_url(self, url_path):
        """
        拼接url
        :param url_path:url的路径
        :return: url 测试地址
        """
        protocol = self.config.get_http("protocol")
        host = self.config.get_http("host")
        port = self.config.get_http("port")
        url = protocol + "://" + host + ":" + port + "/" + url_path
        self.log.info("接口请求地址: %s" % url)
        return url

    def better_show_json(self, dict_str):
        """
        python数据类型转化为json数据类型
        :json_str: python数据类型
        :return: json
        """
        return json.dumps(dict_str, indent=4)

    def re_get_values(self, pattern, response, num):
        """
        正则提取参数值
        :param pattern: 正则表达式 格式如:r"<input type=\"hidden\" value=\"(.+?)\" />"
        :param response: 被提取对象
        :param num: 0表示取第一值,1表示取任意一个值
        :return: 提取值
        """
        if num == 0:
            return re.findall(pattern, response)[0]
        if num == 1:
            length = len(re.findall(pattern, response))
            index = random.randint(1, length - 1)
            return re.findall(pattern, response)[index]
        else:
            self.log.info("num参数不正确")

    def md5(self, str):
        """
        MD5加密
        :param src: 字符串
        :return: 加密数据
        """
        m = hashlib.md5()
        m.update(str.encode('UTF-8'))
        return m.hexdigest()
Ejemplo n.º 8
0
def login():
    path = "/uac/auth/form"
    config = ReadConfig(config_file)
    url = config.get_baseurl()
    optocal = config.get_protocol()
    username = config.get_login()[0]
    password = config.get_login()[1]
    data = {'username': username, "password": password}
    httpurl = optocal + "://" + url + path
    head = {}
    head['Content-Type'] = 'application/x-www-form-urlencoded'
    head[
        'Authorization'] = "Basic cGFhc2Nsb3VkLWNsaWVudC11YWM6cGFhc2Nsb3VkQ2xpZW50U2VjcmV0"
    r = requests.post(httpurl, data=data, headers=head)
    result = r.json()
    token = ''
    print(result)
    if result['code'] != 200:
        print("登录失败")
    else:
        print("登录成功")
        token = re.search(r"'access_token': '(.+?)'", str(result)).group(1)
    return token
Ejemplo n.º 9
0
class Womovie(object):

    log = Log()
    config = ReadConfig()
    excel_path = os.path.join(config.get_excel("path"), "login_data.xlsx")
    excel = ExcelUtil(excel_path, "帐号")

    def __init__(self, s):
        self.s = s

    def login(self, username, psw):
        """登录"""
        url = "http://61.171.24.229:5040/IosAiMovie/AiMovie/inputPassword"
        ret = self.s.get(url)
        # 提取登录Token
        form_token = re.findall(r"id=\"Token\" value=\"(.+?)\"", ret.text)[0]
        self.log.info("登录参数:FormToken=%s" % form_token)
        # 提取FormDate
        form_date = re.findall(r"id=\"Date\" value=\"(.+?)\"", ret.text)[0]
        self.log.info("登录参数:FormDate=%s" % form_date)
        # 提取__RequestVerificationToken
        pattern = r"<input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"(.+?)\" />"
        verification_token = re.findall(pattern, ret.text)[0]
        self.log.info("登录参数:__RequestVerificationToken=%s" %
                      verification_token)
        # 登录url
        url1 = "http://61.171.24.229:5040/IosAiMovie/MySlefContent/IosLoginIn"
        headers = {
            "X-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "__RequestVerificationToken": verification_token
        }
        data = {
            "account": username,
            "password": psw,
            "isSMS": False,
            "FormToken": form_token,
            "FormDate": form_date,
            "IMEI": None
        }
        self.s.post(url1, data, headers)
Ejemplo n.º 10
0
class ConfigEmail():
    #读取文件的配置属性
    r = ReadConfig()
    mail_host = r.get_email('mail_host')

    #配置第三方SMTP服务
    # mail_host = "smtp.126.com" #设置服务器
    mail_user = r.get_email('mail_user')  #用户名
    mail_pass = r.get_email("mail_pass")  #口令

    #配置邮件属性
    sender = r.get_email('sender')
    receivers = r.get_email('receiver')  #接收邮箱
    content = r.get_email('content')
    msg = MIMEMultipart()

    def config_file(self):
        #配置附件属性
        file = self.find_file()

    def find_file(self):
        '''查找最新文件'''
        #获取当前路径
        current_path = os.path.dirname(os.path.abspath(__file__))
        # print(current_path)
        #获取报告的存放路径
        filePath = os.path.dirname(current_path) + '\\' + 'report'
        # print('filepath:',filePath)

        #获取filepath路径下全部文件名称的列表
        fileList = os.listdir(filePath)
        # print(filePath)

        fileDict = {}
        fileTime = []

        for iName in fileList:
            #拼接文件路径和文件名
            filename = filePath + '/' + iName
            #获取该文件的修改时间
            iTime = os.path.getmtime(filename)
            #将该文件的修改时间追加到时间列表中
            # print(iTime)
            fileTime.append(iTime)
            #将文件名iname作为字典的value,文件修改的时间iTime作为字典的key存入
            fileDict[iTime] = iName
        # print(fileDict,fileTime)

        sendfilekey = max(fileTime)
        sendfile = fileDict[sendfilekey]
        # print(sendfile)
        sendfile = filePath + '/' + sendfile
        # print(sendfile)
        return sendfile

    #发送邮件
    def send_mail(self):
        self.config_file()
        try:
            s = smtplib.SMTP()
            # print(self.mail_host,self.mail_user,self.mail_pass)
            s.connect(self.mail_host, 25)
            # s.login(self.mail_user,self.mail_pass)
            print("邮件发送成功")
        except smtplib.SMTPException as msg:
            # print(msg)
            print("Error: 无法发送邮件:", msg)
Ejemplo n.º 11
0
class ConfigEmail():


    #读取ini文件配置属性
    r = ReadConfig()
    mail_host = r.get_email('mail_host')
    # 配置第三方 SMTP 服务
    # mail_host = "smtp.163.com"  #设置服务器
    mail_user = r.get_email('mail_user')  #用户名
    mail_pass = r.get_email('mail_pass')  #密码

    #配置邮件属性
    sender = r.get_email('sender') #发送方
    receivers = r.get_email('receiver')  # 接收方
    content = r.get_email('content') #内容
    msg = MIMEMultipart()

    # 获取创建时间最新的文件
    def get_last(self):
        report_dir = 'report'   # 报告所在文件夹名
        file_dir = os.path.dirname(os.path.split(os.path.abspath(__file__))[0])     # 获取当前路径上层目录
        report_path = file_dir + '\\' + report_dir      # 报告所在目录
        report = os.listdir(report_path)            # 获取报告目录下的所有文件
        report_create_time = []         # 存放报告文件的创建时间
        report_dict = {}                # 存放文件及文件的创建时间
        for i in report:
            c_time = time.ctime(os.path.getctime(report_path + '\\' + i))
            report_create_time.append(c_time)
            report_dict[c_time] = i
        max_time = max(report_create_time)     # 获取最大的时间
        last_file = report_dict[max_time]       # 获取最新的文件
        return report_path + '\\' + last_file

    def config_file(self):
        #配置附件属性
        file = self.get_last()
        print(file)
        sendfile=open(file,'rb').read()
        att = MIMEText(sendfile, 'plain', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        att["Content-Disposition"] = 'attachment; filename=report.html'
        self.msg.attach(att)
        self.msg['From'] = self.mail_user
        self.msg['To'] = self.sender
        self.msg['Subject'] = 'Python SMTP 附件邮件测试'
        self.msg.attach(MIMEText('UI自动化报告邮件,如果想查看详情请查收附件', 'plain', 'utf-8'))


    #发送邮件
    def send_mail(self):
        self.config_file()
        try:
            s = smtplib.SMTP()
            # print(self.mail_host,self.mail_user,self.mail_pass,self.sender,self.receivers,self.message.as_string)
            s.connect(self.mail_host, 25)    # 25 为 SMTP 端口号
            # s.set_debuglevel(1)
            # print(self.mail_user)
            # print(self.mail_pass)
            s.login(self.mail_user,self.mail_pass)

            s.sendmail(self.sender, self.receivers,self.msg.as_string())
            print("邮件发送成功")

        except smtplib.SMTPException as msg:
            print(msg)
            print("Error: 无法发送邮件")
Ejemplo n.º 12
0
from common.BasePageObject import BasePageObject
from common.readConfig import ReadConfig
from time import sleep
from selenium.webdriver.common.by import By

url = ReadConfig().get_config('HTTP', "baseurl")
print('url:%s' % url)


class LoginPage(BasePageObject):
    # BasePage().get_open("https://h5-qa.admin.yuedaowang.com/#/login")

    def login(self, user, pwd):
        self.driver.get("https://h5-qa.admin.yuedaowang.com/#/login")
        eles = self.driver.find_elements(By.CSS_SELECTOR,
                                         "div input[name='name']")
        eles[0].send_keys(user)
        eles[1].send_keys(pwd)
        button = self.driver.find_element(By.CSS_SELECTOR,
                                          'button[type="button"] span')
        button.click()
        sleep(2)
        logout = self.driver.find_element(By.CSS_SELECTOR, 'button span')
        if logout != "":
            print('登录成功')
        self.driver.close()


if __name__ == '__main__':
    loginPage = LoginPage()
    loginPage.login('nxk', '123')
Ejemplo n.º 13
0
        nrows = self.table.nrows
        for i in range(nrows):
            val = self.rowlist(i)[1:]
            if len(val) == 1:
                 d[col[i]] = val[0]
            else:
                d[col[i]] = val
        return d

    # 已列表的形式按行返回数据 i~j行的数据(字典形式)
    def readaslitbyrow(self, i, j):
        l = []
        s = self.rowlist(i)
        e = self.rowlist(j)
        for i in range(1, len(s)):
            d = {s[0]: s[i], e[0]: e[i]}
            l.append(d)
        return l

if __name__=="__main__":
    config = ReadConfig()
    excel_path = os.path.join(config.get_excel("path"), "login_data.xlsx")
    excel = ExcelUtil(excel_path, "帐号")
    username = excel.rowlist(1)[0]
    print(username)
    paw = excel.rowlist(1)[1]
    print(paw)
    # print(excel.readasdict())


Ejemplo n.º 14
0
class ReadCase:
    def __init__(self,excel_name,sheet_name):
        self.excel_name = excel_name
        self.sheet_name = sheet_name
        self.readConfig = ReadConfig()
        self.readExcel = ReadExcel(excel_name,sheet_name)

    def set_excel_name(self,excel_name):
        self.excel_name = excel_name
    def set_sheet_name(self,sheet_name):
        self.sheet_name = sheet_name
    def get_sheet_name(self):
        return  self.sheet_name
    def get_excel_name(self):
        return self.excel_name
    # 根据用例名称获取接口地址,协议+host+port+path
    def get_interface_url(self,case_name,no_online=True,is_serv=True):
        if no_online and is_serv:
            try:
                new_url = self.readConfig.get_service_dev('scheme') + '://' + self.readConfig.get_service_dev(
                    'host') + ':' + self.readConfig.get_service_dev(
                    'port') + self.get_path(case_name)
                return new_url
            except Exception as e:
                print(e)
                print("线上服务用例名称不存在或输入错误,请检查")
        elif no_online and is_serv==False:
            try:
                new_url = self.readConfig.get_h5app_dev('scheme') + '://' + self.readConfig.get_h5app_dev(
                    'host') + ':' + self.readConfig.get_h5app_dev(
                    'port') + self.get_path(case_name)
                return new_url
            except Exception as e:
                print(e)
                print("线上h5app用例名称不存在或输入错误,请检查")
        elif no_online==False and is_serv:
            try:
                new_url = self.readConfig.get_service_online('scheme') + '://' + self.readConfig.get_service_online(
                    'host') + ':' + self.readConfig.get_service_online('port') + self.get_path(case_name)
                return new_url
            except Exception as e:
                print(e)
                print("dev服务用例名称不存在或输入错误,请检查")
        elif no_online==False and is_serv==False:
            try:
                new_url = self.readConfig.get_h5app_online('scheme') + '://' + self.readConfig.get_h5app_online(
                    'host') + ':' + self.readConfig.get_h5app_online('port') + self.get_path(case_name)
                return new_url
            except Exception as e:
                print(e)
                print("dev服务用例名称不存在或输入错误,请检查")
        else:
            print('未知错误')

    # def get_interface_url(self, case_name, is_online=True):
    #         if is_online:
    #             try:
    #                 new_url = self.readConfig.get_h5app_dev('scheme') + '://' + self.readConfig.get_h5app_dev('host') + ":" + self.readConfig.get_h5app_dev('port') + self.get_path(case_name)
    #                 # print(new_url)
    #                 return new_url
    #             except Exception as e:
    #                 print(e)
    #                 print("用例名称不存在2,或输入错误,请检查!!!")
    #         else:
    #             try:
    #                 new_url = self.readConfig.get_http('scheme') + '://' + self.readConfig.get_http('host') + ":" + self.readConfig.get_http('port') + self.get_path(case_name)
    #                 return new_url
    #             except Exception as e:
    #                 print(e)
    #                 print("用例名称不存在1,或输入错误,请检查!!!")

    def get_interface_data(self,case_name):
        try:
            for i in range(0,self.readExcel.nrows):
                row_value = self.readExcel.get_excel()[i][0]
                if case_name ==row_value:
                    return self.readExcel.get_excel()[i][2]
        except Exception as e:
            print(e)
            print("data对应用例名称不存在,或输入错误,请检查")
    def get_interface_headers(self,case_name):
        try:
            for i in range(0,self.readExcel.nrows):
                row_value = self.readExcel.get_excel()[i][0]
                if case_name == row_value:
                    headers = self.readExcel.get_excel()[i][3]
                    headers_dict = json.loads(headers)
                    return headers_dict
        except Exception as e:
            print(e)
            print("Headers不存在或输入错误,请检查")
#     根据用例名称返回这个用例所对应的path路径
    def get_path(self,case_name):
        for i in range(0,self.readExcel.nrows-1):
            row_value = self.readExcel.get_excel()[i][0]
            if case_name == row_value:
                return self.readExcel.get_excel()[i][1]
    def get_method(self,case_name):
        try:
            for i in range(0,self.readExcel.nrows):
                row_value = self.readExcel.get_excel()[i][0]
                if case_name == row_value:
                    return self.readExcel.get_excel()[i][4]
        except Exception as e:
            print(e)
            print("method对应用例名称不存在或输入错误,请检查")
Ejemplo n.º 15
0
 def __init__(self,excel_name,sheet_name):
     self.excel_name = excel_name
     self.sheet_name = sheet_name
     self.readConfig = ReadConfig()
     self.readExcel = ReadExcel(excel_name,sheet_name)
Ejemplo n.º 16
0
 def set_url(self):
     self.url = ReadConfig(config_file).get_baseurl()
     self.optocal = ReadConfig(config_file).get_protocol()
     self.httpurl = self.optocal + "://" + self.url + self.path
     return self.httpurl
Ejemplo n.º 17
0
    att = MIMEText(open(report_file, "rb").read(), "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment; filename= "report.html"'
    msg.attach(att)
    try:
        smtp = smtplib.SMTP_SSL(smtp_server, port)
    except:
        smtp = smtplib.SMTP()
        smtp.connect(smtp_server, port)
    # 用户名密码
    smtp.login(sender, psw)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    print('test report email has send out !')


if __name__ == '__main__':
    all_case = add_case()  # 加载用例
    run_case(all_case)  # 执行用例
    report_path = os.path.join(cur_path, "report")
    report_file = get_report_file(report_path)  # 获取最新的测试报告
    # 邮箱配置
    readConfig = ReadConfig()
    sender = readConfig.get_email_qq("sender")
    psw = readConfig.get_email_qq("psw")
    smtp_server = readConfig.get_email_qq("smtp_server")
    port = readConfig.get_email_qq("port")
    receiver = readConfig.get_email_qq("receiver")
    receiver_list = receiver.split(",")  # 将字符串转化成list列表
    send_mail(sender, psw, receiver_list, smtp_server, report_file,
              port)  # 发送邮件
Ejemplo n.º 18
0
class ReadCase:
    def __init__(self, excle_name, sheet_name):
        self.excle_name = excle_name
        self.sheet_name = sheet_name
        self.readConfig = ReadConfig()
        self.readExcle = ReadExcle(excle_name, sheet_name)

    def set_excle_name(self, excle_name):
        self.excle_name = excle_name

    def set_sheet_name(self, sheet_name):
        self.sheet_name = sheet_name

    def get_sheet_name(self):
        return self.sheet_name

    def get_excle_name(self):
        return self.excle_name

    """根据用例名称获取接口地址 , 协议 +host + port + path"""

    def get_interface_url(self, case_name, is_online=True):
        if is_online:
            try:
                new_url = self.readConfig.get_ml_h5app(
                    'scheme') + '://' + self.readConfig.get_ml_h5app(
                        'host') + ":" + self.readConfig.get_ml_h5app(
                            'port') + self.get_path(case_name)
                return new_url
            except Exception as e:
                print(e)
                print("用例名称不存在2,或输入错误,请检查!!!")
        else:
            try:
                new_url = self.readConfig.get_http(
                    'scheme') + '://' + self.readConfig.get_http(
                        'host') + ":" + self.readConfig.get_http(
                            'port') + self.get_path(case_name)
                return new_url
            except Exception as e:
                print(e)
                print("用例名称不存在1,或输入错误,请检查!!!")

    def get_interface_data(self, case_name):
        try:
            for i in range(0, self.readExcle.nrows):
                row_value = self.readExcle.get_excle()[i][0]
                if case_name == row_value:
                    return self.readExcle.get_excle()[i][2]
        except Exception as e:
            print(e)
            print("data对应用例名称不存在,或输入错误,请检查!!!")

    def get_intetface_headers(self, case_name):
        try:
            for i in range(0, self.readExcle.nrows):
                row_value = self.readExcle.get_excle()[i][0]
                if case_name == row_value:
                    headers = self.readExcle.get_excle()[i][3]
                    headers_dict = json.loads(headers)
                    return headers_dict
        except Exception as e:
            print(e)
            print("Headers用例名称不存在,或输入错误,请检查!!!")

    """根据用例名称返回这个用例所对应的path路径"""

    def get_path(self, case_name):
        for i in range(0, self.readExcle.nrows - 1):
            row_value = self.readExcle.get_excle()[i][0]
            if case_name == row_value:
                return self.readExcle.get_excle()[i][1]

    def get_method(self, case_name):
        try:
            for i in range(0, self.readExcle.nrows):
                row_value = self.readExcle.get_excle()[i][0]
                if case_name == row_value:
                    return self.readExcle.get_excle()[i][4]
        except Exception as e:
            print(e)
            print("Method对应用例名称不存在,或输入错误,请检查!!!")
Ejemplo n.º 19
0
    4-结果写入到excel
'''
from common.readExcel import readExcel
import requests
import json
import unittest
from ddt import ddt, data, unpack
from common.configHttp import ConfigHttp
from common.readConfig import ReadConfig
# from common.writeExcel import WriteExcel
from common.writeExcel import WriteExcel

#python编写测试用例必须继承unittest.TestCase
re = readExcel()
test_data = re.read()
rc = ReadConfig()
wr = WriteExcel()


@ddt
class testCase(unittest.TestCase):
    # 1 - 调用readExcel模块,获取测试数据
    #
    #     def setUp(self) -> None:
    #         re = readExcel()
    #         self.test_data = re.read()

    @data(*test_data)
    @unpack
    def testRun(self, id, urlstr, name, method, param, expect, real, status):
        header = {'User-Agent': 'Mozilla/6.0'}
Ejemplo n.º 20
0
class SendMail():

    re = ReadConfig()
    #配置SMTP属性
    host = re.get_email('mail_host')
    username = re.get_email('mail_user')
    pwd = re.get_email('mail_pass')

    #配置邮件发送属性
    sender = re.get_email('sender')
    receiver = re.get_email('receiver')
    subject = re.get_email('subject')
    content = re.get_email('content')

    # 发送html格式邮件
    msg = MIMEMultipart()

    # 配置附件的属性
    def config_file(self):

        # 调用获取最新文件的方法
        file = self.find_new_file()
        # 添加附件,并打开文件
        f = open(file, 'rb')
        mail_body = f.read()

        # 创建消息对象
        filemsg = MIMEText(mail_body, 'plain', 'utf-8')
        # print(filemsg)

        filemsg["Content-Type"] = 'application/octet-stream'
        filemsg["Content-Disposition"] = 'attachment; filename=report.html'

        self.msg.attach(filemsg)

        self.msg['From'] = self.sender
        self.msg['To'] = self.receiver
        self.msg['subject'] = 'UI自动化测试报告'
        self.msg.attach(MIMEText('附件为UI自动化测试报告,请查收', 'plain', 'utf-8'))

    def send_email(self):

        self.config_file()

        try:
            # 创建一个 SMTP() 对象
            r = smtplib.SMTP()
            # 通过 connect 方法连接 smtp 主机
            r.connect(host=self.host)
            # 邮箱账号登录校验
            r.login(user=self.username, password=self.pwd)
            # 发送邮件
            r.sendmail(self.sender, self.receiver, self.msg.as_string())
            print('邮件发送成功')

        except Exception as msg:
            print('邮件发送失败', msg)
        finally:
            r.close()

    # 查找最新的文件
    def find_new_file(self):
        # 获取当前路径
        current_path = os.path.dirname(os.path.abspath(__file__))
        print('---current', current_path)

        # 获取报告的存放路径
        filePath = os.path.dirname(current_path) + '/' + 'report'
        fileList = os.listdir(filePath)
        #print(fileList)

        fileList = os.listdir(filePath)

        # 定义一个字典来接收文件的路径及文件名
        fileDict = {}
        # 定义一个列表来接收文件的时间
        fileTime = []

        #查找这个文件列表中每个文件的路径及文件名
        for iName in fileList:
            # 拼接文件路径和文件名
            filename = filePath + "/" + iName

            # 获取该文件的修改时间
            iTime = os.path.getmtime(filename)
            print(iTime)
            # 将文件的修改时间追加到时间列表中
            fileTime.append(iTime)
            # 将文件名iName作为字典的value,文件的修改时间iTime作为字典的key存入
            fileDict[iTime] = iName
            # fileD现在是空字典,把文件名和时间以键值对形式填充
        # print(fileDict, fileTime)

        # 查找时间列表中最新的文件
        sendfilekey = max(fileTime)

        #  把这个时间对应的文件名找出来,通过key查找value
        sendfile = fileDict[sendfilekey]
        # print(sendfile)
        sendfile = filePath + "/" + sendfile
        return sendfile
Ejemplo n.º 21
0
class ConfigEmail():
    # 读取ini文件配置属性
    r = ReadConfig()
    mail_host = r.get_email('mail_host')
    # 配置第三方SMTP服务
    mail_host1 = "smtp.126.com"  # 设置服务器
    mail_user = r.get_email('mail_user')  # 用户名

    mail_pass = r.get_email('mail_pass')  # 口令

    # 配置邮件属性
    sender = r.get_email('sender')
    receivers = r.get_email('receiver')
    content = r.get_email('content')
    msg = MIMEMultipart()

    def config_file(self):
        # 配置附件属性
        file = self.find_file()
        print(file)
        sendfile = open(file, 'rb').read()
        att = MIMEText(sendfile, 'plain', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        att["Content-Disposition"] = 'attachment; filename=report.html'
        self.msg.attach(att)
        self.msg['From'] = self.sender
        self.msg['To'] = self.receivers
        self.msg['Subject'] = Header('Python自动化测试报告', 'utf-8')
        self.msg.attach(MIMEText('这是接口自动化报告邮件,如果想查看详情请查收附件', 'plain', 'utf-8'))

    def find_file(self):
        '''查找最新文件'''
        # 获取当前路径
        current_path = os.path.dirname(os.path.abspath(__file__))
        # print('current',current_path)
        # 获取报告的存放路径
        filePath = os.path.dirname(current_path) + "/" + 'report'
        # print('filepath',filePath)

        # 获取filepath路径下全部文件名称的列表
        fileList = os.listdir(filePath)
        # print(fileList)

        fileDict = {}
        fileTime = []

        for iName in fileList:
            # 拼接文件路径和i-文件名
            filename = filePath + "/" + iName
            # 获取该文件的修改时间
            iTime = os.path.getmtime(filename)
            # 将该文件的修改时间追加到时间列表中
            fileTime.append(iTime)
            # 将文件名iname作为字典的value,文件的修改时间iTime作为字典的key存入
            fileDict[iTime] = iName
        # print(fileDict,fileTime)

        sendfilekey = max(fileTime)
        sendfile = fileDict[sendfilekey]
        # rint(sendfile)
        sendfile = filePath + "/" + sendfile

        return sendfile

        # 发送邮件

    def send_mail(self):
        self.config_file()

        s = smtplib.SMTP()

        # print(self.mail_host,self.mail_user,self.mail_pass,self.sender,self.receivers,self.message.as_string)
        s.connect(self.mail_host, 25)  # 25 为 SMTP 端口号
        # s.set_debuglevel(1)
        s.login(self.mail_user, self.mail_pass)
        s.sendmail(self.sender, self.receivers, self.msg.as_string())
        print("邮件发送成功")
Ejemplo n.º 22
0
class ConfigEmail():

    r = ReadConfig()
    mail_host = r.get_eamil("mail_host")  #smtp服务
    mail_user = r.get_eamil("mail_user")  #用户名
    mail_pass = r.get_eamil("mail_pass")  #口令
    sender = r.get_eamil("sender")  #发送者
    receivers = r.get_eamil("receiver")  #接收者
    content = r.get_eamil("content")  #发送内容
    print(content)

    msg = MIMEMultipart()

    def config_file(self):
        #配置附件属性
        file = self.find_file()
        print(file)
        mail_body = open(file, "rb").read()
        #设置附件名字
        self.title = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime())
        att = MIMEText(mail_body, "base64", "utf-8")
        att["Content-Type"] = "application/octet-stream"
        att["Content-Disposition"] = "attachment;filename={}".format(
            self.title)
        self.msg.attach(att)

        #邮件正文内容
        self.msg["from"] = self.sender
        self.msg["To"] = self.receivers
        self.msg["Subject"] = Header(self.content, "utf-8")
        self.msg.attach(MIMEText("这是接口自动化报告邮件,如果想查看详情请查收"))

    def find_file(self):
        #查找最新文件
        #current_path = os.path.dirname(os.path.abspath(__file__))
        # print("文件路径",current_path)
        #filePath = os.path.dirname(os.getcwd()) + "\\" + "testReport"
        filePath = os.getcwd() + "\\" + "testReport"

        print(filePath)

        #获取filepath路径下全部文件名称的列表
        fileList = os.listdir(filePath)

        fileDoct = {}
        fileTime = []

        for iName in fileList:
            #拼接文件路径-文件名
            filename = filePath + "\\" + iName
            #获取文件修改时间
            iTime = os.path.getatime(filename)
            fileTime.append(iTime)
            fileDoct[iTime] = iName
        sendfilekey = max(fileTime)
        sendfile = fileDoct[sendfilekey]
        sendfile = filePath + "\\" + sendfile
        return sendfile

    def send_mail(self):
        self.config_file()
        try:
            s = smtplib.SMTP()
            s.connect(self.mail_host, 25)
            s.login(self.mail_user, self.mail_pass)
            s.sendmail(self.sender, self.receivers, self.msg.as_string())
            print("邮件发送成功")
        except smtplib.SMTPException as msg:
            print("Error:无法发送邮件")
Ejemplo n.º 23
0
    def read_config(cls, section, path=None):
        instance = cls.__new__(cls)

        parser = ReadConfig(path)
        parser.update_attr(instance, section)
        return instance
Ejemplo n.º 24
0
from PageLocators.LoginLocators import LoginLocator
from common.BasePageObject import BasePageObject
from common.readConfig import ReadConfig

baseurl = ReadConfig().get_config('HTTP', 'baseurl')
print(baseurl)


class LoginObject(BasePageObject):
    def login(self, user, pwd):
        self.driver.get_open(baseurl)
        eles = self.driver.find_elements(LoginLocator.eles)
        eles[0].send_keys(user)
        eles[1].send_keys(pwd)
        self.driver.click(LoginLocator.button)
        self.driver.implicitly_wait(10)
        logout = self.driver.find_element(LoginLocator.logout)
        if logout != "":
            print('登录成功')
        else:
            print('登录失败')


if __name__ == '__main__':
    login = LoginObject()
    login.login('nxk', '123')