Python 3.6 + robotFramework automation framework environment construction, study notes

content

 1. Environment Construction

1. Install the relevant libraries

2.pycharm

3.IntelliBot 

4.pycharm configuration executor

5.fireFox browser and corresponding driver

Second, use cmd to execute

3. Basic syntax of case script (.robot file)

1. Basic grammar

2. Call the custom library in the robot file

Fourth, use the SeleniumLibrary library for web interface automation testing

5. Data-driven testing

 1. Environment Construction

Overview: win 7+ python 3.6 + pycharm +  robotframework  + IntelliBot + fireFox

1. Install the relevant libraries

It is recommended to use pip to install, such as pip install robotframework (and selenium2library).
The R&D environment does not have an external network. It is installed offline. After downloading the package, decompress it -- enter -- python setup.py install
(1) WEB page test:
https://pypi. python.org/pypi/robotframework
https://pypi.python.org/pypi/selenium#downloads #Dependency package
https://pypi.python.org/pypi/robotframework-seleniumlibrary #Dependency package
https://pypi.python .org/pypi/robotframework-selenium2library
(2) Interface test:
Online: pip install requests
Offline:
https://pypi.python.org/pypi/certifi #Dependency package
https://pypi.python.org/pypi/urllib3 #downloads #dependent packagehttps://pypi.python.org/pypi/idna#downloads #dependent
package
https://pypi.python.org/pypi/chardet/#downloads #dependency package
https://pypi.python.org/pypi/requests#downloads


2.pycharm

Development IDE, slightly


3.IntelliBot 

pycharm development plugin [syntax highlighting]
Method 1: pycharm>File>setting>Plugins>Browse reponsitories
Method 2: https://plugins.jetbrains.com/plugin/7386-intellibot Download to local
pycharm>File>setting>Plugins> install plugin from disk


4.pycharm configuration executor


File>setting>Tools>External tool, after the configuration is complete, you can choose to use this executor in the .robot file to execute

Parameters: current file path

Working directory: working path, log, result output, etc., as follows:

Note: log.html execution log

  output.xml executes the xml of relevant information, which can be used for subsequent secondary parsing 

  report.xml execution result report

5.fireFox browser and corresponding driver

(1) Browser

https://www.mozilla.org/zh-CN/firefox/developer/

(2) Drive

https://github.com/mozilla/geckodriver/releases/download/v0.19.1/geckodriver-v0.19.1-win64.zip

Unzip (geckodriver.exe) and copy it to the python installation directory


Second, use cmd to execute

Run a test case:
pybot --test test_case test_suit.robot

Run the specified file:
pybot test_suit.robot

Run the test file with the suffix .robot in the current directory
pybot *.robot

Run all test cases in the current testpath directory
pybot testpath


3. Basic syntax of case script (.robot file)

1. Basic grammar

*** Settings ***
Library     MyLib                                          #导入自定义的库
Library     SeleniumLibrary

*** Test Cases ***
                                                            #第一行为固定格式,标识
                                                            #建议同python一致,使用tab缩进对齐(pycharm中设置tab=4空格),否则可能报执行失败,报 "Test case contains no keywords"
case1 helloworld                                            #案例名
    log     chenyuebai first rfw case                        #log 相当于python的print,可在生成的log.xml中查看

case 2 log                                                  #打异常日志,支持多种级别
    log     test line 2     ERROR

case 3 varible
    ${myname}     Set variable        chen                  #定义变量
    log     my name is ${myname}                            #使用变量

#case 4 use varible                                         #变量作用域为其定义所在的案例(case3),否则报"Variable '${myname}' not found."
#    log     ${myname}

case 5 Catenate
    ${hi1}    Catenate      hello    world                  #定义变量方式2  连接两个对象,支持自定义连接符
    log    ${hi1}
    ${hi2}    Catenate      SEPARATOR=----  hello    world
    log    ${hi2}

