8.第一个用例

乙醇 创建于 over 6 years 之前

最后更新: about 2 months 之前

阅读数: 1

8.第一个用例

前面铺垫了很多的基础知识,掌握基础知识是做基于http接口自动化测试的前提,不建议直接跳过。

前提条件

学习本节需要有一些前提条件

  • 安装了postman
  • 安装了python
  • 安装了requests

用例描述

认识测试对象这一节里有过描述。


获得指定节点的名字,简介,URL 及头像图片的地址。

https://www.v2ex.com/api/nodes/show.json

Method: GET
Authentication: None
接受参数:

name: 节点名(V2EX 的节点名全是半角英文或者数字)
例如:

https://www.v2ex.com/api/nodes/show.json?name=python

# 响应

{
    "id" : 90,
    "name" : "python",
    "url" : "http://www.v2ex.com/go/python",
    "title" : "Python",
    "title_alternative" : "Python",
    "topics" : 7669,
    "stars" : 4870,

        "header" : "这里讨论各种 Python 语言编程话题,也包括 Django,Tornado 等框架的讨论。这里是一个能够帮助你解决实际问题的地方。",


        "footer" : null,

    "created" : 1278683336,
    "avatar_mini" : "//v2ex.assets.uxengine.net/navatar/8613/985e/90_mini.png?m=1504279401",
    "avatar_normal" : "//v2ex.assets.uxengine.net/navatar/8613/985e/90_normal.png?m=1504279401",
    "avatar_large" : "//v2ex.assets.uxengine.net/navatar/8613/985e/90_large.png?m=1504279401"
}

使用postman调试接口

在写用例之前,我们先在postman里把接口调通,大家可以参考之前这篇

然后选择右上角的Code菜单,如下图所示

选择导出为python requests的代码,拷贝到系统剪切板,如下图所示

导出的代码应该是这个样子的

import requests

url = "https://www.v2ex.com/api/nodes/show.json"

querystring = {"name":"python"}

headers = {
    'cache-control': "no-cache",
    'postman-token': "a596dcc5-ab8b-8456-79c7-94a6ac11378e"
    }

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)

使用unittest重构代码

导出的代码只是3A里的Arrange和Act,我们使用unittest来重构代码

新建文件v2ex_api_case.py

import requests
import unittest

class V2exAPITestCase(unittest.TestCase):

    def test_node_api(self):
        url = "https://www.v2ex.com/api/nodes/show.json"
        querystring = {"name":"python"}
        response = requests.request("GET", url, params=querystring).json()
        self.assertEqual(response['name'], 'python')
        self.assertEqual(response['id'], 90)

if __name__ == '__main__':
    unittest.main()

运行用例

使用下面的命令可以运行用例

python v2ex_api_case.py

运行结果

.
---------------------------------------
Ran 1 test in 0.437s

OK

总结

  • postman可以帮助我们完成50%左右的工作,比如调试接口,导出部分代码等
  • 使用unittest重构用例可以帮助我们添加断言,提供在命令行执行的能力,很容易跟ci工具进行集成
0

相关课程

requests从入门到精通
图文
requests从入门到精通

课程分类: 测试工具 接口测试

python接口测试必会

  • 已完结
  • 已更新16集
  • 最后更新时间: 2024-03-18 12:54:40

免费

查看详情