在做接口自动化测试过程中,要给每个接口添加对应的断言,执行完成之后可以根据断言的结果来判断接口是否通过。
在Python中添加断言 直接使用 assert 即可。

判断相等

  1. """
  2. cnode 社区接口作业
  3. """
  4. import requests
  5. # 定义请求地址前缀
  6. baseurl = "http://47.100.175.62:3000/api/v1"
  7. token = "e18de36f-d9ce-47e6-a2aa-1cf6508ec10b"
  8. # 预先定义字典格式的数据
  9. test_data={
  10. "topic_id":"", # 需要进行上下游传参的字段 初始值为 空字符串
  11. "reply_id":"" # 评论id 需要进行上下游传参, 初始值设置为 空字符
  12. }
  13. def test_add_topic():
  14. """
  15. 创建话题
  16. :return:
  17. """
  18. url = baseurl+"/topics"
  19. body_data = {
  20. "accesstoken": token,
  21. "title":"hehehehehehe",
  22. "tab":"ask",
  23. "content":"xxxxxxxxxxxx"
  24. }
  25. r = requests.post(url,json=body_data)
  26. print("新建主题:",r.status_code,r.json())
  27. # 从返回结果中提起 话题的id
  28. tid = r.json()["topic_id"]
  29. # 将提取出来的值tid 更新到 外边定义的字典中 test_data[”topic_id”]
  30. test_data["topic_id"] = tid # 上游更新值
  31. # 创建话题成功之后,添加对应的断言
  32. # 状态码为200
  33. assert r.status_code == 200 # 判断相等

在上面接口中添加了 状态码为200 的断言。

  1. assert r.status_code == 200 # 判断相等

添加断言

  1. """
  2. cnode 社区接口作业
  3. """
  4. import requests
  5. # 定义请求地址前缀
  6. baseurl = "http://47.100.175.62:3000/api/v1"
  7. token = "e18de36f-d9ce-47e6-a2aa-1cf6508ec10b"
  8. # 预先定义字典格式的数据
  9. test_data={
  10. "topic_id":"", # 需要进行上下游传参的字段 初始值为 空字符串
  11. "reply_id":"" # 评论id 需要进行上下游传参, 初始值设置为 空字符
  12. }
  13. def test_add_topic():
  14. """
  15. 创建话题
  16. :return:
  17. """
  18. url = baseurl+"/topics"
  19. body_data = {
  20. "accesstoken": token,
  21. "title":"hehehehehehe",
  22. "tab":"ask",
  23. "content":"xxxxxxxxxxxx"
  24. }
  25. r = requests.post(url,json=body_data)
  26. print("新建主题:",r.status_code,r.json())
  27. # 从返回结果中提起 话题的id
  28. tid = r.json()["topic_id"]
  29. # 将提取出来的值tid 更新到 外边定义的字典中 test_data[”topic_id”]
  30. test_data["topic_id"] = tid # 上游更新值
  31. # 创建话题成功之后,添加对应的断言
  32. # 状态码为200
  33. assert r.status_code == 200 # 判断相等
  34. # 返回结果 success 为True 添加断言
  35. assert r.json()["success"] == True

