一、pytest安装
插件安装:pip install -r xx.txt
- pytest
- pytest-html
- pytest-xdist
- pytest-ordering
- pytest-rerunfailures
- pytest-base-url
- allure-pytest
二、pytest默认规则
1、模块名必须以test_或_test开头
2、测试类必须以Test开头,不能有init方法
3、测试方法必须以test_开头
三、pytest运行方式
1、命令行运行方式
运行命令:pytest
参数:
-v 输出更详细的信息
-s 输出调试信息
-n 2 多线程
--reruns 2 失败用例重跑
--html 生成简易报告
eg:pytest -vs --html=./reports/report.html 根目录下的repoets文件夹中生成repoet的html报告
2、主函数的运行方式
- if __name__ == '__main__':
- pytest.main(['-vs'])
3、通过pytest.ini文件运行
- [pytest]
- # 配置参数 用例分组
- addopts = -vs -m "smoke or usermanage"
- # 配置测试用例文件夹 测试用例在test_case文件夹下
- testpaths = ./test_case
- # 配置测试用例模块的规则,以test开头可以自定义修改
- python_files = test_*.py
- # 配置测试用例类的规则
- python_classes = Test*
- # 配置测试用例方法的规则
- python_functions = test_*
- # 配置接口测试的基础路径
- base_url = http://192.168.20.102:180/
- # 给用例分组,自定义 用例上加上@pytest.mark.somking装饰器
- markers=
- smoke:冒烟测试
- usermanage:用户登录
四、pytest执行顺序
默认:从上到下执行
可以通过@pytest.mark.run(order=1)去改变执行顺序
五、pytest前置条件
- def setup_class(self):
- print("在类之前的操作")
-
- def teardown_class(self):
- print("在类之后的操作")
-
- def setup(self):
- print("在所有用例之前的前置操作")
-
- def teardown(self):
- print("在所有用例之后的后置操作")
在部分用例之前或之后执行,在类的外面使用Fixture函数
Fixture完整结构:
@pytest.fixture(scope="作用域",params="数据驱动",autouse="自动执行",ids="参数别名",name="fixture别名")
a、name使用后,原本的fixture名称已失效
b、一把情况下fixture会和conftest.py文件一起使用
c、conftest.py文件用于存放fixture,固定名称不可改变
d、conftest.py文件可以有多个
1、自动执行所有 在conftest.py文件中
- # 自动执行,所用用例之前都会执行
- @pytest.fixture(scope="class", autouse=True) # 类级别一般自动调用
- def ceshi():
- print("执行所有用例的前置")
- yield "返回值"
- print("执行所有用例的后置")
2、在某个用例中执行 将固件名称当成参数放入用例
- # 数据驱动
- def read_yaml():
- return ['张三', '李四', '王五']
- # 自动执行,所用用例之前都会执行
- @pytest.fixture(scope="function",params=read_yaml()) # 函数级别一般手动调用
- def ceshi(request):
- print("执行所有用例的前置")
- yield request.param
- print("执行所有用例的后置")
- # 通过order 123...标记去改变用例的执行顺序
- @pytest.mark.run(order=1)
- def test_get_token(self, ceshi1):
- url = "http://192.168.20.102:180/flexbase/api/w/logon/login"
- data = {
- "username": "102_180",
- "password": "1"
- }
- res = requests.request("post", url=url, data=data)
- print("返回值:"+ceshi1)
六、统一请求封装:
- class Request_Util:
- session = requests.Session()
-
- # 统一发送请求的方法
- def all_send_request(self, method, url, **kwargs):
- res = Request_Util.session.request(method, url, **kwargs)
- return res
- class TestDemo:
- # 类变量
- token = ""
-
- # 通过order 123...标记去改变用例的执行顺序
- @pytest.mark.run(order=1)
- def test_get_token(self):
- url = "http://192.168.20.102:180/flexbase/api/w/logon/login"
- data = {
- "username": "102_180",
- "password": "1"
- }
- res = Request_Util().all_send_request("post", url=url, data=data)
- print(res.json())
- TestDemo.token = res.json()['data']['token'] # json提取器获取token
- print(TestDemo.token)