Pytest测试框架(1)
1. 安装pytest及其插件
pip install pytest
pip install pytest-sugar(更好展示测试进度), pip install pytest-allure(生成报告), pip install pytest_xdist(多CPU分发,加快执行速度)
2.pycharm里设置
file-settings-tools-Python integrated tools,default test runner 选pytest
3. 新建工程、py文件写测试代码
4. 运行(多种方式)
(1)CMD窗口或pycharm Terminal中运行: pytest -v test_01.py
(2).py文件中写:import pytest if __name__ == '__main__': pytest.main(['-v','test_01.py'])
(3)run configuration中配置好,点run三角运行
(4)py文件空白处,右击-run xxx.py
5. pytest的setup和teardown函数:
分为模块级(文件级) 函数级 类级 方法级。函数名称都是定死的,分别:setup_module() teardown_module() setup_function() teardown_function() setup_class() teardown_class() setup_method()和teardown_method()
6. pytest的标签(可按需选择需要运行、或跳过的用例)
@pytest.mark.skip @pytest.mark.skipif @pytest.mark.android @pytest.mark.ios
pytest -v ....py -m android (只运行android标签的用例)
对未修复的,执行肯定也失败的,可用@pytest.mark.xfail去跳过
7. fixture的使用(pytest最闪耀功能)--灵活的进行测试前的配置/数据准备/依赖和销毁(完美替代setup teardown函数)
如有的用例需要登录执行,有的不需要登录运行,setup teardown做不到,而fixture可以
@pytest.fixture(scope= autouse=) //默认是function级,scope=module/class/session. 还可设置autouse=True,则默认每次测试用例执行前都先执行该fixture
- function:每一个函数或方法都会调用
- class:每一个类调用一次,一个类可以有多个方法
- module:每一个.py文件调用一次,该文件内又有多个function和class
- session:是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
# (1)测试前的工作举例(一般将公共的这些fixture都放conftest.py文件里,作为一个数据共享文件,且该文件可放不同位置起到不同范围的共享作用)
@pytest.fixture()
def login():
print('输入账号密码登录') # 这三行fixture定义,一般放conftest.py里
def test_cart(login):
print('登录后加购物车')
# (2)测试后的工作--通过yield实现
@pytest.fixture(scope='session')
def login():
print('输入账号密码登录')
yield
print('退出登录')
# (3)使用fixture传参
@pytest.fixture(params=[1,2,3,'lili'])
def prepare_data(request):
return request.param // request参数及request.param是固定写法
def test_one(prepare_data):
print('testdata: %s' %prepare_data)
//上述代码运行会发现test_one执行了4次,即t通过fixture传递参数,达到每个参数驱动测试用例执行一次的目的
#(4)使用多个fixture及fixture之间相互调用
@pytest.fixture()
def login(openBrowser):
print('输入账号密码登录') # fixture定义,一般放conftest.py里
@pytest.fixture()
def openBrowser():
print('打开浏览器') #fixture定义,一般放conftest.py里
def test_01(login): // 调用fixture方法1:直接在测试用例函数参数里写fixture名字
print('登录后加购物车')
@pytest.mark.usefixtures('login') // 调用fixture方法2:用装饰器
def test_02():
print('登录后付款')
#(5)fixture自动应用(不需要传参或用装饰器调用fixture),每条用例都要先执行fixture,无特例时
使用fixture中的autouse=True实现,即定义fixture时就写上:
@pytest.fixture(autouse=True)
def login(openBrowser):
print('输入账号密码登录') # fixture定义,一般放conftest.py里

浙公网安备 33010602011771号