一个接口根据业务逻辑可以添加 多个断言,主要针对

  • 状态码断言
  • 服务器返回结果值进行断言 ```python import requests

定义请求地址前缀

baseurl = “http://47.100.175.62:3000/api/v1“ token = “e18de36f-d9ce-47e6-a2aa-1cf6508ec10b”

预先定义字典格式的数据

test_data={ “topic_id”:””, # 需要进行上下游传参的字段 初始值为 空字符串 “reply_id”:”” # 评论id 需要进行上下游传参, 初始值设置为 空字符 }

def test_add_topic(): “”” 创建话题 :return: “”” url = baseurl+”/topics” body_data = { “accesstoken”: token, “title”:”hehehehehehe”, “tab”:”ask”, “content”:”xxxxxxxxxxxx” } r = requests.post(url,json=body_data) print(“新建主题:”,r.status_code,r.json())

  1. # 从返回结果中提起 话题的id
  2. tid = r.json()["topic_id"]
  3. # 将提取出来的值tid 更新到 外边定义的字典中 test_data[”topic_id”]
  4. test_data["topic_id"] = tid # 上游更新值
  5. # 创建话题成功之后,添加对应的断言
  6. # 状态码为200
  7. assert r.status_code == 200 # 判断相等
  8. # 返回结果 success 为True 添加断言
  9. assert r.json()["success"] == True

def test_edit_topic(): “”” 编辑话题 :return: “”” url = baseurl + “/topics/update” body_data = { “accesstoken”: token,

  1. # "topic_id":"625cc91ceb0fc111c4a0d584",
  2. "topic_id": test_data["topic_id"] , # 通过字典 topic_id 字段引用最新的值。
  3. "title": "hehehehehehe",
  4. "tab": "ask",
  5. "content": "xxxxxxxxxxxx"
  6. }
  7. r = requests.post(url, json=body_data)
  8. print("编辑主题:", r.status_code, r.json())
  9. # 添加状态码断言
  10. assert r.status_code == 200
  11. # 添加 success 字段值 断言
  12. assert r.json()['success'] == True
  13. # 添加对 tipic_id 值进行断言 topic_id 的值为上游接口中 发帖成功的返回值
  14. assert r.json()["topic_id"] == test_data["topic_id"]
因为这两个接口有参数关联,运行的时候需要 两个用例 都要执行。<br />在命令行运行,使用 pytest 命令执行整个文件即可。
```python
pytest cnode_hm.py

在pycharm 上运行
image.png
在对应的文件上右键-执行。
image.png

练习

testcases/test_cnode.py 通过接口串联来进行 断言。

"""
练习断言
"""
import requests

# 定义请求地址前缀
baseurl = "http://47.100.175.62:3000/api/v1"
token = "e18de36f-d9ce-47e6-a2aa-1cf6508ec10b"
# 预先定义字典格式的数据
test_data={
    "topic_id":"",   # 需要进行上下游传参的字段  初始值为 空字符串
    "reply_id":""   # 评论id 需要进行上下游传参,  初始值设置为 空字符
}

def test_add_topic():
    url = baseurl + "/topics"
    body_data = {
        "accesstoken": token,
        "title": "hehehehehehe",
        "tab": "ask",
        "content": "xxxxxxxxxxxx"
    }
    r = requests.post(url, json=body_data)
    print("新建主题:", r.status_code, r.json())
    # 从返回结果中提起 话题的id
    tid = r.json()["topic_id"]
    # 将提取出来的值tid 更新到 外边定义的字典中 test_data[”topic_id”]
    test_data["topic_id"] = tid  # 上游更新值

    # 创建话题成功之后,添加对应的断言
    # 状态码为200
    assert r.status_code == 200  # 判断相等
    # 返回结果 success 为True 添加断言
    assert r.json()["success"] == True


def test_index_page():
    url = baseurl+"/topics"
    query_data= {
        "tab":"ask",
        "limit":50
    }
    r = requests.get(url,params=query_data)
    print('服务器返回结果')
    print(r.json())
    # 添加断言
    # 状态码 200
    assert r.status_code == 200
    # success True
    assert r.json()["success"] == True
    # 返回的数据中有 50个 话题的id
    ids = []
    for topic in r.json()["data"]:
        print("每个话题的信息:",topic)
        print("每个话题的id:",topic["id"])
        # 存放每个id
        ids.append(topic["id"])
    # 50个id,ids的长度肯定为50
    assert len(ids) == 50
    # 这50个话题的id一定包含 上面创建成功的话题id  ids保存了所有的话题id in 在... 里面
    assert test_data["topic_id"] in ids
    # 服务器返回结果中每个话题的 tab 值 一定是 ask
    # 循环所有话题
    for topic in r.json()["data"]:
        # 每个话题的tab值都是 ask
        assert topic["tab"] == "ask"

运行。
命令行运行

