1、pytest是什么?
pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高。
2、pytest的特点
-
简单灵活,容易上手
-
支持参数化
-
能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appium等自动化测试,接口自动化测试(pytest+request)
-
pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)等
-
测试用例的skip和xfail处理
-
可以很好的和Jenkins集成
-
report框架----allure 也支持了pytest
3、pytest安装
1.安装
pip install pytest
2.验证安装,查看pytest版本
pytest --version
3.pytest文档和测试用例编写规则
官方文档:https://docs.pytest.org/en/latest/contents.html
- 测试文件以test_开头(以_test结尾也行)
- 测试类以Test开头,并且不能带有init方法
- 测试函数以test开头
- 断言使用基本的assert即可
4、实战用例
import pytest, requests
class TestLogin:
# 1.正确流程
def test_login01(self):
response = requests.post(url='http://127.0.0.1:5000/user_login',
data={"username": "xiaohua", "mima": "a123456"})
res = response.json()
print(res)
assert {'code': '1000', 'msg': '登录成功'} == res
# 2.用户名错误
def test_login02(self):
response = requests.post(url='http://127.0.0.1:5000/user_login',
data={"username": "xiaoniu1", "mima": "a123456"})
res = response.json()
print(res)
assert "用户名或密码错误" in str(res)
# 3.用户名为空
def test_login03(self):
response = requests.post(url='http://127.0.0.1:5000/user_login',
data={"username": "", "mima": "a123456"})
res = response.json()
print(res)
assert res["msg"] == "用户名不能为空!" and res["code"] == "1003" # 断言响应结果中的value值是否和预期结果一致
# 4.密码错误
def test_login04(self):
response = requests.post(url='http://127.0.0.1:5000/user_login',
data={"username": "xiaoniu", "mima": "a1234567"})
res = response.json()
print(res)
assert {'code': '1005', 'msg': '用户名或密码错误!'} == res
# 5.密码为空
def test_login05(self):
response = requests.post(url='http://127.0.0.1:5000/user_login',
data={"username": "xiaoniu", "mima": ""})
res = response.json()
print(res)
assert {'code': '1004', 'msg': '密码不能为空!'} == res
if __name__ == "__main__":
# 知识点1: 运行该模块下的所有测试用例 -s -v -q
pytest.main(['-vs','./test_pytest01.py']) # 运行指定模块
# 知识点2: -s -v -q的应用
# pytest.main(['-s', './test_pytest01.py']) # 运行指定模块, -s: 显示程序中的打印信息
# pytest.main(['-v', './test_pytest01.py']) # 运行指定模块, -v: 丰富信息模式, 输出更详细的用例执行信息
# pytest.main(['-q', './test_pytest01.py']) # 运行指定模块, -q: 静默模式,只显示运行结果
# 知识点3: 运行模块中的某个类
# pytest.main(['./test_pytest01.py::TestLogin']) # 运行类中的指定用例
# 知识点4: 运行某个测试类中的指定用例
# pytest.main(['./test_pytest01.py::TestLogin::test_login05']) # 运行模块中的指定用例
# pytest.main(['-vs', './test_pytest01.py::TestLogin::test_login05'])
# 知识点5:运行某个目录下的所有测试用例
# pytest.main(['./']) # 运行当前目录下所有(test_*.py 和 *_test.py)