case 6 list
    @{mylist}       create list     a       b      c        #定义列表
    log many        @{mylist}                               #打印列表中的元素

case 7 get time
    ${currentTime}      get time                            #获取当前时间     2018-01-02 18:05:47
    log     ${currentTime}
    ${currentYear}      get time    format=year             #支持多种传参,详情看函数定义
    log     current year is ${currentYear}

case 8 sleep
    log     get time
    sleep   1                                               #睡眠,等同于python的time.sleep(5)
    log     get time

case 9 if
    ${score}    set variable    55
    run keyword if    ${score}>=90    log    优秀
    ...    ELSE IF    ${score}>=70    log    良好           #ELSE/ELSE IF要大写。。。语法很蛋疼。。为啥不直接套用python的语法。。
    ...    ELSE    log    很差                              # ... 不知道基于什么考虑的。。看起来像是标识属于“run keyword if”这个判断逻辑;类似python的tab?

case 10 for                                                 #for循环,注意需要使用\来标识这个for循环范围,感觉和上面的...类似
    :FOR    ${i}    IN RANGE    5                           #   for in in range(5):
    \   log    ${i}                                         #        print(i)

case 11 allround the list
    @{myList}    create list  1    2    3    4              # myList = [1,2,3,4]
    :FOR    ${i}    IN    @{myList}                         # for i in myList:
    \   log    ${i}                                         #  print(i)

case 12 Evauate                                             #调用python中的方法,很强大
    ${randomNum}    EVALUATE    random.random()     random  #变量    关键字EVALUATE    调用python的方法    方法所在的库名
    log    ${randomNum}

case 13 call my python                                      #导入自定义库,下面有详细说明
    ${nowTime}    get current time
    log    ${nowTime}

case 14 Comment
    log     start
    #line 1
    comment  line 2                                         #标明注释:使用关键字或者#均可
    log     end


case 15 Selenium2Library                      #Selenium2Library库,操作浏览器,可作web界面自动化,待细化
    open_browser    http://www.baidu.com    firefox
    Input text    id=kw    陈月白
    click button    id=su
    sleep       3
    close Browser

2. Call the custom library in the robot file

Selenium2Library provides many methods, but there are still some scenarios that need to be written by themselves in actual use. RobotFramework supports importing user-defined libraries.

Pay attention to the correspondence between the file name and the class name, otherwise the import library will fail;

Under ...\python installation path\Lib\site-packages:

(1) The file where the custom method is located: MyKeywords.py

import time
class MyKeywords():
    def __init__(self):
        pass


    #获取当前时间
    def get_current_time(self):
        current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        return current_time

(2) Create __init__.py

"""
继承自定义库中的类,rfw会解析类中的函数作为关键词
"""
from .MyKeywords import *

class MyRobotFwkLib(MyKeywords):
    ROBOT_LIBRARY_SCOPE = "GLOBAL"
(3) The .robot file imports the custom class, and you can use the methods in the class
*** Settings ***
Library     MyRobotFwkLib                                          #导入自定义的库

case 13 call my python 
    ${nowTime}    get current time
    log    ${nowTime}

Fourth , use the SeleniumLibrary library for web interface automation testing

SeleniumLibrary provides many basic keywords, which can basically simulate most of the operations on the browser;

In addition, it also supports the encapsulation of basic keywords into advanced keywords according to business logic (which can be understood as a function, there are examples below);

Supports specifying multiple browsers and operating elements by element identification;

The Firefox plugins I use for positioning element tools: firePath, fireBug , very convenient;

Basic keywords (included in SeleniumLibrary) + advanced keywords (encapsulate basic keywords according to actual business) + keywords in user-defined libraries (with configuration examples above), which can almost meet various business scenarios of most web applications;

ps: During debugging, it is found that many keywords cannot be viewed and defined, which is inconvenient to see usage and parameter transfer, but there is no problem in actual execution;