pytest testcases/test_cnode.py -s -v
  • -s 显示代码中的print打印
  • -v 详细的运行日志

pycharm 运行
image.png

作业

完成上下游传参和添加断言

# 接口地址 http://49.233.108.117:28019/swagger-ui.html#/


def test_user_register():
    """
    用户注册
    :return:
    """

    # 添加断言
    # code为200
    # msg

def test_user_login():
    """
    用户登录。 登录使用的手机号跟注册是同一个号码
    :return:
    """

    # 断言
    # code 断言
    # msg 断言

    # 提取变量值 token

def test_search():
    """
    搜索商品 需要token
    :return:
    """

    # 搜索条件为 iphone

    # 断言
    # 所有搜索结果中都包含iphone

    # 将价格大于 5500 的商品id 随机抽取一个作为变量

def test_add_cart():
    """
    添加购物车
    :return:
    """

    # 断言 添加成功

作业答案

testcases/test_xf.py

# 接口地址 http://49.233.108.117:28019/swagger-ui.html#/
import requests
# 导入已经编写好的生成手机号码的函数
from common.utils import generate_phone
import random

base_url = "http://49.233.108.117:28019"
# 注册,登录使用的是同一个手机号码  定义变量
phone = generate_phone()

testdata ={
    "token":"", # token,
    "gid": 0    # 商品id
}

def test_user_register():
    """
    用户注册
    :return:
    """
    url = base_url+"/api/v1/user/register"
    body_data = {
        "loginName": phone,
        "password": "123456"
    }
    # 发送请求
    r = requests.post(url,json=body_data)
    print(r.json())
    # 添加断言
    # code为200
    assert r.status_code == 200
    assert r.json()['resultCode'] == 200
    # msg
    assert r.json()['message'] == 'SUCCESS'

def test_user_login():
    """
    用户登录。 登录使用的手机号跟注册是同一个号码
    :return:
    """
    url = base_url+"/api/v1/user/login"
    body_data = {
      "loginName": phone,
      "passwordMd5": "E10ADC3949BA59ABBE56E057F20F883E"
    }
    r = requests.post(url,json=body_data)
    print(r.json())
    # 断言
    # code 断言
    assert r.status_code == 200
    assert r.json()['resultCode'] == 200
    # msg
    assert r.json()['message'] == 'SUCCESS'

    # 提取变量值 token
    testdata["token"] = r.json()["data"]

def test_search():
    """
    搜索商品 需要token
    :return:
    """
    url = base_url+'/api/v1/search'
    query_data = {
        "keyword":"iphone"
    }
    header={
        "token":testdata["token"]
    }
    # 搜索条件为 iphone
    r = requests.get(url,params=query_data,headers=header)
    # 断言
    # 所有搜索结果中都包含iphone

    # 拿到所有的商品信息
    allgoods = r.json()["data"]["list"]
    # 循环所有商品的时候
    for good in allgoods:
        # 拿到每个商品的名称
        goodname = good["goodsName"]
        print('商品的名称',goodname) # 因为返回结果中有大小写字母混合的场景。使用字符串转换大写方法
        assert 'iphone'.upper() in goodname.upper()  # upper 将字符串转为大写
    # 将价格大于 5500 的商品id 随机抽取一个作为变量
    # 将所有价格大于5500 的商品id放在一个列表中
    gids = []
    for good in allgoods:
        if good["sellingPrice"] > 5500:
            gids.append(good["goodsId"])
    print("所有商品价格大于5500的商品id",gids)
    testdata["gid"] = random.choice(gids)

def test_add_cart():
    """
    添加购物车
    :return:
    """
    url = base_url+"/api/v1/shop-cart"
    body_data = {
        "goodsCount": 1,
        "goodsId": testdata["gid"]  # 商品id
    }
    header = {
        "token":testdata["token"]
    }
    r = requests.post(url,json=body_data,headers=header)
    print(r.json())
    # 断言 添加成功
    assert r.status_code == 200
    assert r.json()['resultCode'] == 200
    # msg
    assert r.json()['message'] == 'SUCCESS'

视频