Robot Framework如何使用C語言編寫測試庫

介紹

這里通過一個簡單的例子,演示如何在Robot Framework 的測試庫中使用C語言。我們使用Python標準庫中的ctypes模塊(對于早期Python版本可能未集成,需要另行安裝),該模塊需要調(diào)用C代碼編寫的共享庫。當前的例子我僅在OSX上實現(xiàn)與測試,對于Unix和Linux平臺大同小異,對于Windows平臺,僅僅需要注意共享庫的格式和調(diào)用方式即可,當前未做其他平臺相關測試。

共享庫

第一步,我們需要編寫C的共享庫。

我們編寫的例子是一個非常簡單的登錄系統(tǒng)(login.c), 通過輸入的用戶名和密碼進行驗證,并返回驗證結果。這里有兩組合法的用戶名密碼組合:demo/mode和john/long.其他組合都是錯誤的。下面是login.c的完整代碼:

/*
Simple system that validates passwords and user names. There are two users in
system with valid user name and password. "demo mode" and "john long". All
other user names are invalid. Except that there are bugs. Can you spot them?
*/

#include <string.h>
#define NR_USERS 2

struct User {
    const char* name;
    const char* password;
};
const struct User VALID_USERS[NR_USERS] = { "john", "long", "demo", "mode" };

int validate_user(const char* name, const char* password) {
    int i;
    for (i = 0; i < NR_USERS; i++) {
        if (0 == strncmp(VALID_USERS[i].name, name, strlen(VALID_USERS[i].name)))
            if (0 == strncmp(VALID_USERS[i].password, password,     strlen(VALID_USERS[i].password)))
                return 1;
    }
     return 0;
}

我們將這個文件編譯成共享庫liblogin.so. 在當前目錄下,我們創(chuàng)建Makefile文件。
Makefile編寫如下:

CC=gcc
SRC=login.c
SO=liblogin.so

$(SO): $(SRC)
    $(CC) -fPIC -shared -o $(SO) $(SRC)

clean:
    rm -f $(SO)

我們在當前目錄執(zhí)行make命令,就創(chuàng)建了共享庫liblogin.so.
后面我們將介紹如何編寫Robot Framework測試庫來調(diào)用我們的C共享庫。

測試庫

在這里,我們按照Robot框架的規(guī)范,來編寫測試庫LoginLibrary.py. LoginLibrary是一個簡單的測試庫,通過ctypes模塊來與底層的C共享庫進行交互。我們這個庫僅僅提供了一個關鍵字就是 Check User.

下面是LoginLibrary.py的完整代碼:

"""Robot Framework test library example that calls C code.

This example uses Python's standard `ctypes` module, which requires
that the C code is compiled into a shared library.

It is also possible to execute this file from the command line 
to test the C code manually.
"""

from ctypes import CDLL, c_char_p

LIBRARY = CDLL('./liblogin.so')  # On Windows we'd use '.dll'


def check_user(username, password):
    """Validates user name and password using imported shared C library."""
    if not LIBRARY.validate_user(c_char_p(username), c_char_p(password)):
        raise AssertionError('Wrong username/password combination')


if __name__ == '__main__':
    import sys
    try:
        check_user(*sys.argv[1:])
    except TypeError:
        print 'Usage:  %s username password' % sys.argv[0]
    except AssertionError, err:
        print err
    else:
        print 'Valid password'

if __name__ == '__main__' 語句塊不是用于測試庫的,我們在這里寫是為了方便測試測試庫,我們可以執(zhí)行如下的測試命令:

python LoginLibrary.py demo mode
python LoginLibrary.py demo invalid

來驗證我們的測試庫編寫是否正確,不過對于正式的測試庫,我們需要進行單元測試utest和驗收測試atest.這里就不做過多介紹了。編寫好測試庫以后,我們就可以利用測試庫提供的關鍵字編寫用例了。

測試用例

我們按照Robot框架的規(guī)范,編寫測試用例login_tests.robot, 用例完整代碼如下所示:

*** Settings ***
Library           LoginLibrary.py

*** Test Case ***
Validate Users
    [Template]    Check Valid User
    johns    long
    demo     mode

Login With Invalid User Should Fail
    [Template]    Check Invalid User
    de          mo
    invalid     invalid
    long        invalid
    ${EMPTY}    ${EMPTY}

*** Keyword ***
Check Valid User
    [Arguments]    ${username}    ${password}
    Check User    ${username}    ${password}

Check Invalid User
    [Arguments]    ${username}    ${password}
    Run Keyword And Expect Error    Wrong username/password combination    Check    User    ${username}    ${password}

我們的測試集包含了所有的測試情況,包括獨立的有效登錄測試和無效登錄測試。
注意,盡管我們的測試用例文件以顯示的.robot擴展結尾,它實際上也是文本文件。我們以.txt結尾,Robot框架同樣可以執(zhí)行。用例編寫完了,我們開始執(zhí)行測試用例。

執(zhí)行測試

首先要確保已經(jīng)安裝了Robot Framework了,這里我就不介紹怎么安裝了,相信大家應該都安裝成功了。通過pybot --version查看即可。

我們在控制臺上輸入如下命令,執(zhí)行測試:

>pybot login_tests.robot

pybot命令有很多參數(shù)可選,這里為了方便,我們就選用默認即可。

執(zhí)行結果如下:

==============================================================================
Login Tests                                                                   
==============================================================================
Validate Users                                                        | PASS |
------------------------------------------------------------------------------
Login With Invalid User Should Fail                                   | PASS |
------------------------------------------------------------------------------
Login Tests                                                           | PASS |
2 critical tests, 2 passed, 0 failed
2 tests total, 2 passed, 0 failed
==============================================================================
Output:  ../output.xml
Log:     ../log.html
Report:  ../report.html

通過查看輸出的html日志和報告文件,我們可以查看用例的執(zhí)行情況。

至此,我們就簡單的介紹完了如何在Robot Framework測試庫中調(diào)用C庫的用法。

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容