pytest接口测试轻松入门

对于pytest的运行环境及如何生成漂亮的测试报告,小酋在前面已经做了分享(《Pycharm整合pytest测试框架》《Pycharm+pytest+allure打造高逼格的测试报告》《pytest+allure+jenkins持续集成及生成测试报告》),今天通过一个简单的案例让大家学会如何做pytest的接口测试。

一个免费的天气查询接口:
http://wthrcdn.etouch.cn/weather_mini?city=成都
通过Postman请求结果如下图:

pytest接口测试轻松入门1

那我们怎么用pytest进行测试呢?

在接口测试,我们要用到requests包(关于requests包的用法,可以看此文 https://www.jianshu.com/p/926b51525057),实现代码如下:

import pytest
import allure
import requests

class TestSimple(object):
    def TestWatcher(self):
        url = "http://wthrcdn.etouch.cn/weather_mini?city=成都"
       r = requests.get(url)
        assert r.status_code == 200
        d = r.json()
        print(d)

 

简述:上面通过request实现了天气的查询,对其请求状态做了验证(如果HTTP状态码为200则认为测试通过),并对接口请求结果进行了打印。

执行上面代码时遇到问题:No tests were found

pytest接口测试轻松入门2

结果问题查询:pytest 启动文件名是以test开头,函数名是以test开头。所以我们把上面的函数名改下,把TestWacher改为testWacher再去执行,效果如下:

pytest接口测试轻松入门3

相比于状态码,我们可能更喜欢进行关键字校验,如 查询结果中没有wendu字段,则视为用例失败怎么实现?
此时可以使用pytestxfail标记用例预期失败,如果用例运行成功则显示Xpassed,失败则显示xfailed。xfail标记并不会影响用例的运行。
添加代码如下:

if ('wendu' not in d['data'].keys()):
    pytest.xfail('返回结果不正确,wendu=NULL')

假设我们要检查的字段是 wendi,而结果中没有该字段,此时执行效果如下:

pytest接口测试轻松入门4

如果我们在执行时,如何让报告显得更漂亮呢?这时我们可以进行美化,最终代码如下:

@allure.feature("测试Dome")
class TestSimple(object):
    @allure.story("天气查询")
    @allure.description('一个免费的天气查询接口测试')
    @allure.severity('critical')
    def testWatcher(self):
        url = "http://wthrcdn.etouch.cn/weather_mini?city=成都"
        with allure.step("查询天气"):
            r = requests.get(url)
            assert r.status_code == 200
            d = r.json()
            print(d)
            if ('wendu' not in d['data'].keys()):
                pytest.xfail('返回结果不正确,wendu=NULL')

常见allure报告美化总结:

@allure.feature("测试用例特性场景(主要功能模块)")
@allure.story("feature功能模块下的分支功能(用例名称)")
@allure.description("这里是用例的描述信息")  
@allure.severity("测试用例等级")
说明:allure对用例的等级划分成五个等级

  • blocker -- 阻塞缺陷(功能未实现,无法下一步)
  • critical -- 严重缺陷(功能点缺失)
  • normal -- 一般缺陷(边界情况,格式错误)
  • minor -- 次要缺陷(界面错误与ui需求不符)
  • trivial -- 轻微缺陷(必需项无提示,或者提示不规范)

allure.description_html(html代码) #提供一些HTML在测试用例的描述部分
@allure.step("用例步骤说明")
使用方法:
①@allure.step()  只能以装饰器的形式放在类或者方法上面;
②with allure.step():  可以放在测试用例方法里面,但测试步骤的代码需要被该语句包含;
allure.attach(body, name, attachment_type, extension)
用于向测试报告中输入一些附加的信息,通常是一些测试数据信息,参数说明:

  • body - 要写入文件的原始内容
  • name - 包含文件名的字符串
  • attachment_type - 其中一个allure.attachment_type值,可以是文本、图片、HTML等
  • extension - 提供的将用作创建文件的扩展名

@allure.link("URL=链接地址")
@allure.issue("URL=问题链接")
@allure.testcase("URL=用例链接")

最后执行用例,并生成allure报告

pytest接口测试轻松入门5

点击特性场景,进入详情,结果如下:

pytest接口测试轻松入门6

上面就实现了一个简单的pytest接口测试例子,但怎么参数化,怎么让代码层次更清晰,要不要这么low b?请关注小酋后续文章。

关于pycharm的破解,请参考文章《2020最新Pycharm四步破解教程(永久破解)》,建议pycharm与文中版本一致,否则可能导致破解失败。



留言