# 8.使用pytest做简单的接口测试




### 背景

我们现在需要测试[v2ex](http://www.v2ex.com)网站的查看论坛节点信息的api。具体如下:

```
节点信息

获得指定节点的名字，简介，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" : 7963,
    "stars" : 5138,

        "header" : "这里讨论各种 Python 语言编程话题，也包括 Django，Tornado 等框架的讨论。这里是一个能够帮助你解决实际问题的地方。",


        "footer" : null,

    "created" : 1278683336,
    "avatar_mini" : "//v2ex.assets.uxengine.net/navatar/8613/985e/90_mini.png?m=1509941286",
    "avatar_normal" : "//v2ex.assets.uxengine.net/navatar/8613/985e/90_normal.png?m=1509941286",
    "avatar_large" : "//v2ex.assets.uxengine.net/navatar/8613/985e/90_large.png?m=1509941286"
}

```

### 需求分析

该接口是获取数据的接口，一般来说，这种接口我们的测试重点是验证数据的准确性。

根据[3A原则](/interface/3a/)，我们可以设计如下的[用例](/interface/first_case/)

* 测试数据: 节点的名称:python
* 接口地址: https://www.v2ex.com/api/nodes/show.json
* 断言: 返回的结果里，id必须是90,name必须等于python，大家想一想为什么？

### 代码

新建名为```v2ex_api_test.py```的文件，键入如下内容

```python
import requests

class TestV2exApi(object):
    domain = 'https://www.v2ex.com/'

    def test_node(self):
        path = 'api/nodes/show.json?name=python'
        url = self.domain + path
        res = requests.get(url).json()
        assert res['id'] == 90
        assert res['name'] == 'python'

```

需要注意的点

* 使用[requests](http://docs.python-requests.org/en/master/)库来简化发送get请求并将返回值的json字符串转换成python字典
* 使用domain变量来参数化测试的地址，因为不同环境的地址可能不一样，使用domain变量之后只需要改动这个变量就可以切换测试环境了
* 断言id为90是因为测试数据是静态的，id不会发生变化

### 运行

```
$ pytest v2ex_api_test.py
======================================================================== test session starts ========================================================================
platform darwin -- Python 2.7.12, pytest-3.2.3, py-1.4.34, pluggy-0.4.0
rootdir: /Users/easonhan/code/testclass.net/src/pytest, inifile:
collected 1 item

v2ex_api_test.py .

===================================================================== 1 passed in 1.39 seconds ======================================================================
```

用例执行成功，我们实现了最简单的接口测试场景。




原始封面

![课程图片](https://images.unsplash.com/photo-1498429089284-41f8cf3ffd39?w=300)


