1 基于pytest单元测试框架的规则

1.1 模块名(即文件名)必须以test_开头或者_test结尾

1.2 类名必须以Test开头且不能有init方法

1.3 用例名(测试方法)必须以test开头

3 项目实战

import pytest as pytest
import requests


# 此案例测试用例之间无法关联cookie信息
class TestApi:
    # 类变量也叫全局变量
    access_token = ""

    # 获取鉴权码
    def test_get_token(self):
        url = "https://api.weiixn.com/token"
        datas = {
            "grant_type": "client_credential",
            "appid": "wx32497320974",
            "secret": "dh2983yr4fh9734."
        }
        res = requests.get(url=url, params=datas)
        result = res.json()
        TestApi.access_token = result["access_token"]
        # jsonpath提取实现接口关联
        # lis = jsonpath.jsonpath(res.json(), "$.access_token")
        # print(lis[0])
        # re正则表达式提取
        # token = re.search('name="hduwqidh" value="(.*?)"', res.text).group(1)

    # 编辑标签接口
    def test_edit_flag(self):
        url = "https://api.weiixn.com/update?access_token=" + TestApi.access_token
        headers = {}
        # json是字典的字符串格式,两者可以相互转换
        json = {}
        # 键值对
        data = None
        res = requests.post(url=url, json=json, headers=headers)

    # 文件上传
    def test_file_upload(self):
        url = "https://api.weiixn.com/update?access_token=" + TestApi.access_token
        datas = {
            # 文件路径也可以写为open("D:\\snipaste")
            "media": open(r"D:\snipaste", mode="rb")
        }
        res = requests.post(url=url, files=datas)


if __name__ == '__main__':  # 入口
    pytest.main('-vs')

4 pytest的main使用

4.1 pytest.main() 运行模式时,main()不添加任何参数,表示运行当前目录下的所有的测试文件

4.2 main()添加参数如下:

   pytest.main(['-s', '-v', '-q', '-x','-k "print"'])

   -s   对于代码里print语句会将输出至控制台

   -v   用于增加测试用例的冗长

   -q   用于减少测试用例的执行结果的冗长

   -x   出现一条用例执行失败就退出测试,调试阶段常用

   -k "print"  运行包含某个字符串的用例,如pytest -k add XX.py 表示运行XX.py中包含add的测试用例

   等等   

4.3 执行测试用例的过滤

执行某个测试类或测试方法用 :: 隔开,常用-vs参数

pytest.main(["-vs","模块.py::类或方法"])   

命令行为:pytest 文件名.py::测试类或测试方法

pytest.main(["-vs","模块.py::类::方法"])   

命令行为:pytest 文件名.py::测试类::测试方法

如果是在main目录入口执行测试用例文件:

import pytest

if __name__ == '__main__':

    pytest.main(["-vs","--html=../../report_hdc/20211011_hdc_02.html","--self-contained-html"])

4.4 如果使用pytest.main()生效,再pycharm中必须设置Tools>Python Integrated Tools>Default test runner=Unittests;如果设置为pytest则是无效的。

4.5 在pytest中,测试函数可能返回多种结果,不只是通过或失败。如下:

PASSED(.):测试通过

FAILED(F):测试失败

SKIPED(s):测试未被执行,指定测试跳过执行

xfail (x):预期测试失败,并且确实失败

XPASS (X):预期测试失败,但实际上运行通过,不符合预期

ERROR (E):测试用例之外的代码触发的异常

4.6 pytest.main(["-m", "run_first"])

使用-m 对用例进行标记,用例需注释@pytest.mark.xxx,将xxx作为参数传入

使用-m "mark1 and mark2"可以同时选中带有这两个标记的所有测试用例。

使用-m "mark1 and not mark2"选中带有与mark1的测试用例,而过滤掉带有mark2的测试用例

使用-m "mark1 or mark2"则选中带有mark1或者mark2的所有测试用例

5 接口关联

5.1 三个层次

5.1.1 通过类变量保存中间变量实现接口关联

5.1.2 通过单独的文件保存中间变量实现接口关联

5.1.3 极限封装成零代码的方式实现接口关联

5.2 两种方式

5.2.1 正则提取实现接口关联

re.search() #通过正则匹配一个值,通过下标[1]取值,没有匹配到返回none

re.findall() #通过正则匹配多个值,返回List,通过下标取值,没有匹配到返回none

5.2.2 jsonpath提取实现接口关联

jsonpath.jsonpath() #返回一个列表,通过下标取值,没有找到返回none