Looking at the __init__.py of the SeleniumLibrary library, it is determined that most of the keyword libraries involved are inherited from initialization when the execution is started;

So the stupid method is directly introduced in full, and it has no effect at present.

Realize project background login and verification:

*** Settings ***
#方便IDE调试,不添加无法找到关键字定义
Library    browsermanagement
Library    AlertKeywords
Library    BrowserManagementKeywords
Library    CookieKeywords
Library    ElementKeywords
Library    FormElementKeywords
Library    FrameKeywords
Library    JavaScriptKeywords
Library    RunOnFailureKeywords
Library    ScreenshotKeywords
Library    SelectElementKeywords
Library    TableElementKeywords
Library    WaitingKeywords
Library    WindowKeywords

Library     SeleniumLibrary

#配置套件级别的Setup和Teardown
Suite Setup
...     log     now test start 1       #只执行一条

Suite Teardown    Run Keywords
...     close all browsers  AND         #执行多条
...     log     now end 4


#全局变量
*** Variables ***
${loginPageUrl}    http://10.XX.XX.232:9XX0/admin/index.do?index=1
${validUsername}            admin
${validloginPasswd}         adminpasswd


*** Test Cases ***
case 1 correct login test
    #配置用例级别的Setup和Teardown
    [setup]         log     setup log 2
    [teardown]      log     teardown log 3

    correctLoginTest        ${validUsername}        ${validloginPasswd}     #使用基础关键字封装出的高级关键字


#使用基础关键字封装高级关键字,类似python的一个函数,支持入参出参,很灵活
*** Keywords ***
correctLoginTest
    [Arguments]    ${uasename}      ${passwd}
    open browser    ${loginPageUrl}     firefox
    setBrowser
    input text      xpath=html/body/div[1]/form/input[1]    ${uasename}
    input text      xpath=html/body/div[1]/form/input[2]    ${passwd}
    click element   class=submit
    sleep       5
#    ${page1_title}    get title                                     #获取页面title,可后续校验页面是否到达
#    ${width}    ${height}    get window size                        #获取浏览器窗口大小
#    select window    NEW                                    #切换到新弹出窗口(视图焦点)
    page should contain element     xpath=//*[@id='topMenu4']       #系统管理菜单
    sleep       2
    close all browsers


setBrowser
    set window size    1024     768                        #设置浏览器窗口大小
    maximize browser window                                 #浏览器窗口最大化
    sleep  1

5. Data - driven testing

Data-driven testing, suitable for testing with different input combinations under the same process and the same expected results

For example, test abnormal login process, abnormal verification of user name and password under various combinations of wrong (or empty)

example:

*** Settings ***
Library     SeleniumLibrary
Test Template   errorLoginTest      #公共逻辑



*** Variables ***
${loginPageUrl}    http://10.XX.XX.232:9XX0/admin/index.do?index=1
${validUsername}            admin
${validloginPasswd}         adminpasswd



*** Test Cases ***                  username                 passwd
#异常登录测试
case 2:Invalid Username            invalidname              ${validloginPasswd}

case 3:Invalid Password            ${validUsername}         invalidPasswd

case 4:Invalid Both                invalidName              invalidPasswd

case 5:Empty Username              ${EMPTY}                 ${validloginPasswd}

case 6:Empty Password              ${validUsername}         ${EMPTY}

case 7:Empty Both                  ${EMPTY}                 ${EMPTY}



*** Keywords ***
errorLoginTest
    [Arguments]    ${uasename}      ${passwd}
    open browser    ${loginPageUrl}     firefox
    input text      xpath=html/body/div[1]/form/input[1]    ${uasename}
    input text      xpath=html/body/div[1]/form/input[2]    ${passwd}
    click element   class=submit
    sleep     5
    page should contain element        class=submit     5      error:预期应含登录元素未找到【即跳转失败】
    sleep     5
    close all browsers

Results of the:

Guess you like

Origin blog.csdn.net/ZangKang1/article/details/123164859