robotframework测试web接口

robotframework 是一个简单易用的关键字驱动自动化测试框架,我这里用dbank的python的sdk作为目标测试程序简单使用robotframework

Why Robot Framework?

  • Enables easy-to-use tabular syntax for creating test cases in a uniform way.
  • Provides ability to create reusable higher-level keywords from the existing keywords.
  • Provides easy-to-read result reports and logs in HTML format.
  • Is platform and application independent.
  • Provides a simple library API for creating customized test libraries which can be implemented natively with either Python or Java.
  • Provides a command line interface and XML based output files for integration into existing build infrastructure (continuous integration systems).
  • Provides support for Selenium for web testing, Java GUI testing, running processes, Telnet, SSH, and so on.
  • Supports creating data-driven test cases.
  • Has built-in support for variables, practical particularly for testing in different environments.
  • Provides tagging to categorize and select test cases to be executed.
  • Enables easy integration with source control: test suites are just files and directories that can be versioned with the production code.
  • Provides test-case and test-suite -level setup and teardown.
  • The modular architecture supports creating tests even for applications with several diverse interfaces.

首先安装并检测是否成功

pip install robotframework
ciaos@linux-53dr:~/Downloads/python-sdk-0.1> pybot --version
Robot Framework 2.7.6 (Python 2.7.3 on linux2)

修改demo.py为下面的代码(作为目标测试接口,命令行程序)

nspApi.py

#!/usr/bin/env python

from nsp import NSPClient
import sys
import os

def helloworld(uname):
        nsp = NSPClient(****, '***********************');
        svc = nsp.service("nsp.demo")
        ret = svc.helloworld(uname)
        print ret

def lsdir(path):
        nsp = NSPClient('iuTeAN9uaQ6xYuCt8f7uaL4Hwua5CgiU2J0kYJq01KtsA4DY', 'c94f61061b46668c25d377cead92f898');
        svc = nsp.service("nsp.vfs");
        ret = svc.lsdir(path)
        print ret

def help():
    print 'Usage: %s { nsp.demo.helloworld | nsp.vfs.lsdir | help }' \
             % os.path.basename(sys.argv[0])


if __name__ == '__main__':
    actions = {'nsp.demo.helloworld': helloworld, 'nsp.vfs.lsdir': lsdir,
               'help': help}
    try:
        action = sys.argv[1]
    except IndexError:
        action = 'help'
    args = sys.argv[2:]
    try:
        actions[action](*args)
    except (KeyError, TypeError):
        help()

按照robotframework规范编写测试库如下

testLib/NspLibrary.py

#!/usr/bin/env python

import os
import sys

class NspLibrary:

    def __init__(self):
        self._nsp_path = os.path.join(os.path.dirname(__file__),
                                      '..', '.', 'nspApi.py')
        self._status = ''

    def helloworld(self, name):
        self._run_command('nsp.demo.helloworld', name)

    def lsdir(self, path):
        self._run_command('nsp.vfs.lsdir',path)

    def status_should_be(self, expected_status):
        if expected_status != self._status:
            raise AssertionError("Expected status to be '%s' but was '%s'"
                                  % (expected_status, self._status))

    def _run_command(self, command, *args):
        command = '"%s" %s %s' % (self._nsp_path, command, ' '.join(args))
        process = os.popen(command)
        self._status = process.read().strip()
        process.close()

编写测试用例nspTest.tsv(必须以单个分割符\t区分关键字,不然会报错,不能用多个\t或者空格)

*** Settings ***
Library OperatingSystem
Library testLib/NspLibrary.py

*** Variables ***
${NAME} "PJ!"
${RES1} "{'message': 'Hello:PJ!'}"
${LSDIR_RES}    "{'childList': {0: {'type': 'Directory', 'name': 'Netdisk'}, 1: {'type': 'Directory', 'name': 'Syncbox'}, 2: {'type': 'Directory', 'name': 'Recycle'}}}"

*** Test Cases ***
Demo Test       [Tags]  nsp.demo
        [Documentation] Example test
        Helloworld      ${NAME}
        Status should be        ${RES1}

Another Test
        Should Be Equal ${NAME} PJ!

VFS Test        [Tags]  nsp.vfs
        Lsdir   "/"
        Status should be        ${LSDIR_RES}
        Lsdir   "/Netdisk"
        Status should be        "Wrong results"

运行pybot nspTest.tsv,结果如下

ciaos@linux-53dr:~/Downloads/python-sdk-0.1> pybot nspTest.tsv 
==============================================================================
nspTest                                                                       
==============================================================================
Demo Test :: Example test                                             | PASS |
------------------------------------------------------------------------------
Another Test                                                          | PASS |
------------------------------------------------------------------------------
VFS Test                                                              | FAIL |
Expected status to be 'Wrong results' but was '{'childList': {0: {'type': 'Directory', 'name': 'zhujhdir'}, 1: {'type': 'Directory', 'name': '\xe7\x85\xa7\xe7\x89\x87'}, 2: {'type': 'Directory', 'name': '\xe6\x96\x87\xe6\xa1\xa3'}, 3: {'type': 'Directory', 'name': '\xe6\x88\x91\xe6\x94\xb6\xe5\x88\xb0\xe7\x9a\x84\xe6\x96\x87\xe4\xbb\xb6'}, 4: {'type': 'Directory', 'name': '\xe6\x88\x91\xe7\x9a\x84\xe6\x96\x87\xe4\xbb\xb6'}, 5: {'type': 'Directory', 'name': '\xe8\xbd\xaf\xe4\xbb\xb6'}, 6: {'type': 'File', 'name': '\xe6\x88\x91\xe7\x9a\x84\xe6\xb5\x8b\xe8\xaf\x95.php'}, 7: {'type': 'File', 'name': 'data.txt'}, 8: {'type': 'File', 'name': 'test.thrift'}, 9: {'type': 'File', 'name': 'acds4.txt'}, 10: {'type': 'File', 'name': 'nsp_sdk.log'}, 11: {'type': 'File', 'name': 'data.rar'}, 12: {'type': 'File', 'name': 'test.rar'}}}'
------------------------------------------------------------------------------
nspTest                                                               | FAIL |
3 critical tests, 2 passed, 1 failed
3 tests total, 2 passed, 1 failed
==============================================================================
Output:  /home/ciaos/Downloads/python-sdk-0.1/output.xml
Log:     /home/ciaos/Downloads/python-sdk-0.1/log.html
Report:  /home/ciaos/Downloads/python-sdk-0.1/report.html

 其中report.html等文件包含详细的测试结果

 此外robotframe包含丰富的测试工具,如内置测试库以及用于测试web接口的requests库,直接使用request测试库可以免去我们编写web请求的工作。

安装顺序

pip install -U requests==0.9.0

pip install -U robotframework-requests

使用示例:

WEB TEST        [Tags]  web.test
        Create Session  vmall   http://api.vmall.com
        ${resp}=        GET     vmall   /rest.php
        Should Be Equal As Strings      ${resp.status_code}     200
        log     ${resp.content}
        Should Contain  ${resp.content} "param"
        ${json}=        To JSON ${resp.content}
        Dictionary Should Contain Value ${json} "param error"

猜你喜欢

转载自ciaos.iteye.com/blog/1813898
今日推荐