zoukankan      html  css  js  c++  java
  • python测试api接口

    在开发中,需要测试web-api的接口 spring mvc 使用单元测试非常方便,但是,受不了单元测试的启动速度。用python写了一个小脚本,用于测试接口,

    测试脚本配置文件
    api.yaml

    server:
      url: http://127.0.0.1:9000/ihome/
    
    api:
      name:
        #api-v2-neighbor-list.yaml
        - api/v2/neighbor/list   
    

    api-v2-neighbor-list.yaml
    接口配置文件

    method:
      post
    data:
      #post 的 body 的json
      postSid: a1
      userSid: u2
    

    python 脚本

    import requests, json, yaml, sys
    
    
    def apiTest(apiName):
        f = open("api.yaml")
        obj = yaml.safe_load(f)
        f.close()
    
        if apiName != "":
            runApi(obj["server"]["url"] + apiName, apiName.replace("/", "-") + ".yaml")
            return;
    
        apis = obj['api']["name"]
        for api in apis:
            runApi(obj["server"]["url"] + api, api.replace("/", "-") + ".yaml")
    
    def runApi(url, dataFile):
        headers = {'Content-Type' : 'application/json; charset=UTF-8',
                              'X-Requested-With' : 'XMLHttpRequest',
                              'Connection' : 'keep-alive',
                              'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36'
                        }
    
        f = open(dataFile)
        obj = yaml.safe_load(f)
        f.close()
    
        s = requests.session()
    
        if obj["method"] == "get":
            r = s.get(url= url, headers = headers)
        if obj["method"] == "post":
            r = s.post(url= url , data = json.dumps(obj["data"]), headers = headers)
    
    
        status = r.status_code
        if status != 200:
            print "x1b[31mfail: status-> {} {}x1b[0m".format(status, url)
            return
    
        resp = json.loads(r.text)
        if resp["success"] == 0:
            print "x1b[32mpass: {}x1b[0m".format(url)
        else:
            print "x1b[31mfail: {} message: {}x1b[0m".format(url, resp["message"].encode('utf-8'))
    
    
    def main():
        apiName = ""
        if len(sys.argv) > 1:
            apiName = sys.argv[1]
    
        apiTest(apiName)
    
    if __name__ == '__main__':
        main()
    
    
  • 相关阅读:
    asp.net中控件的enableviewstate属性 的设置
    一个怎样得到treeView值的小例子
    实现表格边框的样式表
    GridView的精妙使用
    无法向会话状态服务器发出会话状态请求。
    Microsoft Visual Studio 2008 快捷键大全
    我每天学习一句英语今天要学的是
    C语言学习心得
    怎么样把GridView里的数据导出到Excel里
    怎么样在c#程序中放音乐
  • 原文地址:https://www.cnblogs.com/warrior/p/6084390.html
Copyright © 2011-2022 走看看