多彩编程 多彩编程MZPH · CODE BLOG
ARTICLE DETAIL

文章详情

深耕前端与后端开发技术的一线实战笔记与踩坑复盘。

pytest速成

pytest速成 【B站讲的最好的Pytest自动化测试教程自动化必备之Pytest测试框架训练营只需一小时速成学会直接上手实操】速成pytest插件管理pytest-html 生成html报告ASUSLAPTOP-VUFPBHN7 MINGW64 /d/Python/Code/pytestProject1 $ pytest --htmlreport.html --self-contained-html test session starts platform win32 -- Python 3.12.6, pytest-9.1.1, pluggy-1.6.0 rootdir: D:\Python\Code\pytestProject1 configfile: pytest.ini plugins: html-4.2.0, metadata-3.1.1 collected 10 items Demo1\test_01.py ..Xx..F. [ 80%] Demo1\test_fixture.py .. [100%] FAILURES _______________________________________________________________ TestAdd.test_ddt[2-3-6] ________________________________________________________________ self test_01.TestAdd object at 0x0000021970B51BE0, a 2, b 3, c 6 pytest.mark.parametrize( a,b,c, read_csv(./data.csv) ) pytest.mark.ddt def test_ddt(self, a, b, c): assert add(int(a), int(b)) int(c) E AssertionError: assert 5 6 E where 5 add(2, 3) E where 2 int(2) E and 3 int(3) E and 6 int(6) Demo1\test_01.py:36: AssertionError --------------------------------------- Generated html report: file:///D:/Python/Code/pytestProject1/report.html --------------------------------------- short test summary info FAILED Demo1/test_01.py::TestAdd::test_ddt[2-3-6] - AssertionError: assert 5 6 1 failed, 7 passed, 1 xfailed, 1 xpassed in 0.25s (venv) ASUSLAPTOP-VUFPBHN7 MINGW64 /d/Python/Code/pytestProject1 $ pytest test session starts platform win32 -- Python 3.12.6, pytest-9.1.1, pluggy-1.6.0 rootdir: D:\Python\Code\pytestProject1 configfile: pytest.ini plugins: html-4.2.0, metadata-3.1.1 collected 10 items Demo1\test_01.py ..Xx..F. [ 80%] Demo1\test_fixture.py .. [100%] FAILURES _______________________________________________________________ TestAdd.test_ddt[2-3-6] ________________________________________________________________ self test_01.TestAdd object at 0x0000020CA0EA57F0, a 2, b 3, c 6 pytest.mark.parametrize( a,b,c, read_csv(./data.csv) ) pytest.mark.ddt def test_ddt(self, a, b, c): Demo1\test_01.py:36: AssertionError --------------------------------------- Generated html report: file:///D:/Python/Code/pytestProject1/report.html --------------------------------------- short test summary info FAILED Demo1/test_01.py::TestAdd::test_ddt[2-3-6] - AssertionError: assert 5 6 1 failed, 7 passed, 1 xfailed, 1 xpassed in 0.24s (venv) ASUSLAPTOP-VUFPBHN7 MINGW64 /d/Python/Code/pytestProject1 $可直接将参数写入配置文件中执行时直接执行即可。pytest-xdist 分布式执行pytest-rerunfailures 失败重试pytest-result-log 生成日志allure 企业级测试报告安装配置可以用命令行方式执行也可以在设置文件中设置执行参数并让系统调用生成allure命令的参数分组关联import allure import pytest allure.epic(自动化测试) allure.feature(pytest框架训练) allure.story(mark标记和筛选) allure.title(实现筛选的用例) pytest.mark.ut def test_a(): pass allure.epic(自动化测试) allure.feature(pytest框架训练) allure.story(fixture前置和后置) allure.title(使用fixture的用例) pytest.mark.ut def test_b(): pass接口自动化框架代码开发Web自动化测试实战-seleniumpip install pytest-selenium -i https://pypi.tuna.tsinghua.edu.cn/simple进入虚拟环境venv方法1Git Bash 中进入 venv在当前终端输入source venv/Scripts/activate成功后会看到(venv) ASUSLAPTOP-VUFPBHN7 MINGW64 /d/Python/Code/pytestProject1 $前面多了(venv)表示进入成功。然后就可以安装插件例如pip install allure-pytest或者pip install pytest-html方法2Windows CMD方式如果打开的是 cmd进入项目cd /d D:\Python\Code\pytestProject1激活venv\Scripts\activate成功(venv) D:\Python\Code\pytestProject1方法3PyCharm里面直接进入PyCharm 其实已经配置了 venv看右下角Python 3.10如果这里是你的 venv解释器就可以直接安装。操作方法1PyCharm底部Python Packages点击搜索allure-pytest安装。方法2Terminal安装推荐打开的 Terminal输入where python如果正确会看到类似D:\Python\Code\pytestProject1\venv\Scripts\python.exe如果看到D:\Python\python3.12.6\python.exe说明还没进入venv。验证pip是否属于venv进入后执行pip -V正确应该类似pip 25.x from D:\Python\Code\pytestProject1\venv\Lib\site-packages重点看pytestProject1\venv建议安装的测试插件根据你现在学习的 pytest allure 项目进入 venv 后pip install pytest pip install allure-pytest pip install pytest-xdist pip install pytest-rerunfailures pip install pytest-html检查pip list应该看到allure-pytest pytest pytest-html pytest-xdist接口自动化框架封装实战封装内容YAML文件格式pip install pyyaml -i https://pypi.tuna.tsinghua.edu.cn/simple读取yamlimport yaml def read_yaml(path): with open(path,encodingutf-8) as f: data yaml.load(f, Loaderyaml.FullLoader) print(data) return data # f open(path,encodingutf-8) # data yaml.load(f, Loaderyaml.FullLoader) # print(data) # return data if __name__ __main__: read_yaml(../jianglin.yaml)接口测试用例新建yaml文件name: 登录成功用例 steps: # 发送登录请求 - request: method: POST url: http://192.168.43.163:8888/auth/login headers: Content-Type: application/json json: username: admin password: 123456 type: 1 # 断言响应 - response: status_code: 200 json: code: 0 user: username: admin # 提取token - extract: token: [json, $.token]封装接口自动化框架请求接口--requestsimport requests # 方法 url http://192.168.43.163:8888/auth/login # get 请求 requests.get(url) # post 请求 requests.post(url) # 任意方法 requests.request(DELETE, url) # 头 method POST requests.request(method, url, headers{Content-Type: application/json}) # 参数 json_params {username:admin,password:123456,type:1} res requests.request(method, url, json json_params) print(res.json())断言响应pip install responses_validator -i https://pypi.tuna.tsinghua.edu.cn/simpleimport requests from responses_validator import validator # 方法 url http://192.168.43.163:8888/auth/login # get 请求 requests.get(url) # post 请求 requests.post(url) # 任意方法 requests.request(DELETE, url) # 头 method POST requests.request(method, url, headers{Content-Type: application/json}) # 参数 json_params {username:admin11,password:123456,type:1} res requests.request(method, url, json json_params) print(res.json()) print(res.status_code) print(res.text) print(res.headers) # 断言 # assert res.status_code 200 # assert res.json()[code] 0 # 响应验证断言全部内容 validator( res, status_code200, json{ code:0 # user:{ # id: 1, # username: * # } } )变量提取jsonpath.json会把返回的内容转化为字典封装成一个函数import jsonpath def extract(resp,attr_name,exp): try: resp.json resp.json() except Exception: resp.json {} attr getattr(resp,attr_name) res jsonpath.jsonpath(attr,exp) return res[0] if __name__ __main__: data { code: 0, token: 1K8, user: {id: 1, username: admin, password: $2a$10$IJAu/Gpcyzk5zparRyReH.fyrMVYsOQE4V2evat0SyQPaypZMU1r2, type: 1, remarks: None}, username: admin } #jsonpath.jsonpath 返回一个列表 # [{id: 1, username: admin, password: $2a$10$IJAu/Gpcyzk5zparRyReH.fyrMVYsOQE4V2evat0SyQPaypZMU1r2, type: 1, remarks: None}] print(jsonpath.jsonpath(data,$.user)) print(jsonpath.jsonpath(data,$.user)[0][username])import requests from responses_validator import validator from extract_utils import extract # 方法 url http://192.168.43.163:8888/auth/login # get 请求 requests.get(url) # post 请求 requests.post(url) # 任意方法 requests.request(DELETE, url) # 头 method POST requests.request(method, url, headers{Content-Type: application/json}) # 参数 json_params {username:admin,password:123456,type:1} res requests.request(method, url, json json_params) print(res.json()) print(res.status_code) print(res.text) print(res.headers) # 断言 # assert res.status_code 200 # assert res.json()[code] 0 # 响应验证断言全部内容 validator( res, status_code200, json{ code:0 # user:{ # id: 1, # username: * # } } ) # 变量提取 res_data extract(res,json,$.token) print(res_data)
返回列表