# 8.第一个用例




前面铺垫了很多的基础知识，掌握基础知识是做基于http接口自动化测试的前提，不建议直接跳过。

### 前提条件

学习本节需要有一些前提条件

* 安装了postman
* 安装了python
* 安装了requests

### 用例描述

在[认识测试对象](/interface/test_object/)这一节里有过描述。

```

获得指定节点的名字，简介，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"
}
```

* 测试数据: 节点的名称:python
* 接口地址: https://www.v2ex.com/api/nodes/show.json
* 断言: 返回的结果里，id必须是90,name必须等于python，大家想一想为什么？

### 使用postman调试接口

在写用例之前，我们先在postman里把接口调通，大家可以参考[之前这篇](/interface/install_postman/)

然后选择右上角的Code菜单，如下图所示

![](http://oriphg3yh.bkt.clouddn.com/code.png)

选择导出为python requests的代码，拷贝到系统剪切板，如下图所示

![](http://oriphg3yh.bkt.clouddn.com/choose_request.png)

导出的代码应该是这个样子的

```python
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

```python
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工具进行集成




原始封面

![课程图片](https://images.unsplash.com/photo-1496181133206-80ce9b88a853?w=300)


