1. 程式人生 > >Robotframework 入門教程(六)

Robotframework 入門教程(六)

== resource&Library ==

在Setting表裡使用Resource匯入檔案,resource檔案語法和testcase語法大部分相同只是沒有Test Cases表。支援多種檔案格式,為了和testcae區分開,這裡就用txt。新建pub.txt如下:
*** Settings ***
[Documentation]    demo resource

*** Variables ***
${var1}           value
@{list1}          a    b    c    d
&{dict1}          key1=sf    key2=${list1}

*** Keywords ***
Calculate and Check Equals
    [Arguments]    ${expression}=3+3    ${expected}=${6}
    ${res}    Evaluate    ${expression}
    Log to console    expression = ${expression}
    Log to console    result = ${res}
    Should Be Equal    ${res}    ${expected}

Varargs keyword
    [Arguments]    @{args}
    Log to console    --------
    : FOR    ${item}    IN    @{args}
    \    Log to console    ${item}

Kwargs keyword
    [Arguments]    &{kwargs}
    Log to console    --------
    : FOR    ${item}    IN    @{kwargs.items()}
    \    Log to console    ${item}

Calculate "${expression}" and Check Equals "${expected}"
    Calculate and Check Equals    ${expression}    ${expected}
在demo.robot匯入該resource檔案,裡面的關鍵字和變數就可以直接使用了,修改demo.robot如下;
*** Settings ***
Documentation     Example test cases using the keyword-driven testing approach.
Resource          pub.txt

*** Test Cases ***
First Case
    [Documentation]    variable type
    Log to console    ${var1}
    Log to console    ${list1}[0]
    Log to console    ${list1[0]}
    Log to console    ${dict1}['key1']
    Log to console    ${dict1['key1']}
    Log to console    ${dict1.key1}

Second Case
    [Documentation]    Default values with user-keywords
    Calculate and Check Equals
    Calculate and Check Equals    1+5
    Calculate and Check Equals    7-2    ${5}
    Calculate and Check Equals    expression=6+3    expected=${9}

Third Case
    [Documentation]    Varargs with user-keywords
    Varargs keyword    a    f    ${var1}
    Varargs keyword    @{list1}    ${var1}
    Kwargs keyword    key1=value1    key2=789
    Kwargs keyword    &{dict1}
    Kwargs keyword    &{dict1}    mykey=tututu    &{dict1}

Fourth Case
    [Documentation]    data-driven case
    [Template]    Calculate "${expression}" and Check Equals "${expected}"
    2+4    ${6}
    9-2    ${7}
    6*4    ${24}

Fifth Case
    [Documentation]    builtIn library
    ${item}    Get Dictionary Keys    ${dict1}
    Log to console    ${item}
匯入Library在Setting表裡使用Library關鍵字。加入一行 “Library           Collections”,引入了庫Collections,其提供的關鍵字就可以直接使用了。
*** Settings ***
Documentation     Example test cases using the keyword-driven testing approach.
Resource          pub.txt
Library           Collections
testcase表中加入一條case呼叫Collections中的 Get Dictionary Keys。
*** Test Cases ***
Fifth Case
    ${item}    Get Dictionary Keys    ${dict1}
    log    ${item}