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_demo.py
(2).py文件中写: if __name__ == ‘__main__‘: pytest.main([‘-v‘,‘test_01.py‘])
(3)run configuration中配置好,点run三角运行
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() //默认是function级,scope=module/class/session
# (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次,即每个参数驱动运行了一次
原文:https://www.cnblogs.com/sunnyday21/p/14738753.html