pytest接口测试轻松入门

通过Postman请求结果如下图:

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

在接口测试,我们要用到requests包,实现代码如下:

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 启动文件名是以test开头,函数名是以test开头。所以我们把上面的函数名改下,把TestWacher改为testWacher再去执行,效果如下:

相比于状态码,我们可能更喜欢进行关键字校验,如 查询结果中没有wendu字段,则视为用例失败怎么实现?

此时可以使用pytest的xfail标记用例预期失败,如果用例运行成功则显示Xpassed,失败则显示xfailed。xfail标记并不会影响用例的运行。 添加代码如下:

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

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

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

@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报告:

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

测试工程师职业发展路线图

功能测试 — 接口测试 — 自动化测试 — 测试开发 — 测试架构师

加油吧,测试人!如果你需要提升规划,那就行动吧,在路上总比在起点观望的要好。事必有法,然后有成。

资源不错就给个推荐吧~

经验分享 程序员 微信小程序 职场和发展