• Jenkins下构建UI自动化之初体验


    一、缘 起

    笔者之前一直在Windows环境下编写UI自动化测试脚本,近日在看《京东系统质量保障技术实战》一书中,萌生出在jenkins下构建UI自动化测试的想法

    二、思 路

    首先,在Linux环境搭建jenkins平台
    然后,将脚本上传至Linux服务器
    最后,在jenkins平台构建自动化任务

    三、说 明

    • Linux环境,Centos7 64位 虚拟机
    • JDK1.8 + jenkins 2.121.2
    • Python3.6 + Selenium 2.5.3 + Phantomjs 2.1.1
    • 注意:
      1. Centos7下默认的Python版本为2.7.5,安装Python3的方法:Centos7:5分钟安装python3.5 并存python2.7,兼容yum及Gnome
      2. Centos7下默认不带pip命令,安装Selenium需要用到pip命令,安装方法:Centos7:3分钟安装pip3
      3. Linux服务器通常为无界面状态,安装浏览器跑UI自动化脚本是不太可能的,解决方法就是用无头浏览器(phantomjs)来代替,何为无头浏览器请读者自行百度,值得注意的是Selenium3.0之后不再支持Phantomjs,故为了在不安装浏览器情况下运行UI自动化脚本,就得安装Selenium3.0之前的版本
      selenium与phantomjs分离

    四、搭 建

    1. 搭建jenkins平台,详细教程请自行百度,主要步骤如下
    # 下载jenkins.war包
    wget http://mirrors.jenkins.io/war-stable/latest/jenkins.war
    # 直接用java起war包即可
    (nohup)java -jar jenkins.war (port=8090)
    # nohup 后台运行,port为指定jenkins端口,默认为8080
    
    # 运行起来后,在浏览器输入:http://localhost:808/即可访问jenkins平台
    

    jenkins平台
    2. Selenium + Phantomjs

    # 安装selenium
    pip install selenium==2.53.6
    # 检查
    pip show selenium
    >> Name: selenium
    >> Version: 2.53.6
    >> Summary: Python bindings for Selenium
    >> Home-page: https://github.com/SeleniumHQ/selenium/
    
    # 下载phantomjs
    mkdir /usr/local/phantomjs/
    wget  https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
    # 解压
    tar -jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2
    # 链接
    ln -s /usr/local/phantomjs/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /user/bin/phantosjs
    # 检查
    phantomjs -v
    >> 2.1.1
    
    1. 脚本说明
    • testBaiduProj
      testBaiduProj 脚本结构
    • baidu.py: 打开百度,输入Python搜索,并截图
    #!/usr/bin/python
    # coding=utf-8
    from selenium import webdriver
    from time import sleep
    import time, os
    
    cur_path = os.path.dirname(__file__)
    url = 'http://www.baidu.com'
    driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1'])
    # driver = webdriver.Firefox()
    driver.get(url)
    driver.find_element_by_name("wd").send_keys("Python")
    driver.find_element_by_xpath("//*[@id='su']").submit()
    sleep(2)
    
    assert driver.title == 'Python_百度搜索', 'title错误'
    cur_time = time.strftime('%Y-%m-%-d %H_%M_%S')
    fp = cur_path + '/pic/'
    driver.get_screenshot_as_file(r'./pic/' + cur_time + ' image.png')
    sleep(1)
    driver.quit()
    print('完成!')
    
    • sendAttEmail.py: 查找最新的一个png截图,自动发邮件
    #!/usr/bin/python
    #coding=utf-8
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.header import Header
    import datetime
    import os
    import time
    
    def send_att_mail(username, passwd, recv, title, content, fp, mail_host='mail.xxx.com'):
        """
        自动发邮件
        :param username:
        :param passwd:
        :param recv:
        :param title:
        :param content:
        :parm fp:
        :param mail_host:
        :return:
        """
        msg = MIMEMultipart()
        msg['Subject'] = Header(title, 'utf-8')
        msg['From'] = username + "@xxx.com"
        msg['To'] = ';'.join(recv)
        # msg['Cc'] = ','.join(cc_recv)   # 抄送
        # 邮件正文
        msg.attach(MIMEText(content, 'html', 'utf-8'))    # 文本'plain', HTML为'html'
        # 构造附件
        att = MIMEText(open(fp, 'rb').read(), 'base64', 'utf-8')
        att['Content-Type'] = 'application/octet-stream'
        att.add_header('Content-Disposition', 'attachment', filename=('%s' % fp.split('/')[-1]))
        # encoders.encode_base64(att)
        msg.attach(att)
        smtp = smtplib.SMTP()
        smtp.connect(mail_host)
        smtp.starttls()
        smtp.login(username, passwd)
        smtp.sendmail(username + "@xxx.com", recv , msg.as_string())
        smtp.quit()
    
    
    # 邮件内容(文本/HTML)
    content = """
    <p>
    <font size="4" face="SimSun">
    <p>你好,请查收邮件~</p>
    </font>
    </p>
    """.format(start, end, tomorrow)
    # 邮件标题
    title = '百度测试报告'
    
    email_user = '账号'  # 发送者账号
    email_pwd = '密码'  # 发送者密码
    # 接收者邮件列表
    recv_lst = ['xx@xxx.com']
    len(cc_recv_lst)))
    time.sleep(1)
    # 将pic文件夹里面的png文件名称生成list,对列表排序,选择最后一个即为最新一个png截图
    png_lst = os.listdir('./pic')
    png_lst.sort()
    filename = './pic/' + png_lst[-1]
    send_att_mail(email_user, email_pwd, recv_lst, title, content, filename)
    print('邮件发送成功!')
    time.sleep(1)
    

    五、构 建 任 务

    • 构建自由风格项目
    • 填写项目名和说明,其他均为默认选项
    • 构建部分选择 Execute shell,具体脚本如下
    #!/usr/bin/bash
    cd /home/lid/pyproj/testBaiduProj/
    python baidu.py
    sleep 1
    python sendAttEmail.py
    
    • 保存项目,并构建

    构建部分shell脚本

    保存项目,构建中

    • 初步OK,然而 ~ ~ ~

    六、问 题

    1. phantomjs情况下,用.click()方法报错,但是用.submit()方法却正常
    2. phantomjs情况下,find_element_by_id('xx').send_keys('xx'),报同样错误,但是find_element_by_name('xx').send_keys('xx'),却不报错
    Traceback (most recent call last):
      File "baidu.py", line 17, in <module>
        driver.find_element_by_id("su").click()
      File "/usr/local/python3/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 72, in click
        self._execute(Command.CLICK_ELEMENT)
      File "/usr/local/python3/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 461, in _execute
        return self._parent.execute(command, params)
      File "/usr/local/python3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
        self.error_handler.check_response(response)
      File "/usr/local/python3/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
        raise exception_class(message, screen, stacktrace)
    selenium.common.exceptions.ElementNotVisibleException: Message: {"errorMessage":"Element is not currently visible and may not be manipulated","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"81","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:36212","User-Agent":"Python-urllib/3.6"},"httpVersion":"1.1","method":"POST","post":"{"id": ":wdc:1532881699579", "sessionId": "670f3e90-934c-11e8-accd-f1bcf1bf551c"}","url":"/click","urlParsed":{"anchor":"","query":"","file":"click","directory":"/","path":"/click","relative":"/click","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/click","queryKey":{},"chunks":["click"]},"urlOriginal":"/session/670f3e90-934c-11e8-accd-f1bcf1bf551c/element/:wdc:1532881699579/click"}}
    Screenshot: available via screen
    

    七、总 结

    Jenkins下构建UI自动化测试,看似简单,实则里面无数坑,笔者遇到的如:selenium3.0以上不支持phantomjs问题、Linux环境下安装Python3但是输出中文报错问题、在Linux环境下安装pip3命令无效问题、自动发邮件/添加附件问题,等等,只有你亲自尝试一遍,才能体会所有的不起眼都不容被忽视~
    ~
    ~
    ~

    不积跬步,无以至千里

    积跬步,至千里
  • 相关阅读:
    【转】 robotframework(rf)中对时间操作的datetime库常用关键字
    在RobotFramework--RIDE中把日期转化为整型进行运算
    Oracle中date转为timstam可以函数to_timestamp的方式来转化
    Java项目缺少.project文件
    数据库时间戳转换日期(MYSQL数据库)
    spring+struts+mybatis中关于报错org.hibernate.exception.GenericJDBCException: Connection is read-only. Queries leading to data modification are not allowed 的产生原因及解决方案
    新加字段问题(增加联合主键)
    集合问题
    数组面试题
    集合的问题
  • 原文地址:https://www.cnblogs.com/freedomlidi/p/12431343.html
Copyright © 2020-2023  润新知